Bug Summary

File:build/source/clang/lib/Sema/SemaOverload.cpp
Warning:line 14013, column 21
Although the value stored to 'RHS' is used in the enclosing expression, the value is never actually read from 'RHS'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1668078801 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-11-10-135928-647445-1 -x c++ /build/source/clang/lib/Sema/SemaOverload.cpp
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/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DependenceFlags.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/Type.h"
22#include "clang/AST/TypeOrdering.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/DiagnosticOptions.h"
25#include "clang/Basic/OperatorKinds.h"
26#include "clang/Basic/PartialDiagnostic.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Sema/Initialization.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Overload.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/Template.h"
34#include "clang/Sema/TemplateDeduction.h"
35#include "llvm/ADT/DenseSet.h"
36#include "llvm/ADT/Optional.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallString.h"
40#include "llvm/Support/Casting.h"
41#include <algorithm>
42#include <cstdlib>
43
44using namespace clang;
45using namespace sema;
46
47using AllowedExplicit = Sema::AllowedExplicit;
48
49static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
50 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
51 return P->hasAttr<PassObjectSizeAttr>();
52 });
53}
54
55/// A convenience routine for creating a decayed reference to a function.
56static ExprResult CreateFunctionRefExpr(
57 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
58 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
59 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
60 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
61 return ExprError();
62 // If FoundDecl is different from Fn (such as if one is a template
63 // and the other a specialization), make sure DiagnoseUseOfDecl is
64 // called on both.
65 // FIXME: This would be more comprehensively addressed by modifying
66 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
67 // being used.
68 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
69 return ExprError();
70 DeclRefExpr *DRE = new (S.Context)
71 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
72 if (HadMultipleCandidates)
73 DRE->setHadMultipleCandidates(true);
74
75 S.MarkDeclRefReferenced(DRE, Base);
76 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
77 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
78 S.ResolveExceptionSpec(Loc, FPT);
79 DRE->setType(Fn->getType());
80 }
81 }
82 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
83 CK_FunctionToPointerDecay);
84}
85
86static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
87 bool InOverloadResolution,
88 StandardConversionSequence &SCS,
89 bool CStyle,
90 bool AllowObjCWritebackConversion);
91
92static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
93 QualType &ToType,
94 bool InOverloadResolution,
95 StandardConversionSequence &SCS,
96 bool CStyle);
97static OverloadingResult
98IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
99 UserDefinedConversionSequence& User,
100 OverloadCandidateSet& Conversions,
101 AllowedExplicit AllowExplicit,
102 bool AllowObjCConversionOnExplicit);
103
104static ImplicitConversionSequence::CompareKind
105CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
106 const StandardConversionSequence& SCS1,
107 const StandardConversionSequence& SCS2);
108
109static ImplicitConversionSequence::CompareKind
110CompareQualificationConversions(Sema &S,
111 const StandardConversionSequence& SCS1,
112 const StandardConversionSequence& SCS2);
113
114static ImplicitConversionSequence::CompareKind
115CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
118
119/// GetConversionRank - Retrieve the implicit conversion rank
120/// corresponding to the given implicit conversion kind.
121ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
122 static const ImplicitConversionRank
123 Rank[(int)ICK_Num_Conversion_Kinds] = {
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Promotion,
131 ICR_Promotion,
132 ICR_Promotion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_OCL_Scalar_Widening,
145 ICR_Complex_Real_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Writeback_Conversion,
149 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
150 // it was omitted by the patch that added
151 // ICK_Zero_Event_Conversion
152 ICR_C_Conversion,
153 ICR_C_Conversion_Extension
154 };
155 return Rank[(int)Kind];
156}
157
158/// GetImplicitConversionName - Return the name of this kind of
159/// implicit conversion.
160static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
161 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
162 "No conversion",
163 "Lvalue-to-rvalue",
164 "Array-to-pointer",
165 "Function-to-pointer",
166 "Function pointer conversion",
167 "Qualification",
168 "Integral promotion",
169 "Floating point promotion",
170 "Complex promotion",
171 "Integral conversion",
172 "Floating conversion",
173 "Complex conversion",
174 "Floating-integral conversion",
175 "Pointer conversion",
176 "Pointer-to-member conversion",
177 "Boolean conversion",
178 "Compatible-types conversion",
179 "Derived-to-base conversion",
180 "Vector conversion",
181 "SVE Vector conversion",
182 "Vector splat",
183 "Complex-real conversion",
184 "Block Pointer conversion",
185 "Transparent Union Conversion",
186 "Writeback conversion",
187 "OpenCL Zero Event Conversion",
188 "C specific type conversion",
189 "Incompatible pointer conversion"
190 };
191 return Name[Kind];
192}
193
194/// StandardConversionSequence - Set the standard conversion
195/// sequence to the identity conversion.
196void StandardConversionSequence::setAsIdentityConversion() {
197 First = ICK_Identity;
198 Second = ICK_Identity;
199 Third = ICK_Identity;
200 DeprecatedStringLiteralToCharPtr = false;
201 QualificationIncludesObjCLifetime = false;
202 ReferenceBinding = false;
203 DirectBinding = false;
204 IsLvalueReference = true;
205 BindsToFunctionLvalue = false;
206 BindsToRvalue = false;
207 BindsImplicitObjectArgumentWithoutRefQualifier = false;
208 ObjCLifetimeConversionBinding = false;
209 CopyConstructor = nullptr;
210}
211
212/// getRank - Retrieve the rank of this standard conversion sequence
213/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
214/// implicit conversions.
215ImplicitConversionRank StandardConversionSequence::getRank() const {
216 ImplicitConversionRank Rank = ICR_Exact_Match;
217 if (GetConversionRank(First) > Rank)
218 Rank = GetConversionRank(First);
219 if (GetConversionRank(Second) > Rank)
220 Rank = GetConversionRank(Second);
221 if (GetConversionRank(Third) > Rank)
222 Rank = GetConversionRank(Third);
223 return Rank;
224}
225
226/// isPointerConversionToBool - Determines whether this conversion is
227/// a conversion of a pointer or pointer-to-member to bool. This is
228/// used as part of the ranking of standard conversion sequences
229/// (C++ 13.3.3.2p4).
230bool StandardConversionSequence::isPointerConversionToBool() const {
231 // Note that FromType has not necessarily been transformed by the
232 // array-to-pointer or function-to-pointer implicit conversions, so
233 // check for their presence as well as checking whether FromType is
234 // a pointer.
235 if (getToType(1)->isBooleanType() &&
236 (getFromType()->isPointerType() ||
237 getFromType()->isMemberPointerType() ||
238 getFromType()->isObjCObjectPointerType() ||
239 getFromType()->isBlockPointerType() ||
240 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
241 return true;
242
243 return false;
244}
245
246/// isPointerConversionToVoidPointer - Determines whether this
247/// conversion is a conversion of a pointer to a void pointer. This is
248/// used as part of the ranking of standard conversion sequences (C++
249/// 13.3.3.2p4).
250bool
251StandardConversionSequence::
252isPointerConversionToVoidPointer(ASTContext& Context) const {
253 QualType FromType = getFromType();
254 QualType ToType = getToType(1);
255
256 // Note that FromType has not necessarily been transformed by the
257 // array-to-pointer implicit conversion, so check for its presence
258 // and redo the conversion to get a pointer.
259 if (First == ICK_Array_To_Pointer)
260 FromType = Context.getArrayDecayedType(FromType);
261
262 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
263 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
264 return ToPtrType->getPointeeType()->isVoidType();
265
266 return false;
267}
268
269/// Skip any implicit casts which could be either part of a narrowing conversion
270/// or after one in an implicit conversion.
271static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
272 const Expr *Converted) {
273 // We can have cleanups wrapping the converted expression; these need to be
274 // preserved so that destructors run if necessary.
275 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
276 Expr *Inner =
277 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
278 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
279 EWC->getObjects());
280 }
281
282 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
283 switch (ICE->getCastKind()) {
284 case CK_NoOp:
285 case CK_IntegralCast:
286 case CK_IntegralToBoolean:
287 case CK_IntegralToFloating:
288 case CK_BooleanToSignedIntegral:
289 case CK_FloatingToIntegral:
290 case CK_FloatingToBoolean:
291 case CK_FloatingCast:
292 Converted = ICE->getSubExpr();
293 continue;
294
295 default:
296 return Converted;
297 }
298 }
299
300 return Converted;
301}
302
303/// Check if this standard conversion sequence represents a narrowing
304/// conversion, according to C++11 [dcl.init.list]p7.
305///
306/// \param Ctx The AST context.
307/// \param Converted The result of applying this standard conversion sequence.
308/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
309/// value of the expression prior to the narrowing conversion.
310/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
311/// type of the expression prior to the narrowing conversion.
312/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
313/// from floating point types to integral types should be ignored.
314NarrowingKind StandardConversionSequence::getNarrowingKind(
315 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
316 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
317 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus &&
"narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "clang/lib/Sema/SemaOverload.cpp", 317, __extension__ __PRETTY_FUNCTION__
))
;
318
319 // C++11 [dcl.init.list]p7:
320 // A narrowing conversion is an implicit conversion ...
321 QualType FromType = getToType(0);
322 QualType ToType = getToType(1);
323
324 // A conversion to an enumeration type is narrowing if the conversion to
325 // the underlying type is narrowing. This only arises for expressions of
326 // the form 'Enum{init}'.
327 if (auto *ET = ToType->getAs<EnumType>())
328 ToType = ET->getDecl()->getIntegerType();
329
330 switch (Second) {
331 // 'bool' is an integral type; dispatch to the right place to handle it.
332 case ICK_Boolean_Conversion:
333 if (FromType->isRealFloatingType())
334 goto FloatingIntegralConversion;
335 if (FromType->isIntegralOrUnscopedEnumerationType())
336 goto IntegralConversion;
337 // -- from a pointer type or pointer-to-member type to bool, or
338 return NK_Type_Narrowing;
339
340 // -- from a floating-point type to an integer type, or
341 //
342 // -- from an integer type or unscoped enumeration type to a floating-point
343 // type, except where the source is a constant expression and the actual
344 // value after conversion will fit into the target type and will produce
345 // the original value when converted back to the original type, or
346 case ICK_Floating_Integral:
347 FloatingIntegralConversion:
348 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
349 return NK_Type_Narrowing;
350 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
351 ToType->isRealFloatingType()) {
352 if (IgnoreFloatToIntegralConversion)
353 return NK_Not_Narrowing;
354 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
355 assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression"
) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "clang/lib/Sema/SemaOverload.cpp", 355, __extension__ __PRETTY_FUNCTION__
))
;
356
357 // If it's value-dependent, we can't tell whether it's narrowing.
358 if (Initializer->isValueDependent())
359 return NK_Dependent_Narrowing;
360
361 if (Optional<llvm::APSInt> IntConstantValue =
362 Initializer->getIntegerConstantExpr(Ctx)) {
363 // Convert the integer to the floating type.
364 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
365 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
366 llvm::APFloat::rmNearestTiesToEven);
367 // And back.
368 llvm::APSInt ConvertedValue = *IntConstantValue;
369 bool ignored;
370 Result.convertToInteger(ConvertedValue,
371 llvm::APFloat::rmTowardZero, &ignored);
372 // If the resulting value is different, this was a narrowing conversion.
373 if (*IntConstantValue != ConvertedValue) {
374 ConstantValue = APValue(*IntConstantValue);
375 ConstantType = Initializer->getType();
376 return NK_Constant_Narrowing;
377 }
378 } else {
379 // Variables are always narrowings.
380 return NK_Variable_Narrowing;
381 }
382 }
383 return NK_Not_Narrowing;
384
385 // -- from long double to double or float, or from double to float, except
386 // where the source is a constant expression and the actual value after
387 // conversion is within the range of values that can be represented (even
388 // if it cannot be represented exactly), or
389 case ICK_Floating_Conversion:
390 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
391 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
392 // FromType is larger than ToType.
393 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
394
395 // If it's value-dependent, we can't tell whether it's narrowing.
396 if (Initializer->isValueDependent())
397 return NK_Dependent_Narrowing;
398
399 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
400 // Constant!
401 assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0
) : __assert_fail ("ConstantValue.isFloat()", "clang/lib/Sema/SemaOverload.cpp"
, 401, __extension__ __PRETTY_FUNCTION__))
;
402 llvm::APFloat FloatVal = ConstantValue.getFloat();
403 // Convert the source value into the target type.
404 bool ignored;
405 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
406 Ctx.getFloatTypeSemantics(ToType),
407 llvm::APFloat::rmNearestTiesToEven, &ignored);
408 // If there was no overflow, the source value is within the range of
409 // values that can be represented.
410 if (ConvertStatus & llvm::APFloat::opOverflow) {
411 ConstantType = Initializer->getType();
412 return NK_Constant_Narrowing;
413 }
414 } else {
415 return NK_Variable_Narrowing;
416 }
417 }
418 return NK_Not_Narrowing;
419
420 // -- from an integer type or unscoped enumeration type to an integer type
421 // that cannot represent all the values of the original type, except where
422 // the source is a constant expression and the actual value after
423 // conversion will fit into the target type and will produce the original
424 // value when converted back to the original type.
425 case ICK_Integral_Conversion:
426 IntegralConversion: {
427 assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 427, __extension__ __PRETTY_FUNCTION__
))
;
428 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 428, __extension__ __PRETTY_FUNCTION__
))
;
429 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
430 const unsigned FromWidth = Ctx.getIntWidth(FromType);
431 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
432 const unsigned ToWidth = Ctx.getIntWidth(ToType);
433
434 if (FromWidth > ToWidth ||
435 (FromWidth == ToWidth && FromSigned != ToSigned) ||
436 (FromSigned && !ToSigned)) {
437 // Not all values of FromType can be represented in ToType.
438 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439
440 // If it's value-dependent, we can't tell whether it's narrowing.
441 if (Initializer->isValueDependent())
442 return NK_Dependent_Narrowing;
443
444 Optional<llvm::APSInt> OptInitializerValue;
445 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
446 // Such conversions on variables are always narrowing.
447 return NK_Variable_Narrowing;
448 }
449 llvm::APSInt &InitializerValue = *OptInitializerValue;
450 bool Narrowing = false;
451 if (FromWidth < ToWidth) {
452 // Negative -> unsigned is narrowing. Otherwise, more bits is never
453 // narrowing.
454 if (InitializerValue.isSigned() && InitializerValue.isNegative())
455 Narrowing = true;
456 } else {
457 // Add a bit to the InitializerValue so we don't have to worry about
458 // signed vs. unsigned comparisons.
459 InitializerValue = InitializerValue.extend(
460 InitializerValue.getBitWidth() + 1);
461 // Convert the initializer to and from the target width and signed-ness.
462 llvm::APSInt ConvertedValue = InitializerValue;
463 ConvertedValue = ConvertedValue.trunc(ToWidth);
464 ConvertedValue.setIsSigned(ToSigned);
465 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
466 ConvertedValue.setIsSigned(InitializerValue.isSigned());
467 // If the result is different, this was a narrowing conversion.
468 if (ConvertedValue != InitializerValue)
469 Narrowing = true;
470 }
471 if (Narrowing) {
472 ConstantType = Initializer->getType();
473 ConstantValue = APValue(InitializerValue);
474 return NK_Constant_Narrowing;
475 }
476 }
477 return NK_Not_Narrowing;
478 }
479
480 default:
481 // Other kinds of conversions are not narrowings.
482 return NK_Not_Narrowing;
483 }
484}
485
486/// dump - Print this standard conversion sequence to standard
487/// error. Useful for debugging overloading issues.
488LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
489 raw_ostream &OS = llvm::errs();
490 bool PrintedSomething = false;
491 if (First != ICK_Identity) {
492 OS << GetImplicitConversionName(First);
493 PrintedSomething = true;
494 }
495
496 if (Second != ICK_Identity) {
497 if (PrintedSomething) {
498 OS << " -> ";
499 }
500 OS << GetImplicitConversionName(Second);
501
502 if (CopyConstructor) {
503 OS << " (by copy constructor)";
504 } else if (DirectBinding) {
505 OS << " (direct reference binding)";
506 } else if (ReferenceBinding) {
507 OS << " (reference binding)";
508 }
509 PrintedSomething = true;
510 }
511
512 if (Third != ICK_Identity) {
513 if (PrintedSomething) {
514 OS << " -> ";
515 }
516 OS << GetImplicitConversionName(Third);
517 PrintedSomething = true;
518 }
519
520 if (!PrintedSomething) {
521 OS << "No conversions required";
522 }
523}
524
525/// dump - Print this user-defined conversion sequence to standard
526/// error. Useful for debugging overloading issues.
527void UserDefinedConversionSequence::dump() const {
528 raw_ostream &OS = llvm::errs();
529 if (Before.First || Before.Second || Before.Third) {
530 Before.dump();
531 OS << " -> ";
532 }
533 if (ConversionFunction)
534 OS << '\'' << *ConversionFunction << '\'';
535 else
536 OS << "aggregate initialization";
537 if (After.First || After.Second || After.Third) {
538 OS << " -> ";
539 After.dump();
540 }
541}
542
543/// dump - Print this implicit conversion sequence to standard
544/// error. Useful for debugging overloading issues.
545void ImplicitConversionSequence::dump() const {
546 raw_ostream &OS = llvm::errs();
547 if (hasInitializerListContainerType())
548 OS << "Worst list element conversion: ";
549 switch (ConversionKind) {
550 case StandardConversion:
551 OS << "Standard conversion: ";
552 Standard.dump();
553 break;
554 case UserDefinedConversion:
555 OS << "User-defined conversion: ";
556 UserDefined.dump();
557 break;
558 case EllipsisConversion:
559 OS << "Ellipsis conversion";
560 break;
561 case AmbiguousConversion:
562 OS << "Ambiguous conversion";
563 break;
564 case BadConversion:
565 OS << "Bad conversion";
566 break;
567 }
568
569 OS << "\n";
570}
571
572void AmbiguousConversionSequence::construct() {
573 new (&conversions()) ConversionSet();
574}
575
576void AmbiguousConversionSequence::destruct() {
577 conversions().~ConversionSet();
578}
579
580void
581AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
582 FromTypePtr = O.FromTypePtr;
583 ToTypePtr = O.ToTypePtr;
584 new (&conversions()) ConversionSet(O.conversions());
585}
586
587namespace {
588 // Structure used by DeductionFailureInfo to store
589 // template argument information.
590 struct DFIArguments {
591 TemplateArgument FirstArg;
592 TemplateArgument SecondArg;
593 };
594 // Structure used by DeductionFailureInfo to store
595 // template parameter and template argument information.
596 struct DFIParamWithArguments : DFIArguments {
597 TemplateParameter Param;
598 };
599 // Structure used by DeductionFailureInfo to store template argument
600 // information and the index of the problematic call argument.
601 struct DFIDeducedMismatchArgs : DFIArguments {
602 TemplateArgumentList *TemplateArgs;
603 unsigned CallArgIndex;
604 };
605 // Structure used by DeductionFailureInfo to store information about
606 // unsatisfied constraints.
607 struct CNSInfo {
608 TemplateArgumentList *TemplateArgs;
609 ConstraintSatisfaction Satisfaction;
610 };
611}
612
613/// Convert from Sema's representation of template deduction information
614/// to the form used in overload-candidate information.
615DeductionFailureInfo
616clang::MakeDeductionFailureInfo(ASTContext &Context,
617 Sema::TemplateDeductionResult TDK,
618 TemplateDeductionInfo &Info) {
619 DeductionFailureInfo Result;
620 Result.Result = static_cast<unsigned>(TDK);
621 Result.HasDiagnostic = false;
622 switch (TDK) {
623 case Sema::TDK_Invalid:
624 case Sema::TDK_InstantiationDepth:
625 case Sema::TDK_TooManyArguments:
626 case Sema::TDK_TooFewArguments:
627 case Sema::TDK_MiscellaneousDeductionFailure:
628 case Sema::TDK_CUDATargetMismatch:
629 Result.Data = nullptr;
630 break;
631
632 case Sema::TDK_Incomplete:
633 case Sema::TDK_InvalidExplicitArguments:
634 Result.Data = Info.Param.getOpaqueValue();
635 break;
636
637 case Sema::TDK_DeducedMismatch:
638 case Sema::TDK_DeducedMismatchNested: {
639 // FIXME: Should allocate from normal heap so that we can free this later.
640 auto *Saved = new (Context) DFIDeducedMismatchArgs;
641 Saved->FirstArg = Info.FirstArg;
642 Saved->SecondArg = Info.SecondArg;
643 Saved->TemplateArgs = Info.takeSugared();
644 Saved->CallArgIndex = Info.CallArgIndex;
645 Result.Data = Saved;
646 break;
647 }
648
649 case Sema::TDK_NonDeducedMismatch: {
650 // FIXME: Should allocate from normal heap so that we can free this later.
651 DFIArguments *Saved = new (Context) DFIArguments;
652 Saved->FirstArg = Info.FirstArg;
653 Saved->SecondArg = Info.SecondArg;
654 Result.Data = Saved;
655 break;
656 }
657
658 case Sema::TDK_IncompletePack:
659 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
660 case Sema::TDK_Inconsistent:
661 case Sema::TDK_Underqualified: {
662 // FIXME: Should allocate from normal heap so that we can free this later.
663 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
664 Saved->Param = Info.Param;
665 Saved->FirstArg = Info.FirstArg;
666 Saved->SecondArg = Info.SecondArg;
667 Result.Data = Saved;
668 break;
669 }
670
671 case Sema::TDK_SubstitutionFailure:
672 Result.Data = Info.takeSugared();
673 if (Info.hasSFINAEDiagnostic()) {
674 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
675 SourceLocation(), PartialDiagnostic::NullDiagnostic());
676 Info.takeSFINAEDiagnostic(*Diag);
677 Result.HasDiagnostic = true;
678 }
679 break;
680
681 case Sema::TDK_ConstraintsNotSatisfied: {
682 CNSInfo *Saved = new (Context) CNSInfo;
683 Saved->TemplateArgs = Info.takeSugared();
684 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
685 Result.Data = Saved;
686 break;
687 }
688
689 case Sema::TDK_Success:
690 case Sema::TDK_NonDependentConversionFailure:
691 case Sema::TDK_AlreadyDiagnosed:
692 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "clang/lib/Sema/SemaOverload.cpp"
, 692)
;
693 }
694
695 return Result;
696}
697
698void DeductionFailureInfo::Destroy() {
699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
700 case Sema::TDK_Success:
701 case Sema::TDK_Invalid:
702 case Sema::TDK_InstantiationDepth:
703 case Sema::TDK_Incomplete:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_InvalidExplicitArguments:
707 case Sema::TDK_CUDATargetMismatch:
708 case Sema::TDK_NonDependentConversionFailure:
709 break;
710
711 case Sema::TDK_IncompletePack:
712 case Sema::TDK_Inconsistent:
713 case Sema::TDK_Underqualified:
714 case Sema::TDK_DeducedMismatch:
715 case Sema::TDK_DeducedMismatchNested:
716 case Sema::TDK_NonDeducedMismatch:
717 // FIXME: Destroy the data?
718 Data = nullptr;
719 break;
720
721 case Sema::TDK_SubstitutionFailure:
722 // FIXME: Destroy the template argument list?
723 Data = nullptr;
724 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
725 Diag->~PartialDiagnosticAt();
726 HasDiagnostic = false;
727 }
728 break;
729
730 case Sema::TDK_ConstraintsNotSatisfied:
731 // FIXME: Destroy the template argument list?
732 Data = nullptr;
733 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
734 Diag->~PartialDiagnosticAt();
735 HasDiagnostic = false;
736 }
737 break;
738
739 // Unhandled
740 case Sema::TDK_MiscellaneousDeductionFailure:
741 case Sema::TDK_AlreadyDiagnosed:
742 break;
743 }
744}
745
746PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
747 if (HasDiagnostic)
748 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
749 return nullptr;
750}
751
752TemplateParameter DeductionFailureInfo::getTemplateParameter() {
753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754 case Sema::TDK_Success:
755 case Sema::TDK_Invalid:
756 case Sema::TDK_InstantiationDepth:
757 case Sema::TDK_TooManyArguments:
758 case Sema::TDK_TooFewArguments:
759 case Sema::TDK_SubstitutionFailure:
760 case Sema::TDK_DeducedMismatch:
761 case Sema::TDK_DeducedMismatchNested:
762 case Sema::TDK_NonDeducedMismatch:
763 case Sema::TDK_CUDATargetMismatch:
764 case Sema::TDK_NonDependentConversionFailure:
765 case Sema::TDK_ConstraintsNotSatisfied:
766 return TemplateParameter();
767
768 case Sema::TDK_Incomplete:
769 case Sema::TDK_InvalidExplicitArguments:
770 return TemplateParameter::getFromOpaqueValue(Data);
771
772 case Sema::TDK_IncompletePack:
773 case Sema::TDK_Inconsistent:
774 case Sema::TDK_Underqualified:
775 return static_cast<DFIParamWithArguments*>(Data)->Param;
776
777 // Unhandled
778 case Sema::TDK_MiscellaneousDeductionFailure:
779 case Sema::TDK_AlreadyDiagnosed:
780 break;
781 }
782
783 return TemplateParameter();
784}
785
786TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
787 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
788 case Sema::TDK_Success:
789 case Sema::TDK_Invalid:
790 case Sema::TDK_InstantiationDepth:
791 case Sema::TDK_TooManyArguments:
792 case Sema::TDK_TooFewArguments:
793 case Sema::TDK_Incomplete:
794 case Sema::TDK_IncompletePack:
795 case Sema::TDK_InvalidExplicitArguments:
796 case Sema::TDK_Inconsistent:
797 case Sema::TDK_Underqualified:
798 case Sema::TDK_NonDeducedMismatch:
799 case Sema::TDK_CUDATargetMismatch:
800 case Sema::TDK_NonDependentConversionFailure:
801 return nullptr;
802
803 case Sema::TDK_DeducedMismatch:
804 case Sema::TDK_DeducedMismatchNested:
805 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
806
807 case Sema::TDK_SubstitutionFailure:
808 return static_cast<TemplateArgumentList*>(Data);
809
810 case Sema::TDK_ConstraintsNotSatisfied:
811 return static_cast<CNSInfo*>(Data)->TemplateArgs;
812
813 // Unhandled
814 case Sema::TDK_MiscellaneousDeductionFailure:
815 case Sema::TDK_AlreadyDiagnosed:
816 break;
817 }
818
819 return nullptr;
820}
821
822const TemplateArgument *DeductionFailureInfo::getFirstArg() {
823 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
824 case Sema::TDK_Success:
825 case Sema::TDK_Invalid:
826 case Sema::TDK_InstantiationDepth:
827 case Sema::TDK_Incomplete:
828 case Sema::TDK_TooManyArguments:
829 case Sema::TDK_TooFewArguments:
830 case Sema::TDK_InvalidExplicitArguments:
831 case Sema::TDK_SubstitutionFailure:
832 case Sema::TDK_CUDATargetMismatch:
833 case Sema::TDK_NonDependentConversionFailure:
834 case Sema::TDK_ConstraintsNotSatisfied:
835 return nullptr;
836
837 case Sema::TDK_IncompletePack:
838 case Sema::TDK_Inconsistent:
839 case Sema::TDK_Underqualified:
840 case Sema::TDK_DeducedMismatch:
841 case Sema::TDK_DeducedMismatchNested:
842 case Sema::TDK_NonDeducedMismatch:
843 return &static_cast<DFIArguments*>(Data)->FirstArg;
844
845 // Unhandled
846 case Sema::TDK_MiscellaneousDeductionFailure:
847 case Sema::TDK_AlreadyDiagnosed:
848 break;
849 }
850
851 return nullptr;
852}
853
854const TemplateArgument *DeductionFailureInfo::getSecondArg() {
855 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
856 case Sema::TDK_Success:
857 case Sema::TDK_Invalid:
858 case Sema::TDK_InstantiationDepth:
859 case Sema::TDK_Incomplete:
860 case Sema::TDK_IncompletePack:
861 case Sema::TDK_TooManyArguments:
862 case Sema::TDK_TooFewArguments:
863 case Sema::TDK_InvalidExplicitArguments:
864 case Sema::TDK_SubstitutionFailure:
865 case Sema::TDK_CUDATargetMismatch:
866 case Sema::TDK_NonDependentConversionFailure:
867 case Sema::TDK_ConstraintsNotSatisfied:
868 return nullptr;
869
870 case Sema::TDK_Inconsistent:
871 case Sema::TDK_Underqualified:
872 case Sema::TDK_DeducedMismatch:
873 case Sema::TDK_DeducedMismatchNested:
874 case Sema::TDK_NonDeducedMismatch:
875 return &static_cast<DFIArguments*>(Data)->SecondArg;
876
877 // Unhandled
878 case Sema::TDK_MiscellaneousDeductionFailure:
879 case Sema::TDK_AlreadyDiagnosed:
880 break;
881 }
882
883 return nullptr;
884}
885
886llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
887 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
888 case Sema::TDK_DeducedMismatch:
889 case Sema::TDK_DeducedMismatchNested:
890 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
891
892 default:
893 return llvm::None;
894 }
895}
896
897static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
898 const FunctionDecl *Y) {
899 if (!X || !Y)
900 return false;
901 if (X->getNumParams() != Y->getNumParams())
902 return false;
903 for (unsigned I = 0; I < X->getNumParams(); ++I)
904 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
905 Y->getParamDecl(I)->getType()))
906 return false;
907 if (auto *FTX = X->getDescribedFunctionTemplate()) {
908 auto *FTY = Y->getDescribedFunctionTemplate();
909 if (!FTY)
910 return false;
911 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
912 FTY->getTemplateParameters()))
913 return false;
914 }
915 return true;
916}
917
918static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
919 Expr *FirstOperand, FunctionDecl *EqFD) {
920 assert(EqFD->getOverloadedOperator() ==(static_cast <bool> (EqFD->getOverloadedOperator() ==
OverloadedOperatorKind::OO_EqualEqual) ? void (0) : __assert_fail
("EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual"
, "clang/lib/Sema/SemaOverload.cpp", 921, __extension__ __PRETTY_FUNCTION__
))
921 OverloadedOperatorKind::OO_EqualEqual)(static_cast <bool> (EqFD->getOverloadedOperator() ==
OverloadedOperatorKind::OO_EqualEqual) ? void (0) : __assert_fail
("EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual"
, "clang/lib/Sema/SemaOverload.cpp", 921, __extension__ __PRETTY_FUNCTION__
))
;
922 // C++2a [over.match.oper]p4:
923 // A non-template function or function template F named operator== is a
924 // rewrite target with first operand o unless a search for the name operator!=
925 // in the scope S from the instantiation context of the operator expression
926 // finds a function or function template that would correspond
927 // ([basic.scope.scope]) to F if its name were operator==, where S is the
928 // scope of the class type of o if F is a class member, and the namespace
929 // scope of which F is a member otherwise. A function template specialization
930 // named operator== is a rewrite target if its function template is a rewrite
931 // target.
932 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
933 OverloadedOperatorKind::OO_ExclaimEqual);
934 if (isa<CXXMethodDecl>(EqFD)) {
935 // If F is a class member, search scope is class type of first operand.
936 QualType RHS = FirstOperand->getType();
937 auto *RHSRec = RHS->getAs<RecordType>();
938 if (!RHSRec)
939 return true;
940 LookupResult Members(S, NotEqOp, OpLoc,
941 Sema::LookupNameKind::LookupMemberName);
942 S.LookupQualifiedName(Members, RHSRec->getDecl());
943 Members.suppressDiagnostics();
944 for (NamedDecl *Op : Members)
945 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
946 return false;
947 return true;
948 }
949 // Otherwise the search scope is the namespace scope of which F is a member.
950 LookupResult NonMembers(S, NotEqOp, OpLoc,
951 Sema::LookupNameKind::LookupOperatorName);
952 S.LookupName(NonMembers,
953 S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
954 NonMembers.suppressDiagnostics();
955 for (NamedDecl *Op : NonMembers) {
956 auto *FD = Op->getAsFunction();
957 if(auto* UD = dyn_cast<UsingShadowDecl>(Op))
958 FD = UD->getUnderlyingDecl()->getAsFunction();
959 if (FunctionsCorrespond(S.Context, EqFD, FD) &&
960 declaresSameEntity(cast<Decl>(EqFD->getDeclContext()),
961 cast<Decl>(Op->getDeclContext())))
962 return false;
963 }
964 return true;
965}
966
967bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
968 OverloadedOperatorKind Op) {
969 if (!AllowRewrittenCandidates)
970 return false;
971 return Op == OO_EqualEqual || Op == OO_Spaceship;
972}
973
974bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
975 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
976 auto Op = FD->getOverloadedOperator();
977 if (!allowsReversed(Op))
978 return false;
979 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
980 assert(OriginalArgs.size() == 2)(static_cast <bool> (OriginalArgs.size() == 2) ? void (
0) : __assert_fail ("OriginalArgs.size() == 2", "clang/lib/Sema/SemaOverload.cpp"
, 980, __extension__ __PRETTY_FUNCTION__))
;
981 if (!shouldAddReversedEqEq(
982 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
983 return false;
984 }
985 // Don't bother adding a reversed candidate that can never be a better
986 // match than the non-reversed version.
987 return FD->getNumParams() != 2 ||
988 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
989 FD->getParamDecl(1)->getType()) ||
990 FD->hasAttr<EnableIfAttr>();
991}
992
993void OverloadCandidateSet::destroyCandidates() {
994 for (iterator i = begin(), e = end(); i != e; ++i) {
995 for (auto &C : i->Conversions)
996 C.~ImplicitConversionSequence();
997 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
998 i->DeductionFailure.Destroy();
999 }
1000}
1001
1002void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1003 destroyCandidates();
1004 SlabAllocator.Reset();
1005 NumInlineBytesUsed = 0;
1006 Candidates.clear();
1007 Functions.clear();
1008 Kind = CSK;
1009}
1010
1011namespace {
1012 class UnbridgedCastsSet {
1013 struct Entry {
1014 Expr **Addr;
1015 Expr *Saved;
1016 };
1017 SmallVector<Entry, 2> Entries;
1018
1019 public:
1020 void save(Sema &S, Expr *&E) {
1021 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType
::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "clang/lib/Sema/SemaOverload.cpp", 1021, __extension__ __PRETTY_FUNCTION__
))
;
1022 Entry entry = { &E, E };
1023 Entries.push_back(entry);
1024 E = S.stripARCUnbridgedCast(E);
1025 }
1026
1027 void restore() {
1028 for (SmallVectorImpl<Entry>::iterator
1029 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1030 *i->Addr = i->Saved;
1031 }
1032 };
1033}
1034
1035/// checkPlaceholderForOverload - Do any interesting placeholder-like
1036/// preprocessing on the given expression.
1037///
1038/// \param unbridgedCasts a collection to which to add unbridged casts;
1039/// without this, they will be immediately diagnosed as errors
1040///
1041/// Return true on unrecoverable error.
1042static bool
1043checkPlaceholderForOverload(Sema &S, Expr *&E,
1044 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1045 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1046 // We can't handle overloaded expressions here because overload
1047 // resolution might reasonably tweak them.
1048 if (placeholder->getKind() == BuiltinType::Overload) return false;
1049
1050 // If the context potentially accepts unbridged ARC casts, strip
1051 // the unbridged cast and add it to the collection for later restoration.
1052 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1053 unbridgedCasts) {
1054 unbridgedCasts->save(S, E);
1055 return false;
1056 }
1057
1058 // Go ahead and check everything else.
1059 ExprResult result = S.CheckPlaceholderExpr(E);
1060 if (result.isInvalid())
1061 return true;
1062
1063 E = result.get();
1064 return false;
1065 }
1066
1067 // Nothing to do.
1068 return false;
1069}
1070
1071/// checkArgPlaceholdersForOverload - Check a set of call operands for
1072/// placeholders.
1073static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1074 UnbridgedCastsSet &unbridged) {
1075 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1076 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1077 return true;
1078
1079 return false;
1080}
1081
1082/// Determine whether the given New declaration is an overload of the
1083/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1084/// New and Old cannot be overloaded, e.g., if New has the same signature as
1085/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1086/// functions (or function templates) at all. When it does return Ovl_Match or
1087/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1088/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1089/// declaration.
1090///
1091/// Example: Given the following input:
1092///
1093/// void f(int, float); // #1
1094/// void f(int, int); // #2
1095/// int f(int, int); // #3
1096///
1097/// When we process #1, there is no previous declaration of "f", so IsOverload
1098/// will not be used.
1099///
1100/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1101/// the parameter types, we see that #1 and #2 are overloaded (since they have
1102/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1103/// unchanged.
1104///
1105/// When we process #3, Old is an overload set containing #1 and #2. We compare
1106/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1107/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1108/// functions are not part of the signature), IsOverload returns Ovl_Match and
1109/// MatchedDecl will be set to point to the FunctionDecl for #2.
1110///
1111/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1112/// by a using declaration. The rules for whether to hide shadow declarations
1113/// ignore some properties which otherwise figure into a function template's
1114/// signature.
1115Sema::OverloadKind
1116Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1117 NamedDecl *&Match, bool NewIsUsingDecl) {
1118 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1119 I != E; ++I) {
1120 NamedDecl *OldD = *I;
1121
1122 bool OldIsUsingDecl = false;
1123 if (isa<UsingShadowDecl>(OldD)) {
1124 OldIsUsingDecl = true;
1125
1126 // We can always introduce two using declarations into the same
1127 // context, even if they have identical signatures.
1128 if (NewIsUsingDecl) continue;
1129
1130 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1131 }
1132
1133 // A using-declaration does not conflict with another declaration
1134 // if one of them is hidden.
1135 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1136 continue;
1137
1138 // If either declaration was introduced by a using declaration,
1139 // we'll need to use slightly different rules for matching.
1140 // Essentially, these rules are the normal rules, except that
1141 // function templates hide function templates with different
1142 // return types or template parameter lists.
1143 bool UseMemberUsingDeclRules =
1144 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1145 !New->getFriendObjectKind();
1146
1147 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1148 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1149 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1150 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1151 continue;
1152 }
1153
1154 if (!isa<FunctionTemplateDecl>(OldD) &&
1155 !shouldLinkPossiblyHiddenDecl(*I, New))
1156 continue;
1157
1158 // C++20 [temp.friend] p9: A non-template friend declaration with a
1159 // requires-clause shall be a definition. A friend function template
1160 // with a constraint that depends on a template parameter from an
1161 // enclosing template shall be a definition. Such a constrained friend
1162 // function or function template declaration does not declare the same
1163 // function or function template as a declaration in any other scope.
1164 if (Context.FriendsDifferByConstraints(OldF, New))
1165 continue;
1166
1167 Match = *I;
1168 return Ovl_Match;
1169 }
1170
1171 // Builtins that have custom typechecking or have a reference should
1172 // not be overloadable or redeclarable.
1173 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1174 Match = *I;
1175 return Ovl_NonFunction;
1176 }
1177 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1178 // We can overload with these, which can show up when doing
1179 // redeclaration checks for UsingDecls.
1180 assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "clang/lib/Sema/SemaOverload.cpp", 1180, __extension__ __PRETTY_FUNCTION__
))
;
1181 } else if (isa<TagDecl>(OldD)) {
1182 // We can always overload with tags by hiding them.
1183 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1184 // Optimistically assume that an unresolved using decl will
1185 // overload; if it doesn't, we'll have to diagnose during
1186 // template instantiation.
1187 //
1188 // Exception: if the scope is dependent and this is not a class
1189 // member, the using declaration can only introduce an enumerator.
1190 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1191 Match = *I;
1192 return Ovl_NonFunction;
1193 }
1194 } else {
1195 // (C++ 13p1):
1196 // Only function declarations can be overloaded; object and type
1197 // declarations cannot be overloaded.
1198 Match = *I;
1199 return Ovl_NonFunction;
1200 }
1201 }
1202
1203 // C++ [temp.friend]p1:
1204 // For a friend function declaration that is not a template declaration:
1205 // -- if the name of the friend is a qualified or unqualified template-id,
1206 // [...], otherwise
1207 // -- if the name of the friend is a qualified-id and a matching
1208 // non-template function is found in the specified class or namespace,
1209 // the friend declaration refers to that function, otherwise,
1210 // -- if the name of the friend is a qualified-id and a matching function
1211 // template is found in the specified class or namespace, the friend
1212 // declaration refers to the deduced specialization of that function
1213 // template, otherwise
1214 // -- the name shall be an unqualified-id [...]
1215 // If we get here for a qualified friend declaration, we've just reached the
1216 // third bullet. If the type of the friend is dependent, skip this lookup
1217 // until instantiation.
1218 if (New->getFriendObjectKind() && New->getQualifier() &&
1219 !New->getDescribedFunctionTemplate() &&
1220 !New->getDependentSpecializationInfo() &&
1221 !New->getType()->isDependentType()) {
1222 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1223 TemplateSpecResult.addAllDecls(Old);
1224 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1225 /*QualifiedFriend*/true)) {
1226 New->setInvalidDecl();
1227 return Ovl_Overload;
1228 }
1229
1230 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1231 return Ovl_Match;
1232 }
1233
1234 return Ovl_Overload;
1235}
1236
1237bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1238 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1239 bool ConsiderRequiresClauses) {
1240 // C++ [basic.start.main]p2: This function shall not be overloaded.
1241 if (New->isMain())
1242 return false;
1243
1244 // MSVCRT user defined entry points cannot be overloaded.
1245 if (New->isMSVCRTEntryPoint())
1246 return false;
1247
1248 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1249 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1250
1251 // C++ [temp.fct]p2:
1252 // A function template can be overloaded with other function templates
1253 // and with normal (non-template) functions.
1254 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1255 return true;
1256
1257 // Is the function New an overload of the function Old?
1258 QualType OldQType = Context.getCanonicalType(Old->getType());
1259 QualType NewQType = Context.getCanonicalType(New->getType());
1260
1261 // Compare the signatures (C++ 1.3.10) of the two functions to
1262 // determine whether they are overloads. If we find any mismatch
1263 // in the signature, they are overloads.
1264
1265 // If either of these functions is a K&R-style function (no
1266 // prototype), then we consider them to have matching signatures.
1267 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1268 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1269 return false;
1270
1271 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1272 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1273
1274 // The signature of a function includes the types of its
1275 // parameters (C++ 1.3.10), which includes the presence or absence
1276 // of the ellipsis; see C++ DR 357).
1277 if (OldQType != NewQType &&
1278 (OldType->getNumParams() != NewType->getNumParams() ||
1279 OldType->isVariadic() != NewType->isVariadic() ||
1280 !FunctionParamTypesAreEqual(OldType, NewType)))
1281 return true;
1282
1283 if (NewTemplate) {
1284 // C++ [temp.over.link]p4:
1285 // The signature of a function template consists of its function
1286 // signature, its return type and its template parameter list. The names
1287 // of the template parameters are significant only for establishing the
1288 // relationship between the template parameters and the rest of the
1289 // signature.
1290 //
1291 // We check the return type and template parameter lists for function
1292 // templates first; the remaining checks follow.
1293 bool SameTemplateParameterList = TemplateParameterListsAreEqual(
1294 NewTemplate->getTemplateParameters(),
1295 OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
1296 bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
1297 New->getDeclaredReturnType());
1298 // FIXME(GH58571): Match template parameter list even for non-constrained
1299 // template heads. This currently ensures that the code prior to C++20 is
1300 // not newly broken.
1301 bool ConstraintsInTemplateHead =
1302 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1303 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1304 // C++ [namespace.udecl]p11:
1305 // The set of declarations named by a using-declarator that inhabits a
1306 // class C does not include member functions and member function
1307 // templates of a base class that "correspond" to (and thus would
1308 // conflict with) a declaration of a function or function template in
1309 // C.
1310 // Comparing return types is not required for the "correspond" check to
1311 // decide whether a member introduced by a shadow declaration is hidden.
1312 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1313 !SameTemplateParameterList)
1314 return true;
1315 if (!UseMemberUsingDeclRules &&
1316 (!SameTemplateParameterList || !SameReturnType))
1317 return true;
1318 }
1319 // If the function is a class member, its signature includes the
1320 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1321 //
1322 // As part of this, also check whether one of the member functions
1323 // is static, in which case they are not overloads (C++
1324 // 13.1p2). While not part of the definition of the signature,
1325 // this check is important to determine whether these functions
1326 // can be overloaded.
1327 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1328 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1329 if (OldMethod && NewMethod &&
1330 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1331 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1332 if (!UseMemberUsingDeclRules &&
1333 (OldMethod->getRefQualifier() == RQ_None ||
1334 NewMethod->getRefQualifier() == RQ_None)) {
1335 // C++0x [over.load]p2:
1336 // - Member function declarations with the same name and the same
1337 // parameter-type-list as well as member function template
1338 // declarations with the same name, the same parameter-type-list, and
1339 // the same template parameter lists cannot be overloaded if any of
1340 // them, but not all, have a ref-qualifier (8.3.5).
1341 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1342 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1343 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1344 }
1345 return true;
1346 }
1347
1348 // We may not have applied the implicit const for a constexpr member
1349 // function yet (because we haven't yet resolved whether this is a static
1350 // or non-static member function). Add it now, on the assumption that this
1351 // is a redeclaration of OldMethod.
1352 auto OldQuals = OldMethod->getMethodQualifiers();
1353 auto NewQuals = NewMethod->getMethodQualifiers();
1354 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1355 !isa<CXXConstructorDecl>(NewMethod))
1356 NewQuals.addConst();
1357 // We do not allow overloading based off of '__restrict'.
1358 OldQuals.removeRestrict();
1359 NewQuals.removeRestrict();
1360 if (OldQuals != NewQuals)
1361 return true;
1362 }
1363
1364 // Though pass_object_size is placed on parameters and takes an argument, we
1365 // consider it to be a function-level modifier for the sake of function
1366 // identity. Either the function has one or more parameters with
1367 // pass_object_size or it doesn't.
1368 if (functionHasPassObjectSizeParams(New) !=
1369 functionHasPassObjectSizeParams(Old))
1370 return true;
1371
1372 // enable_if attributes are an order-sensitive part of the signature.
1373 for (specific_attr_iterator<EnableIfAttr>
1374 NewI = New->specific_attr_begin<EnableIfAttr>(),
1375 NewE = New->specific_attr_end<EnableIfAttr>(),
1376 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1377 OldE = Old->specific_attr_end<EnableIfAttr>();
1378 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1379 if (NewI == NewE || OldI == OldE)
1380 return true;
1381 llvm::FoldingSetNodeID NewID, OldID;
1382 NewI->getCond()->Profile(NewID, Context, true);
1383 OldI->getCond()->Profile(OldID, Context, true);
1384 if (NewID != OldID)
1385 return true;
1386 }
1387
1388 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1389 // Don't allow overloading of destructors. (In theory we could, but it
1390 // would be a giant change to clang.)
1391 if (!isa<CXXDestructorDecl>(New)) {
1392 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1393 OldTarget = IdentifyCUDATarget(Old);
1394 if (NewTarget != CFT_InvalidTarget) {
1395 assert((OldTarget != CFT_InvalidTarget) &&(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1396, __extension__ __PRETTY_FUNCTION__
))
1396 "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1396, __extension__ __PRETTY_FUNCTION__
))
;
1397
1398 // Allow overloading of functions with same signature and different CUDA
1399 // target attributes.
1400 if (NewTarget != OldTarget)
1401 return true;
1402 }
1403 }
1404 }
1405
1406 if (ConsiderRequiresClauses) {
1407 Expr *NewRC = New->getTrailingRequiresClause(),
1408 *OldRC = Old->getTrailingRequiresClause();
1409 if ((NewRC != nullptr) != (OldRC != nullptr))
1410 // RC are most certainly different - these are overloads.
1411 return true;
1412
1413 if (NewRC) {
1414 llvm::FoldingSetNodeID NewID, OldID;
1415 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1416 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1417 if (NewID != OldID)
1418 // RCs are not equivalent - these are overloads.
1419 return true;
1420 }
1421 }
1422
1423 // The signatures match; this is not an overload.
1424 return false;
1425}
1426
1427/// Tries a user-defined conversion from From to ToType.
1428///
1429/// Produces an implicit conversion sequence for when a standard conversion
1430/// is not an option. See TryImplicitConversion for more information.
1431static ImplicitConversionSequence
1432TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1433 bool SuppressUserConversions,
1434 AllowedExplicit AllowExplicit,
1435 bool InOverloadResolution,
1436 bool CStyle,
1437 bool AllowObjCWritebackConversion,
1438 bool AllowObjCConversionOnExplicit) {
1439 ImplicitConversionSequence ICS;
1440
1441 if (SuppressUserConversions) {
1442 // We're not in the case above, so there is no conversion that
1443 // we can perform.
1444 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1445 return ICS;
1446 }
1447
1448 // Attempt user-defined conversion.
1449 OverloadCandidateSet Conversions(From->getExprLoc(),
1450 OverloadCandidateSet::CSK_Normal);
1451 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1452 Conversions, AllowExplicit,
1453 AllowObjCConversionOnExplicit)) {
1454 case OR_Success:
1455 case OR_Deleted:
1456 ICS.setUserDefined();
1457 // C++ [over.ics.user]p4:
1458 // A conversion of an expression of class type to the same class
1459 // type is given Exact Match rank, and a conversion of an
1460 // expression of class type to a base class of that type is
1461 // given Conversion rank, in spite of the fact that a copy
1462 // constructor (i.e., a user-defined conversion function) is
1463 // called for those cases.
1464 if (CXXConstructorDecl *Constructor
1465 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1466 QualType FromCanon
1467 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1468 QualType ToCanon
1469 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1470 if (Constructor->isCopyConstructor() &&
1471 (FromCanon == ToCanon ||
1472 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1473 // Turn this into a "standard" conversion sequence, so that it
1474 // gets ranked with standard conversion sequences.
1475 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1476 ICS.setStandard();
1477 ICS.Standard.setAsIdentityConversion();
1478 ICS.Standard.setFromType(From->getType());
1479 ICS.Standard.setAllToTypes(ToType);
1480 ICS.Standard.CopyConstructor = Constructor;
1481 ICS.Standard.FoundCopyConstructor = Found;
1482 if (ToCanon != FromCanon)
1483 ICS.Standard.Second = ICK_Derived_To_Base;
1484 }
1485 }
1486 break;
1487
1488 case OR_Ambiguous:
1489 ICS.setAmbiguous();
1490 ICS.Ambiguous.setFromType(From->getType());
1491 ICS.Ambiguous.setToType(ToType);
1492 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1493 Cand != Conversions.end(); ++Cand)
1494 if (Cand->Best)
1495 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1496 break;
1497
1498 // Fall through.
1499 case OR_No_Viable_Function:
1500 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1501 break;
1502 }
1503
1504 return ICS;
1505}
1506
1507/// TryImplicitConversion - Attempt to perform an implicit conversion
1508/// from the given expression (Expr) to the given type (ToType). This
1509/// function returns an implicit conversion sequence that can be used
1510/// to perform the initialization. Given
1511///
1512/// void f(float f);
1513/// void g(int i) { f(i); }
1514///
1515/// this routine would produce an implicit conversion sequence to
1516/// describe the initialization of f from i, which will be a standard
1517/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1518/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1519//
1520/// Note that this routine only determines how the conversion can be
1521/// performed; it does not actually perform the conversion. As such,
1522/// it will not produce any diagnostics if no conversion is available,
1523/// but will instead return an implicit conversion sequence of kind
1524/// "BadConversion".
1525///
1526/// If @p SuppressUserConversions, then user-defined conversions are
1527/// not permitted.
1528/// If @p AllowExplicit, then explicit user-defined conversions are
1529/// permitted.
1530///
1531/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1532/// writeback conversion, which allows __autoreleasing id* parameters to
1533/// be initialized with __strong id* or __weak id* arguments.
1534static ImplicitConversionSequence
1535TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1536 bool SuppressUserConversions,
1537 AllowedExplicit AllowExplicit,
1538 bool InOverloadResolution,
1539 bool CStyle,
1540 bool AllowObjCWritebackConversion,
1541 bool AllowObjCConversionOnExplicit) {
1542 ImplicitConversionSequence ICS;
1543 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1544 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1545 ICS.setStandard();
1546 return ICS;
1547 }
1548
1549 if (!S.getLangOpts().CPlusPlus) {
1550 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1551 return ICS;
1552 }
1553
1554 // C++ [over.ics.user]p4:
1555 // A conversion of an expression of class type to the same class
1556 // type is given Exact Match rank, and a conversion of an
1557 // expression of class type to a base class of that type is
1558 // given Conversion rank, in spite of the fact that a copy/move
1559 // constructor (i.e., a user-defined conversion function) is
1560 // called for those cases.
1561 QualType FromType = From->getType();
1562 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1563 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1564 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1565 ICS.setStandard();
1566 ICS.Standard.setAsIdentityConversion();
1567 ICS.Standard.setFromType(FromType);
1568 ICS.Standard.setAllToTypes(ToType);
1569
1570 // We don't actually check at this point whether there is a valid
1571 // copy/move constructor, since overloading just assumes that it
1572 // exists. When we actually perform initialization, we'll find the
1573 // appropriate constructor to copy the returned object, if needed.
1574 ICS.Standard.CopyConstructor = nullptr;
1575
1576 // Determine whether this is considered a derived-to-base conversion.
1577 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1578 ICS.Standard.Second = ICK_Derived_To_Base;
1579
1580 return ICS;
1581 }
1582
1583 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1584 AllowExplicit, InOverloadResolution, CStyle,
1585 AllowObjCWritebackConversion,
1586 AllowObjCConversionOnExplicit);
1587}
1588
1589ImplicitConversionSequence
1590Sema::TryImplicitConversion(Expr *From, QualType ToType,
1591 bool SuppressUserConversions,
1592 AllowedExplicit AllowExplicit,
1593 bool InOverloadResolution,
1594 bool CStyle,
1595 bool AllowObjCWritebackConversion) {
1596 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1597 AllowExplicit, InOverloadResolution, CStyle,
1598 AllowObjCWritebackConversion,
1599 /*AllowObjCConversionOnExplicit=*/false);
1600}
1601
1602/// PerformImplicitConversion - Perform an implicit conversion of the
1603/// expression From to the type ToType. Returns the
1604/// converted expression. Flavor is the kind of conversion we're
1605/// performing, used in the error message. If @p AllowExplicit,
1606/// explicit user-defined conversions are permitted.
1607ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1608 AssignmentAction Action,
1609 bool AllowExplicit) {
1610 if (checkPlaceholderForOverload(*this, From))
1611 return ExprError();
1612
1613 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1614 bool AllowObjCWritebackConversion
1615 = getLangOpts().ObjCAutoRefCount &&
1616 (Action == AA_Passing || Action == AA_Sending);
1617 if (getLangOpts().ObjC)
1618 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1619 From->getType(), From);
1620 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1621 *this, From, ToType,
1622 /*SuppressUserConversions=*/false,
1623 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1624 /*InOverloadResolution=*/false,
1625 /*CStyle=*/false, AllowObjCWritebackConversion,
1626 /*AllowObjCConversionOnExplicit=*/false);
1627 return PerformImplicitConversion(From, ToType, ICS, Action);
1628}
1629
1630/// Determine whether the conversion from FromType to ToType is a valid
1631/// conversion that strips "noexcept" or "noreturn" off the nested function
1632/// type.
1633bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1634 QualType &ResultTy) {
1635 if (Context.hasSameUnqualifiedType(FromType, ToType))
1636 return false;
1637
1638 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1639 // or F(t noexcept) -> F(t)
1640 // where F adds one of the following at most once:
1641 // - a pointer
1642 // - a member pointer
1643 // - a block pointer
1644 // Changes here need matching changes in FindCompositePointerType.
1645 CanQualType CanTo = Context.getCanonicalType(ToType);
1646 CanQualType CanFrom = Context.getCanonicalType(FromType);
1647 Type::TypeClass TyClass = CanTo->getTypeClass();
1648 if (TyClass != CanFrom->getTypeClass()) return false;
1649 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1650 if (TyClass == Type::Pointer) {
1651 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1652 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1653 } else if (TyClass == Type::BlockPointer) {
1654 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1655 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1656 } else if (TyClass == Type::MemberPointer) {
1657 auto ToMPT = CanTo.castAs<MemberPointerType>();
1658 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1659 // A function pointer conversion cannot change the class of the function.
1660 if (ToMPT->getClass() != FromMPT->getClass())
1661 return false;
1662 CanTo = ToMPT->getPointeeType();
1663 CanFrom = FromMPT->getPointeeType();
1664 } else {
1665 return false;
1666 }
1667
1668 TyClass = CanTo->getTypeClass();
1669 if (TyClass != CanFrom->getTypeClass()) return false;
1670 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1671 return false;
1672 }
1673
1674 const auto *FromFn = cast<FunctionType>(CanFrom);
1675 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1676
1677 const auto *ToFn = cast<FunctionType>(CanTo);
1678 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1679
1680 bool Changed = false;
1681
1682 // Drop 'noreturn' if not present in target type.
1683 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1684 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1685 Changed = true;
1686 }
1687
1688 // Drop 'noexcept' if not present in target type.
1689 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1690 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1691 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1692 FromFn = cast<FunctionType>(
1693 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1694 EST_None)
1695 .getTypePtr());
1696 Changed = true;
1697 }
1698
1699 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1700 // only if the ExtParameterInfo lists of the two function prototypes can be
1701 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1702 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1703 bool CanUseToFPT, CanUseFromFPT;
1704 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1705 CanUseFromFPT, NewParamInfos) &&
1706 CanUseToFPT && !CanUseFromFPT) {
1707 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1708 ExtInfo.ExtParameterInfos =
1709 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1710 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1711 FromFPT->getParamTypes(), ExtInfo);
1712 FromFn = QT->getAs<FunctionType>();
1713 Changed = true;
1714 }
1715 }
1716
1717 if (!Changed)
1718 return false;
1719
1720 assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical())
? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()"
, "clang/lib/Sema/SemaOverload.cpp", 1720, __extension__ __PRETTY_FUNCTION__
))
;
1721 if (QualType(FromFn, 0) != CanTo) return false;
1722
1723 ResultTy = ToType;
1724 return true;
1725}
1726
1727/// Determine whether the conversion from FromType to ToType is a valid
1728/// vector conversion.
1729///
1730/// \param ICK Will be set to the vector conversion kind, if this is a vector
1731/// conversion.
1732static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1733 ImplicitConversionKind &ICK, Expr *From,
1734 bool InOverloadResolution) {
1735 // We need at least one of these types to be a vector type to have a vector
1736 // conversion.
1737 if (!ToType->isVectorType() && !FromType->isVectorType())
1738 return false;
1739
1740 // Identical types require no conversions.
1741 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1742 return false;
1743
1744 // There are no conversions between extended vector types, only identity.
1745 if (ToType->isExtVectorType()) {
1746 // There are no conversions between extended vector types other than the
1747 // identity conversion.
1748 if (FromType->isExtVectorType())
1749 return false;
1750
1751 // Vector splat from any arithmetic type to a vector.
1752 if (FromType->isArithmeticType()) {
1753 ICK = ICK_Vector_Splat;
1754 return true;
1755 }
1756 }
1757
1758 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1759 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1760 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1761 ICK = ICK_SVE_Vector_Conversion;
1762 return true;
1763 }
1764
1765 // We can perform the conversion between vector types in the following cases:
1766 // 1)vector types are equivalent AltiVec and GCC vector types
1767 // 2)lax vector conversions are permitted and the vector types are of the
1768 // same size
1769 // 3)the destination type does not have the ARM MVE strict-polymorphism
1770 // attribute, which inhibits lax vector conversion for overload resolution
1771 // only
1772 if (ToType->isVectorType() && FromType->isVectorType()) {
1773 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1774 (S.isLaxVectorConversion(FromType, ToType) &&
1775 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1776 if (S.isLaxVectorConversion(FromType, ToType) &&
1777 S.anyAltivecTypes(FromType, ToType) &&
1778 !S.areSameVectorElemTypes(FromType, ToType) &&
1779 !InOverloadResolution) {
1780 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1781 << FromType << ToType;
1782 }
1783 ICK = ICK_Vector_Conversion;
1784 return true;
1785 }
1786 }
1787
1788 return false;
1789}
1790
1791static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1792 bool InOverloadResolution,
1793 StandardConversionSequence &SCS,
1794 bool CStyle);
1795
1796/// IsStandardConversion - Determines whether there is a standard
1797/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1798/// expression From to the type ToType. Standard conversion sequences
1799/// only consider non-class types; for conversions that involve class
1800/// types, use TryImplicitConversion. If a conversion exists, SCS will
1801/// contain the standard conversion sequence required to perform this
1802/// conversion and this routine will return true. Otherwise, this
1803/// routine will return false and the value of SCS is unspecified.
1804static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1805 bool InOverloadResolution,
1806 StandardConversionSequence &SCS,
1807 bool CStyle,
1808 bool AllowObjCWritebackConversion) {
1809 QualType FromType = From->getType();
1810
1811 // Standard conversions (C++ [conv])
1812 SCS.setAsIdentityConversion();
1813 SCS.IncompatibleObjC = false;
1814 SCS.setFromType(FromType);
1815 SCS.CopyConstructor = nullptr;
1816
1817 // There are no standard conversions for class types in C++, so
1818 // abort early. When overloading in C, however, we do permit them.
1819 if (S.getLangOpts().CPlusPlus &&
1820 (FromType->isRecordType() || ToType->isRecordType()))
1821 return false;
1822
1823 // The first conversion can be an lvalue-to-rvalue conversion,
1824 // array-to-pointer conversion, or function-to-pointer conversion
1825 // (C++ 4p1).
1826
1827 if (FromType == S.Context.OverloadTy) {
1828 DeclAccessPair AccessPair;
1829 if (FunctionDecl *Fn
1830 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1831 AccessPair)) {
1832 // We were able to resolve the address of the overloaded function,
1833 // so we can convert to the type of that function.
1834 FromType = Fn->getType();
1835 SCS.setFromType(FromType);
1836
1837 // we can sometimes resolve &foo<int> regardless of ToType, so check
1838 // if the type matches (identity) or we are converting to bool
1839 if (!S.Context.hasSameUnqualifiedType(
1840 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1841 QualType resultTy;
1842 // if the function type matches except for [[noreturn]], it's ok
1843 if (!S.IsFunctionConversion(FromType,
1844 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1845 // otherwise, only a boolean conversion is standard
1846 if (!ToType->isBooleanType())
1847 return false;
1848 }
1849
1850 // Check if the "from" expression is taking the address of an overloaded
1851 // function and recompute the FromType accordingly. Take advantage of the
1852 // fact that non-static member functions *must* have such an address-of
1853 // expression.
1854 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1855 if (Method && !Method->isStatic()) {
1856 assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1857, __extension__ __PRETTY_FUNCTION__
))
1857 "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1857, __extension__ __PRETTY_FUNCTION__
))
;
1858 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1860, __extension__ __PRETTY_FUNCTION__
))
1859 == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1860, __extension__ __PRETTY_FUNCTION__
))
1860 "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1860, __extension__ __PRETTY_FUNCTION__
))
;
1861 const Type *ClassType
1862 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1863 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1864 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1865 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1867, __extension__ __PRETTY_FUNCTION__
))
1866 UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1867, __extension__ __PRETTY_FUNCTION__
))
1867 "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1867, __extension__ __PRETTY_FUNCTION__
))
;
1868 FromType = S.Context.getPointerType(FromType);
1869 }
1870 } else {
1871 return false;
1872 }
1873 }
1874 // Lvalue-to-rvalue conversion (C++11 4.1):
1875 // A glvalue (3.10) of a non-function, non-array type T can
1876 // be converted to a prvalue.
1877 bool argIsLValue = From->isGLValue();
1878 if (argIsLValue &&
1879 !FromType->isFunctionType() && !FromType->isArrayType() &&
1880 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1881 SCS.First = ICK_Lvalue_To_Rvalue;
1882
1883 // C11 6.3.2.1p2:
1884 // ... if the lvalue has atomic type, the value has the non-atomic version
1885 // of the type of the lvalue ...
1886 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1887 FromType = Atomic->getValueType();
1888
1889 // If T is a non-class type, the type of the rvalue is the
1890 // cv-unqualified version of T. Otherwise, the type of the rvalue
1891 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1892 // just strip the qualifiers because they don't matter.
1893 FromType = FromType.getUnqualifiedType();
1894 } else if (FromType->isArrayType()) {
1895 // Array-to-pointer conversion (C++ 4.2)
1896 SCS.First = ICK_Array_To_Pointer;
1897
1898 // An lvalue or rvalue of type "array of N T" or "array of unknown
1899 // bound of T" can be converted to an rvalue of type "pointer to
1900 // T" (C++ 4.2p1).
1901 FromType = S.Context.getArrayDecayedType(FromType);
1902
1903 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1904 // This conversion is deprecated in C++03 (D.4)
1905 SCS.DeprecatedStringLiteralToCharPtr = true;
1906
1907 // For the purpose of ranking in overload resolution
1908 // (13.3.3.1.1), this conversion is considered an
1909 // array-to-pointer conversion followed by a qualification
1910 // conversion (4.4). (C++ 4.2p2)
1911 SCS.Second = ICK_Identity;
1912 SCS.Third = ICK_Qualification;
1913 SCS.QualificationIncludesObjCLifetime = false;
1914 SCS.setAllToTypes(FromType);
1915 return true;
1916 }
1917 } else if (FromType->isFunctionType() && argIsLValue) {
1918 // Function-to-pointer conversion (C++ 4.3).
1919 SCS.First = ICK_Function_To_Pointer;
1920
1921 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1922 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1923 if (!S.checkAddressOfFunctionIsAvailable(FD))
1924 return false;
1925
1926 // An lvalue of function type T can be converted to an rvalue of
1927 // type "pointer to T." The result is a pointer to the
1928 // function. (C++ 4.3p1).
1929 FromType = S.Context.getPointerType(FromType);
1930 } else {
1931 // We don't require any conversions for the first step.
1932 SCS.First = ICK_Identity;
1933 }
1934 SCS.setToType(0, FromType);
1935
1936 // The second conversion can be an integral promotion, floating
1937 // point promotion, integral conversion, floating point conversion,
1938 // floating-integral conversion, pointer conversion,
1939 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1940 // For overloading in C, this can also be a "compatible-type"
1941 // conversion.
1942 bool IncompatibleObjC = false;
1943 ImplicitConversionKind SecondICK = ICK_Identity;
1944 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1945 // The unqualified versions of the types are the same: there's no
1946 // conversion to do.
1947 SCS.Second = ICK_Identity;
1948 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1949 // Integral promotion (C++ 4.5).
1950 SCS.Second = ICK_Integral_Promotion;
1951 FromType = ToType.getUnqualifiedType();
1952 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1953 // Floating point promotion (C++ 4.6).
1954 SCS.Second = ICK_Floating_Promotion;
1955 FromType = ToType.getUnqualifiedType();
1956 } else if (S.IsComplexPromotion(FromType, ToType)) {
1957 // Complex promotion (Clang extension)
1958 SCS.Second = ICK_Complex_Promotion;
1959 FromType = ToType.getUnqualifiedType();
1960 } else if (ToType->isBooleanType() &&
1961 (FromType->isArithmeticType() ||
1962 FromType->isAnyPointerType() ||
1963 FromType->isBlockPointerType() ||
1964 FromType->isMemberPointerType())) {
1965 // Boolean conversions (C++ 4.12).
1966 SCS.Second = ICK_Boolean_Conversion;
1967 FromType = S.Context.BoolTy;
1968 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1969 ToType->isIntegralType(S.Context)) {
1970 // Integral conversions (C++ 4.7).
1971 SCS.Second = ICK_Integral_Conversion;
1972 FromType = ToType.getUnqualifiedType();
1973 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1974 // Complex conversions (C99 6.3.1.6)
1975 SCS.Second = ICK_Complex_Conversion;
1976 FromType = ToType.getUnqualifiedType();
1977 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1978 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1979 // Complex-real conversions (C99 6.3.1.7)
1980 SCS.Second = ICK_Complex_Real;
1981 FromType = ToType.getUnqualifiedType();
1982 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1983 // FIXME: disable conversions between long double, __ibm128 and __float128
1984 // if their representation is different until there is back end support
1985 // We of course allow this conversion if long double is really double.
1986
1987 // Conversions between bfloat and other floats are not permitted.
1988 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1989 return false;
1990
1991 // Conversions between IEEE-quad and IBM-extended semantics are not
1992 // permitted.
1993 const llvm::fltSemantics &FromSem =
1994 S.Context.getFloatTypeSemantics(FromType);
1995 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1996 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1997 &ToSem == &llvm::APFloat::IEEEquad()) ||
1998 (&FromSem == &llvm::APFloat::IEEEquad() &&
1999 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2000 return false;
2001
2002 // Floating point conversions (C++ 4.8).
2003 SCS.Second = ICK_Floating_Conversion;
2004 FromType = ToType.getUnqualifiedType();
2005 } else if ((FromType->isRealFloatingType() &&
2006 ToType->isIntegralType(S.Context)) ||
2007 (FromType->isIntegralOrUnscopedEnumerationType() &&
2008 ToType->isRealFloatingType())) {
2009 // Conversions between bfloat and int are not permitted.
2010 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
2011 return false;
2012
2013 // Floating-integral conversions (C++ 4.9).
2014 SCS.Second = ICK_Floating_Integral;
2015 FromType = ToType.getUnqualifiedType();
2016 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2017 SCS.Second = ICK_Block_Pointer_Conversion;
2018 } else if (AllowObjCWritebackConversion &&
2019 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2020 SCS.Second = ICK_Writeback_Conversion;
2021 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2022 FromType, IncompatibleObjC)) {
2023 // Pointer conversions (C++ 4.10).
2024 SCS.Second = ICK_Pointer_Conversion;
2025 SCS.IncompatibleObjC = IncompatibleObjC;
2026 FromType = FromType.getUnqualifiedType();
2027 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2028 InOverloadResolution, FromType)) {
2029 // Pointer to member conversions (4.11).
2030 SCS.Second = ICK_Pointer_Member;
2031 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
2032 InOverloadResolution)) {
2033 SCS.Second = SecondICK;
2034 FromType = ToType.getUnqualifiedType();
2035 } else if (!S.getLangOpts().CPlusPlus &&
2036 S.Context.typesAreCompatible(ToType, FromType)) {
2037 // Compatible conversions (Clang extension for C function overloading)
2038 SCS.Second = ICK_Compatible_Conversion;
2039 FromType = ToType.getUnqualifiedType();
2040 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
2041 InOverloadResolution,
2042 SCS, CStyle)) {
2043 SCS.Second = ICK_TransparentUnionConversion;
2044 FromType = ToType;
2045 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2046 CStyle)) {
2047 // tryAtomicConversion has updated the standard conversion sequence
2048 // appropriately.
2049 return true;
2050 } else if (ToType->isEventT() &&
2051 From->isIntegerConstantExpr(S.getASTContext()) &&
2052 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2053 SCS.Second = ICK_Zero_Event_Conversion;
2054 FromType = ToType;
2055 } else if (ToType->isQueueT() &&
2056 From->isIntegerConstantExpr(S.getASTContext()) &&
2057 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2058 SCS.Second = ICK_Zero_Queue_Conversion;
2059 FromType = ToType;
2060 } else if (ToType->isSamplerT() &&
2061 From->isIntegerConstantExpr(S.getASTContext())) {
2062 SCS.Second = ICK_Compatible_Conversion;
2063 FromType = ToType;
2064 } else {
2065 // No second conversion required.
2066 SCS.Second = ICK_Identity;
2067 }
2068 SCS.setToType(1, FromType);
2069
2070 // The third conversion can be a function pointer conversion or a
2071 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2072 bool ObjCLifetimeConversion;
2073 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2074 // Function pointer conversions (removing 'noexcept') including removal of
2075 // 'noreturn' (Clang extension).
2076 SCS.Third = ICK_Function_Conversion;
2077 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2078 ObjCLifetimeConversion)) {
2079 SCS.Third = ICK_Qualification;
2080 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2081 FromType = ToType;
2082 } else {
2083 // No conversion required
2084 SCS.Third = ICK_Identity;
2085 }
2086
2087 // C++ [over.best.ics]p6:
2088 // [...] Any difference in top-level cv-qualification is
2089 // subsumed by the initialization itself and does not constitute
2090 // a conversion. [...]
2091 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2092 QualType CanonTo = S.Context.getCanonicalType(ToType);
2093 if (CanonFrom.getLocalUnqualifiedType()
2094 == CanonTo.getLocalUnqualifiedType() &&
2095 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2096 FromType = ToType;
2097 CanonFrom = CanonTo;
2098 }
2099
2100 SCS.setToType(2, FromType);
2101
2102 if (CanonFrom == CanonTo)
2103 return true;
2104
2105 // If we have not converted the argument type to the parameter type,
2106 // this is a bad conversion sequence, unless we're resolving an overload in C.
2107 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2108 return false;
2109
2110 ExprResult ER = ExprResult{From};
2111 Sema::AssignConvertType Conv =
2112 S.CheckSingleAssignmentConstraints(ToType, ER,
2113 /*Diagnose=*/false,
2114 /*DiagnoseCFAudited=*/false,
2115 /*ConvertRHS=*/false);
2116 ImplicitConversionKind SecondConv;
2117 switch (Conv) {
2118 case Sema::Compatible:
2119 SecondConv = ICK_C_Only_Conversion;
2120 break;
2121 // For our purposes, discarding qualifiers is just as bad as using an
2122 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2123 // qualifiers, as well.
2124 case Sema::CompatiblePointerDiscardsQualifiers:
2125 case Sema::IncompatiblePointer:
2126 case Sema::IncompatiblePointerSign:
2127 SecondConv = ICK_Incompatible_Pointer_Conversion;
2128 break;
2129 default:
2130 return false;
2131 }
2132
2133 // First can only be an lvalue conversion, so we pretend that this was the
2134 // second conversion. First should already be valid from earlier in the
2135 // function.
2136 SCS.Second = SecondConv;
2137 SCS.setToType(1, ToType);
2138
2139 // Third is Identity, because Second should rank us worse than any other
2140 // conversion. This could also be ICK_Qualification, but it's simpler to just
2141 // lump everything in with the second conversion, and we don't gain anything
2142 // from making this ICK_Qualification.
2143 SCS.Third = ICK_Identity;
2144 SCS.setToType(2, ToType);
2145 return true;
2146}
2147
2148static bool
2149IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2150 QualType &ToType,
2151 bool InOverloadResolution,
2152 StandardConversionSequence &SCS,
2153 bool CStyle) {
2154
2155 const RecordType *UT = ToType->getAsUnionType();
2156 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2157 return false;
2158 // The field to initialize within the transparent union.
2159 RecordDecl *UD = UT->getDecl();
2160 // It's compatible if the expression matches any of the fields.
2161 for (const auto *it : UD->fields()) {
2162 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2163 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2164 ToType = it->getType();
2165 return true;
2166 }
2167 }
2168 return false;
2169}
2170
2171/// IsIntegralPromotion - Determines whether the conversion from the
2172/// expression From (whose potentially-adjusted type is FromType) to
2173/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2174/// sets PromotedType to the promoted type.
2175bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2176 const BuiltinType *To = ToType->getAs<BuiltinType>();
2177 // All integers are built-in.
2178 if (!To) {
2179 return false;
2180 }
2181
2182 // An rvalue of type char, signed char, unsigned char, short int, or
2183 // unsigned short int can be converted to an rvalue of type int if
2184 // int can represent all the values of the source type; otherwise,
2185 // the source rvalue can be converted to an rvalue of type unsigned
2186 // int (C++ 4.5p1).
2187 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2188 !FromType->isEnumeralType()) {
2189 if ( // We can promote any signed, promotable integer type to an int
2190 (FromType->isSignedIntegerType() ||
2191 // We can promote any unsigned integer type whose size is
2192 // less than int to an int.
2193 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2194 return To->getKind() == BuiltinType::Int;
2195 }
2196
2197 return To->getKind() == BuiltinType::UInt;
2198 }
2199
2200 // C++11 [conv.prom]p3:
2201 // A prvalue of an unscoped enumeration type whose underlying type is not
2202 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2203 // following types that can represent all the values of the enumeration
2204 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2205 // unsigned int, long int, unsigned long int, long long int, or unsigned
2206 // long long int. If none of the types in that list can represent all the
2207 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2208 // type can be converted to an rvalue a prvalue of the extended integer type
2209 // with lowest integer conversion rank (4.13) greater than the rank of long
2210 // long in which all the values of the enumeration can be represented. If
2211 // there are two such extended types, the signed one is chosen.
2212 // C++11 [conv.prom]p4:
2213 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2214 // can be converted to a prvalue of its underlying type. Moreover, if
2215 // integral promotion can be applied to its underlying type, a prvalue of an
2216 // unscoped enumeration type whose underlying type is fixed can also be
2217 // converted to a prvalue of the promoted underlying type.
2218 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2219 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2220 // provided for a scoped enumeration.
2221 if (FromEnumType->getDecl()->isScoped())
2222 return false;
2223
2224 // We can perform an integral promotion to the underlying type of the enum,
2225 // even if that's not the promoted type. Note that the check for promoting
2226 // the underlying type is based on the type alone, and does not consider
2227 // the bitfield-ness of the actual source expression.
2228 if (FromEnumType->getDecl()->isFixed()) {
2229 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2230 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2231 IsIntegralPromotion(nullptr, Underlying, ToType);
2232 }
2233
2234 // We have already pre-calculated the promotion type, so this is trivial.
2235 if (ToType->isIntegerType() &&
2236 isCompleteType(From->getBeginLoc(), FromType))
2237 return Context.hasSameUnqualifiedType(
2238 ToType, FromEnumType->getDecl()->getPromotionType());
2239
2240 // C++ [conv.prom]p5:
2241 // If the bit-field has an enumerated type, it is treated as any other
2242 // value of that type for promotion purposes.
2243 //
2244 // ... so do not fall through into the bit-field checks below in C++.
2245 if (getLangOpts().CPlusPlus)
2246 return false;
2247 }
2248
2249 // C++0x [conv.prom]p2:
2250 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2251 // to an rvalue a prvalue of the first of the following types that can
2252 // represent all the values of its underlying type: int, unsigned int,
2253 // long int, unsigned long int, long long int, or unsigned long long int.
2254 // If none of the types in that list can represent all the values of its
2255 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2256 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2257 // type.
2258 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2259 ToType->isIntegerType()) {
2260 // Determine whether the type we're converting from is signed or
2261 // unsigned.
2262 bool FromIsSigned = FromType->isSignedIntegerType();
2263 uint64_t FromSize = Context.getTypeSize(FromType);
2264
2265 // The types we'll try to promote to, in the appropriate
2266 // order. Try each of these types.
2267 QualType PromoteTypes[6] = {
2268 Context.IntTy, Context.UnsignedIntTy,
2269 Context.LongTy, Context.UnsignedLongTy ,
2270 Context.LongLongTy, Context.UnsignedLongLongTy
2271 };
2272 for (int Idx = 0; Idx < 6; ++Idx) {
2273 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2274 if (FromSize < ToSize ||
2275 (FromSize == ToSize &&
2276 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2277 // We found the type that we can promote to. If this is the
2278 // type we wanted, we have a promotion. Otherwise, no
2279 // promotion.
2280 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2281 }
2282 }
2283 }
2284
2285 // An rvalue for an integral bit-field (9.6) can be converted to an
2286 // rvalue of type int if int can represent all the values of the
2287 // bit-field; otherwise, it can be converted to unsigned int if
2288 // unsigned int can represent all the values of the bit-field. If
2289 // the bit-field is larger yet, no integral promotion applies to
2290 // it. If the bit-field has an enumerated type, it is treated as any
2291 // other value of that type for promotion purposes (C++ 4.5p3).
2292 // FIXME: We should delay checking of bit-fields until we actually perform the
2293 // conversion.
2294 //
2295 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2296 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2297 // bit-fields and those whose underlying type is larger than int) for GCC
2298 // compatibility.
2299 if (From) {
2300 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2301 Optional<llvm::APSInt> BitWidth;
2302 if (FromType->isIntegralType(Context) &&
2303 (BitWidth =
2304 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2305 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2306 ToSize = Context.getTypeSize(ToType);
2307
2308 // Are we promoting to an int from a bitfield that fits in an int?
2309 if (*BitWidth < ToSize ||
2310 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2311 return To->getKind() == BuiltinType::Int;
2312 }
2313
2314 // Are we promoting to an unsigned int from an unsigned bitfield
2315 // that fits into an unsigned int?
2316 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2317 return To->getKind() == BuiltinType::UInt;
2318 }
2319
2320 return false;
2321 }
2322 }
2323 }
2324
2325 // An rvalue of type bool can be converted to an rvalue of type int,
2326 // with false becoming zero and true becoming one (C++ 4.5p4).
2327 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2328 return true;
2329 }
2330
2331 return false;
2332}
2333
2334/// IsFloatingPointPromotion - Determines whether the conversion from
2335/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2336/// returns true and sets PromotedType to the promoted type.
2337bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2338 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2339 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2340 /// An rvalue of type float can be converted to an rvalue of type
2341 /// double. (C++ 4.6p1).
2342 if (FromBuiltin->getKind() == BuiltinType::Float &&
2343 ToBuiltin->getKind() == BuiltinType::Double)
2344 return true;
2345
2346 // C99 6.3.1.5p1:
2347 // When a float is promoted to double or long double, or a
2348 // double is promoted to long double [...].
2349 if (!getLangOpts().CPlusPlus &&
2350 (FromBuiltin->getKind() == BuiltinType::Float ||
2351 FromBuiltin->getKind() == BuiltinType::Double) &&
2352 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2353 ToBuiltin->getKind() == BuiltinType::Float128 ||
2354 ToBuiltin->getKind() == BuiltinType::Ibm128))
2355 return true;
2356
2357 // Half can be promoted to float.
2358 if (!getLangOpts().NativeHalfType &&
2359 FromBuiltin->getKind() == BuiltinType::Half &&
2360 ToBuiltin->getKind() == BuiltinType::Float)
2361 return true;
2362 }
2363
2364 return false;
2365}
2366
2367/// Determine if a conversion is a complex promotion.
2368///
2369/// A complex promotion is defined as a complex -> complex conversion
2370/// where the conversion between the underlying real types is a
2371/// floating-point or integral promotion.
2372bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2373 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2374 if (!FromComplex)
2375 return false;
2376
2377 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2378 if (!ToComplex)
2379 return false;
2380
2381 return IsFloatingPointPromotion(FromComplex->getElementType(),
2382 ToComplex->getElementType()) ||
2383 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2384 ToComplex->getElementType());
2385}
2386
2387/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2388/// the pointer type FromPtr to a pointer to type ToPointee, with the
2389/// same type qualifiers as FromPtr has on its pointee type. ToType,
2390/// if non-empty, will be a pointer to ToType that may or may not have
2391/// the right set of qualifiers on its pointee.
2392///
2393static QualType
2394BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2395 QualType ToPointee, QualType ToType,
2396 ASTContext &Context,
2397 bool StripObjCLifetime = false) {
2398 assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2400, __extension__ __PRETTY_FUNCTION__
))
2399 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2400, __extension__ __PRETTY_FUNCTION__
))
2400 "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2400, __extension__ __PRETTY_FUNCTION__
))
;
2401
2402 /// Conversions to 'id' subsume cv-qualifier conversions.
2403 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2404 return ToType.getUnqualifiedType();
2405
2406 QualType CanonFromPointee
2407 = Context.getCanonicalType(FromPtr->getPointeeType());
2408 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2409 Qualifiers Quals = CanonFromPointee.getQualifiers();
2410
2411 if (StripObjCLifetime)
2412 Quals.removeObjCLifetime();
2413
2414 // Exact qualifier match -> return the pointer type we're converting to.
2415 if (CanonToPointee.getLocalQualifiers() == Quals) {
2416 // ToType is exactly what we need. Return it.
2417 if (!ToType.isNull())
2418 return ToType.getUnqualifiedType();
2419
2420 // Build a pointer to ToPointee. It has the right qualifiers
2421 // already.
2422 if (isa<ObjCObjectPointerType>(ToType))
2423 return Context.getObjCObjectPointerType(ToPointee);
2424 return Context.getPointerType(ToPointee);
2425 }
2426
2427 // Just build a canonical type that has the right qualifiers.
2428 QualType QualifiedCanonToPointee
2429 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2430
2431 if (isa<ObjCObjectPointerType>(ToType))
2432 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2433 return Context.getPointerType(QualifiedCanonToPointee);
2434}
2435
2436static bool isNullPointerConstantForConversion(Expr *Expr,
2437 bool InOverloadResolution,
2438 ASTContext &Context) {
2439 // Handle value-dependent integral null pointer constants correctly.
2440 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2441 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2442 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2443 return !InOverloadResolution;
2444
2445 return Expr->isNullPointerConstant(Context,
2446 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2447 : Expr::NPC_ValueDependentIsNull);
2448}
2449
2450/// IsPointerConversion - Determines whether the conversion of the
2451/// expression From, which has the (possibly adjusted) type FromType,
2452/// can be converted to the type ToType via a pointer conversion (C++
2453/// 4.10). If so, returns true and places the converted type (that
2454/// might differ from ToType in its cv-qualifiers at some level) into
2455/// ConvertedType.
2456///
2457/// This routine also supports conversions to and from block pointers
2458/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2459/// pointers to interfaces. FIXME: Once we've determined the
2460/// appropriate overloading rules for Objective-C, we may want to
2461/// split the Objective-C checks into a different routine; however,
2462/// GCC seems to consider all of these conversions to be pointer
2463/// conversions, so for now they live here. IncompatibleObjC will be
2464/// set if the conversion is an allowed Objective-C conversion that
2465/// should result in a warning.
2466bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2467 bool InOverloadResolution,
2468 QualType& ConvertedType,
2469 bool &IncompatibleObjC) {
2470 IncompatibleObjC = false;
2471 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2472 IncompatibleObjC))
2473 return true;
2474
2475 // Conversion from a null pointer constant to any Objective-C pointer type.
2476 if (ToType->isObjCObjectPointerType() &&
2477 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2478 ConvertedType = ToType;
2479 return true;
2480 }
2481
2482 // Blocks: Block pointers can be converted to void*.
2483 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2484 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2485 ConvertedType = ToType;
2486 return true;
2487 }
2488 // Blocks: A null pointer constant can be converted to a block
2489 // pointer type.
2490 if (ToType->isBlockPointerType() &&
2491 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2492 ConvertedType = ToType;
2493 return true;
2494 }
2495
2496 // If the left-hand-side is nullptr_t, the right side can be a null
2497 // pointer constant.
2498 if (ToType->isNullPtrType() &&
2499 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2500 ConvertedType = ToType;
2501 return true;
2502 }
2503
2504 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2505 if (!ToTypePtr)
2506 return false;
2507
2508 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2509 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2510 ConvertedType = ToType;
2511 return true;
2512 }
2513
2514 // Beyond this point, both types need to be pointers
2515 // , including objective-c pointers.
2516 QualType ToPointeeType = ToTypePtr->getPointeeType();
2517 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2518 !getLangOpts().ObjCAutoRefCount) {
2519 ConvertedType = BuildSimilarlyQualifiedPointerType(
2520 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2521 Context);
2522 return true;
2523 }
2524 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2525 if (!FromTypePtr)
2526 return false;
2527
2528 QualType FromPointeeType = FromTypePtr->getPointeeType();
2529
2530 // If the unqualified pointee types are the same, this can't be a
2531 // pointer conversion, so don't do all of the work below.
2532 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2533 return false;
2534
2535 // An rvalue of type "pointer to cv T," where T is an object type,
2536 // can be converted to an rvalue of type "pointer to cv void" (C++
2537 // 4.10p2).
2538 if (FromPointeeType->isIncompleteOrObjectType() &&
2539 ToPointeeType->isVoidType()) {
2540 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2541 ToPointeeType,
2542 ToType, Context,
2543 /*StripObjCLifetime=*/true);
2544 return true;
2545 }
2546
2547 // MSVC allows implicit function to void* type conversion.
2548 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2549 ToPointeeType->isVoidType()) {
2550 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2551 ToPointeeType,
2552 ToType, Context);
2553 return true;
2554 }
2555
2556 // When we're overloading in C, we allow a special kind of pointer
2557 // conversion for compatible-but-not-identical pointee types.
2558 if (!getLangOpts().CPlusPlus &&
2559 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2560 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2561 ToPointeeType,
2562 ToType, Context);
2563 return true;
2564 }
2565
2566 // C++ [conv.ptr]p3:
2567 //
2568 // An rvalue of type "pointer to cv D," where D is a class type,
2569 // can be converted to an rvalue of type "pointer to cv B," where
2570 // B is a base class (clause 10) of D. If B is an inaccessible
2571 // (clause 11) or ambiguous (10.2) base class of D, a program that
2572 // necessitates this conversion is ill-formed. The result of the
2573 // conversion is a pointer to the base class sub-object of the
2574 // derived class object. The null pointer value is converted to
2575 // the null pointer value of the destination type.
2576 //
2577 // Note that we do not check for ambiguity or inaccessibility
2578 // here. That is handled by CheckPointerConversion.
2579 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2580 ToPointeeType->isRecordType() &&
2581 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2582 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2583 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2584 ToPointeeType,
2585 ToType, Context);
2586 return true;
2587 }
2588
2589 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2590 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2591 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2592 ToPointeeType,
2593 ToType, Context);
2594 return true;
2595 }
2596
2597 return false;
2598}
2599
2600/// Adopt the given qualifiers for the given type.
2601static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2602 Qualifiers TQs = T.getQualifiers();
2603
2604 // Check whether qualifiers already match.
2605 if (TQs == Qs)
2606 return T;
2607
2608 if (Qs.compatiblyIncludes(TQs))
2609 return Context.getQualifiedType(T, Qs);
2610
2611 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2612}
2613
2614/// isObjCPointerConversion - Determines whether this is an
2615/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2616/// with the same arguments and return values.
2617bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2618 QualType& ConvertedType,
2619 bool &IncompatibleObjC) {
2620 if (!getLangOpts().ObjC)
2621 return false;
2622
2623 // The set of qualifiers on the type we're converting from.
2624 Qualifiers FromQualifiers = FromType.getQualifiers();
2625
2626 // First, we handle all conversions on ObjC object pointer types.
2627 const ObjCObjectPointerType* ToObjCPtr =
2628 ToType->getAs<ObjCObjectPointerType>();
2629 const ObjCObjectPointerType *FromObjCPtr =
2630 FromType->getAs<ObjCObjectPointerType>();
2631
2632 if (ToObjCPtr && FromObjCPtr) {
2633 // If the pointee types are the same (ignoring qualifications),
2634 // then this is not a pointer conversion.
2635 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2636 FromObjCPtr->getPointeeType()))
2637 return false;
2638
2639 // Conversion between Objective-C pointers.
2640 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2641 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2642 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2643 if (getLangOpts().CPlusPlus && LHS && RHS &&
2644 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2645 FromObjCPtr->getPointeeType()))
2646 return false;
2647 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2648 ToObjCPtr->getPointeeType(),
2649 ToType, Context);
2650 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2651 return true;
2652 }
2653
2654 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2655 // Okay: this is some kind of implicit downcast of Objective-C
2656 // interfaces, which is permitted. However, we're going to
2657 // complain about it.
2658 IncompatibleObjC = true;
2659 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2660 ToObjCPtr->getPointeeType(),
2661 ToType, Context);
2662 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2663 return true;
2664 }
2665 }
2666 // Beyond this point, both types need to be C pointers or block pointers.
2667 QualType ToPointeeType;
2668 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2669 ToPointeeType = ToCPtr->getPointeeType();
2670 else if (const BlockPointerType *ToBlockPtr =
2671 ToType->getAs<BlockPointerType>()) {
2672 // Objective C++: We're able to convert from a pointer to any object
2673 // to a block pointer type.
2674 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2675 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2676 return true;
2677 }
2678 ToPointeeType = ToBlockPtr->getPointeeType();
2679 }
2680 else if (FromType->getAs<BlockPointerType>() &&
2681 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2682 // Objective C++: We're able to convert from a block pointer type to a
2683 // pointer to any object.
2684 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2685 return true;
2686 }
2687 else
2688 return false;
2689
2690 QualType FromPointeeType;
2691 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2692 FromPointeeType = FromCPtr->getPointeeType();
2693 else if (const BlockPointerType *FromBlockPtr =
2694 FromType->getAs<BlockPointerType>())
2695 FromPointeeType = FromBlockPtr->getPointeeType();
2696 else
2697 return false;
2698
2699 // If we have pointers to pointers, recursively check whether this
2700 // is an Objective-C conversion.
2701 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2702 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2703 IncompatibleObjC)) {
2704 // We always complain about this conversion.
2705 IncompatibleObjC = true;
2706 ConvertedType = Context.getPointerType(ConvertedType);
2707 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2708 return true;
2709 }
2710 // Allow conversion of pointee being objective-c pointer to another one;
2711 // as in I* to id.
2712 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2713 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2714 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2715 IncompatibleObjC)) {
2716
2717 ConvertedType = Context.getPointerType(ConvertedType);
2718 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2719 return true;
2720 }
2721
2722 // If we have pointers to functions or blocks, check whether the only
2723 // differences in the argument and result types are in Objective-C
2724 // pointer conversions. If so, we permit the conversion (but
2725 // complain about it).
2726 const FunctionProtoType *FromFunctionType
2727 = FromPointeeType->getAs<FunctionProtoType>();
2728 const FunctionProtoType *ToFunctionType
2729 = ToPointeeType->getAs<FunctionProtoType>();
2730 if (FromFunctionType && ToFunctionType) {
2731 // If the function types are exactly the same, this isn't an
2732 // Objective-C pointer conversion.
2733 if (Context.getCanonicalType(FromPointeeType)
2734 == Context.getCanonicalType(ToPointeeType))
2735 return false;
2736
2737 // Perform the quick checks that will tell us whether these
2738 // function types are obviously different.
2739 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2740 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2741 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2742 return false;
2743
2744 bool HasObjCConversion = false;
2745 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2746 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2747 // Okay, the types match exactly. Nothing to do.
2748 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2749 ToFunctionType->getReturnType(),
2750 ConvertedType, IncompatibleObjC)) {
2751 // Okay, we have an Objective-C pointer conversion.
2752 HasObjCConversion = true;
2753 } else {
2754 // Function types are too different. Abort.
2755 return false;
2756 }
2757
2758 // Check argument types.
2759 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2760 ArgIdx != NumArgs; ++ArgIdx) {
2761 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2762 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2763 if (Context.getCanonicalType(FromArgType)
2764 == Context.getCanonicalType(ToArgType)) {
2765 // Okay, the types match exactly. Nothing to do.
2766 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2767 ConvertedType, IncompatibleObjC)) {
2768 // Okay, we have an Objective-C pointer conversion.
2769 HasObjCConversion = true;
2770 } else {
2771 // Argument types are too different. Abort.
2772 return false;
2773 }
2774 }
2775
2776 if (HasObjCConversion) {
2777 // We had an Objective-C conversion. Allow this pointer
2778 // conversion, but complain about it.
2779 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2780 IncompatibleObjC = true;
2781 return true;
2782 }
2783 }
2784
2785 return false;
2786}
2787
2788/// Determine whether this is an Objective-C writeback conversion,
2789/// used for parameter passing when performing automatic reference counting.
2790///
2791/// \param FromType The type we're converting form.
2792///
2793/// \param ToType The type we're converting to.
2794///
2795/// \param ConvertedType The type that will be produced after applying
2796/// this conversion.
2797bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2798 QualType &ConvertedType) {
2799 if (!getLangOpts().ObjCAutoRefCount ||
2800 Context.hasSameUnqualifiedType(FromType, ToType))
2801 return false;
2802
2803 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2804 QualType ToPointee;
2805 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2806 ToPointee = ToPointer->getPointeeType();
2807 else
2808 return false;
2809
2810 Qualifiers ToQuals = ToPointee.getQualifiers();
2811 if (!ToPointee->isObjCLifetimeType() ||
2812 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2813 !ToQuals.withoutObjCLifetime().empty())
2814 return false;
2815
2816 // Argument must be a pointer to __strong to __weak.
2817 QualType FromPointee;
2818 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2819 FromPointee = FromPointer->getPointeeType();
2820 else
2821 return false;
2822
2823 Qualifiers FromQuals = FromPointee.getQualifiers();
2824 if (!FromPointee->isObjCLifetimeType() ||
2825 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2826 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2827 return false;
2828
2829 // Make sure that we have compatible qualifiers.
2830 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2831 if (!ToQuals.compatiblyIncludes(FromQuals))
2832 return false;
2833
2834 // Remove qualifiers from the pointee type we're converting from; they
2835 // aren't used in the compatibility check belong, and we'll be adding back
2836 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2837 FromPointee = FromPointee.getUnqualifiedType();
2838
2839 // The unqualified form of the pointee types must be compatible.
2840 ToPointee = ToPointee.getUnqualifiedType();
2841 bool IncompatibleObjC;
2842 if (Context.typesAreCompatible(FromPointee, ToPointee))
2843 FromPointee = ToPointee;
2844 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2845 IncompatibleObjC))
2846 return false;
2847
2848 /// Construct the type we're converting to, which is a pointer to
2849 /// __autoreleasing pointee.
2850 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2851 ConvertedType = Context.getPointerType(FromPointee);
2852 return true;
2853}
2854
2855bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2856 QualType& ConvertedType) {
2857 QualType ToPointeeType;
2858 if (const BlockPointerType *ToBlockPtr =
2859 ToType->getAs<BlockPointerType>())
2860 ToPointeeType = ToBlockPtr->getPointeeType();
2861 else
2862 return false;
2863
2864 QualType FromPointeeType;
2865 if (const BlockPointerType *FromBlockPtr =
2866 FromType->getAs<BlockPointerType>())
2867 FromPointeeType = FromBlockPtr->getPointeeType();
2868 else
2869 return false;
2870 // We have pointer to blocks, check whether the only
2871 // differences in the argument and result types are in Objective-C
2872 // pointer conversions. If so, we permit the conversion.
2873
2874 const FunctionProtoType *FromFunctionType
2875 = FromPointeeType->getAs<FunctionProtoType>();
2876 const FunctionProtoType *ToFunctionType
2877 = ToPointeeType->getAs<FunctionProtoType>();
2878
2879 if (!FromFunctionType || !ToFunctionType)
2880 return false;
2881
2882 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2883 return true;
2884
2885 // Perform the quick checks that will tell us whether these
2886 // function types are obviously different.
2887 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2888 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2889 return false;
2890
2891 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2892 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2893 if (FromEInfo != ToEInfo)
2894 return false;
2895
2896 bool IncompatibleObjC = false;
2897 if (Context.hasSameType(FromFunctionType->getReturnType(),
2898 ToFunctionType->getReturnType())) {
2899 // Okay, the types match exactly. Nothing to do.
2900 } else {
2901 QualType RHS = FromFunctionType->getReturnType();
2902 QualType LHS = ToFunctionType->getReturnType();
2903 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2904 !RHS.hasQualifiers() && LHS.hasQualifiers())
2905 LHS = LHS.getUnqualifiedType();
2906
2907 if (Context.hasSameType(RHS,LHS)) {
2908 // OK exact match.
2909 } else if (isObjCPointerConversion(RHS, LHS,
2910 ConvertedType, IncompatibleObjC)) {
2911 if (IncompatibleObjC)
2912 return false;
2913 // Okay, we have an Objective-C pointer conversion.
2914 }
2915 else
2916 return false;
2917 }
2918
2919 // Check argument types.
2920 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2921 ArgIdx != NumArgs; ++ArgIdx) {
2922 IncompatibleObjC = false;
2923 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2924 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2925 if (Context.hasSameType(FromArgType, ToArgType)) {
2926 // Okay, the types match exactly. Nothing to do.
2927 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2928 ConvertedType, IncompatibleObjC)) {
2929 if (IncompatibleObjC)
2930 return false;
2931 // Okay, we have an Objective-C pointer conversion.
2932 } else
2933 // Argument types are too different. Abort.
2934 return false;
2935 }
2936
2937 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2938 bool CanUseToFPT, CanUseFromFPT;
2939 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2940 CanUseToFPT, CanUseFromFPT,
2941 NewParamInfos))
2942 return false;
2943
2944 ConvertedType = ToType;
2945 return true;
2946}
2947
2948enum {
2949 ft_default,
2950 ft_different_class,
2951 ft_parameter_arity,
2952 ft_parameter_mismatch,
2953 ft_return_type,
2954 ft_qualifer_mismatch,
2955 ft_noexcept
2956};
2957
2958/// Attempts to get the FunctionProtoType from a Type. Handles
2959/// MemberFunctionPointers properly.
2960static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2961 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2962 return FPT;
2963
2964 if (auto *MPT = FromType->getAs<MemberPointerType>())
2965 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2966
2967 return nullptr;
2968}
2969
2970/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2971/// function types. Catches different number of parameter, mismatch in
2972/// parameter types, and different return types.
2973void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2974 QualType FromType, QualType ToType) {
2975 // If either type is not valid, include no extra info.
2976 if (FromType.isNull() || ToType.isNull()) {
2977 PDiag << ft_default;
2978 return;
2979 }
2980
2981 // Get the function type from the pointers.
2982 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2983 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2984 *ToMember = ToType->castAs<MemberPointerType>();
2985 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2986 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2987 << QualType(FromMember->getClass(), 0);
2988 return;
2989 }
2990 FromType = FromMember->getPointeeType();
2991 ToType = ToMember->getPointeeType();
2992 }
2993
2994 if (FromType->isPointerType())
2995 FromType = FromType->getPointeeType();
2996 if (ToType->isPointerType())
2997 ToType = ToType->getPointeeType();
2998
2999 // Remove references.
3000 FromType = FromType.getNonReferenceType();
3001 ToType = ToType.getNonReferenceType();
3002
3003 // Don't print extra info for non-specialized template functions.
3004 if (FromType->isInstantiationDependentType() &&
3005 !FromType->getAs<TemplateSpecializationType>()) {
3006 PDiag << ft_default;
3007 return;
3008 }
3009
3010 // No extra info for same types.
3011 if (Context.hasSameType(FromType, ToType)) {
3012 PDiag << ft_default;
3013 return;
3014 }
3015
3016 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3017 *ToFunction = tryGetFunctionProtoType(ToType);
3018
3019 // Both types need to be function types.
3020 if (!FromFunction || !ToFunction) {
3021 PDiag << ft_default;
3022 return;
3023 }
3024
3025 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3026 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3027 << FromFunction->getNumParams();
3028 return;
3029 }
3030
3031 // Handle different parameter types.
3032 unsigned ArgPos;
3033 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3034 PDiag << ft_parameter_mismatch << ArgPos + 1
3035 << ToFunction->getParamType(ArgPos)
3036 << FromFunction->getParamType(ArgPos);
3037 return;
3038 }
3039
3040 // Handle different return type.
3041 if (!Context.hasSameType(FromFunction->getReturnType(),
3042 ToFunction->getReturnType())) {
3043 PDiag << ft_return_type << ToFunction->getReturnType()
3044 << FromFunction->getReturnType();
3045 return;
3046 }
3047
3048 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3049 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3050 << FromFunction->getMethodQuals();
3051 return;
3052 }
3053
3054 // Handle exception specification differences on canonical type (in C++17
3055 // onwards).
3056 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3057 ->isNothrow() !=
3058 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3059 ->isNothrow()) {
3060 PDiag << ft_noexcept;
3061 return;
3062 }
3063
3064 // Unable to find a difference, so add no extra info.
3065 PDiag << ft_default;
3066}
3067
3068/// FunctionParamTypesAreEqual - This routine checks two function proto types
3069/// for equality of their parameter types. Caller has already checked that
3070/// they have same number of parameters. If the parameters are different,
3071/// ArgPos will have the parameter index of the first different parameter.
3072/// If `Reversed` is true, the parameters of `NewType` will be compared in
3073/// reverse order. That's useful if one of the functions is being used as a C++20
3074/// synthesized operator overload with a reversed parameter order.
3075bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3076 const FunctionProtoType *NewType,
3077 unsigned *ArgPos, bool Reversed) {
3078 assert(OldType->getNumParams() == NewType->getNumParams() &&(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 3080, __extension__ __PRETTY_FUNCTION__
))
3079 "Can't compare parameters of functions with different number of "(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 3080, __extension__ __PRETTY_FUNCTION__
))
3080 "parameters!")(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 3080, __extension__ __PRETTY_FUNCTION__
))
;
3081 for (size_t I = 0; I < OldType->getNumParams(); I++) {
3082 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3083 size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
3084
3085 // Ignore address spaces in pointee type. This is to disallow overloading
3086 // on __ptr32/__ptr64 address spaces.
3087 QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
3088 QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
3089
3090 if (!Context.hasSameType(Old, New)) {
3091 if (ArgPos)
3092 *ArgPos = I;
3093 return false;
3094 }
3095 }
3096 return true;
3097}
3098
3099/// CheckPointerConversion - Check the pointer conversion from the
3100/// expression From to the type ToType. This routine checks for
3101/// ambiguous or inaccessible derived-to-base pointer
3102/// conversions for which IsPointerConversion has already returned
3103/// true. It returns true and produces a diagnostic if there was an
3104/// error, or returns false otherwise.
3105bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3106 CastKind &Kind,
3107 CXXCastPath& BasePath,
3108 bool IgnoreBaseAccess,
3109 bool Diagnose) {
3110 QualType FromType = From->getType();
3111 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3112
3113 Kind = CK_BitCast;
3114
3115 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3116 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3117 Expr::NPCK_ZeroExpression) {
3118 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3119 DiagRuntimeBehavior(From->getExprLoc(), From,
3120 PDiag(diag::warn_impcast_bool_to_null_pointer)
3121 << ToType << From->getSourceRange());
3122 else if (!isUnevaluatedContext())
3123 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3124 << ToType << From->getSourceRange();
3125 }
3126 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3127 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3128 QualType FromPointeeType = FromPtrType->getPointeeType(),
3129 ToPointeeType = ToPtrType->getPointeeType();
3130
3131 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3132 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3133 // We must have a derived-to-base conversion. Check an
3134 // ambiguous or inaccessible conversion.
3135 unsigned InaccessibleID = 0;
3136 unsigned AmbiguousID = 0;
3137 if (Diagnose) {
3138 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3139 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3140 }
3141 if (CheckDerivedToBaseConversion(
3142 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3143 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3144 &BasePath, IgnoreBaseAccess))
3145 return true;
3146
3147 // The conversion was successful.
3148 Kind = CK_DerivedToBase;
3149 }
3150
3151 if (Diagnose && !IsCStyleOrFunctionalCast &&
3152 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3153 assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3154, __extension__ __PRETTY_FUNCTION__
))
3154 "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3154, __extension__ __PRETTY_FUNCTION__
))
;
3155 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3156 << From->getSourceRange();
3157 }
3158 }
3159 } else if (const ObjCObjectPointerType *ToPtrType =
3160 ToType->getAs<ObjCObjectPointerType>()) {
3161 if (const ObjCObjectPointerType *FromPtrType =
3162 FromType->getAs<ObjCObjectPointerType>()) {
3163 // Objective-C++ conversions are always okay.
3164 // FIXME: We should have a different class of conversions for the
3165 // Objective-C++ implicit conversions.
3166 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3167 return false;
3168 } else if (FromType->isBlockPointerType()) {
3169 Kind = CK_BlockPointerToObjCPointerCast;
3170 } else {
3171 Kind = CK_CPointerToObjCPointerCast;
3172 }
3173 } else if (ToType->isBlockPointerType()) {
3174 if (!FromType->isBlockPointerType())
3175 Kind = CK_AnyPointerToBlockPointerCast;
3176 }
3177
3178 // We shouldn't fall into this case unless it's valid for other
3179 // reasons.
3180 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3181 Kind = CK_NullToPointer;
3182
3183 return false;
3184}
3185
3186/// IsMemberPointerConversion - Determines whether the conversion of the
3187/// expression From, which has the (possibly adjusted) type FromType, can be
3188/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3189/// If so, returns true and places the converted type (that might differ from
3190/// ToType in its cv-qualifiers at some level) into ConvertedType.
3191bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3192 QualType ToType,
3193 bool InOverloadResolution,
3194 QualType &ConvertedType) {
3195 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3196 if (!ToTypePtr)
3197 return false;
3198
3199 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3200 if (From->isNullPointerConstant(Context,
3201 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3202 : Expr::NPC_ValueDependentIsNull)) {
3203 ConvertedType = ToType;
3204 return true;
3205 }
3206
3207 // Otherwise, both types have to be member pointers.
3208 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3209 if (!FromTypePtr)
3210 return false;
3211
3212 // A pointer to member of B can be converted to a pointer to member of D,
3213 // where D is derived from B (C++ 4.11p2).
3214 QualType FromClass(FromTypePtr->getClass(), 0);
3215 QualType ToClass(ToTypePtr->getClass(), 0);
3216
3217 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3218 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3219 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3220 ToClass.getTypePtr());
3221 return true;
3222 }
3223
3224 return false;
3225}
3226
3227/// CheckMemberPointerConversion - Check the member pointer conversion from the
3228/// expression From to the type ToType. This routine checks for ambiguous or
3229/// virtual or inaccessible base-to-derived member pointer conversions
3230/// for which IsMemberPointerConversion has already returned true. It returns
3231/// true and produces a diagnostic if there was an error, or returns false
3232/// otherwise.
3233bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3234 CastKind &Kind,
3235 CXXCastPath &BasePath,
3236 bool IgnoreBaseAccess) {
3237 QualType FromType = From->getType();
3238 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3239 if (!FromPtrType) {
3240 // This must be a null pointer to member pointer conversion
3241 assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3243, __extension__ __PRETTY_FUNCTION__
))
3242 Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3243, __extension__ __PRETTY_FUNCTION__
))
3243 "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3243, __extension__ __PRETTY_FUNCTION__
))
;
3244 Kind = CK_NullToMemberPointer;
3245 return false;
3246 }
3247
3248 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3249 assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3250, __extension__ __PRETTY_FUNCTION__
))
3250 "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3250, __extension__ __PRETTY_FUNCTION__
))
;
3251
3252 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3253 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3254
3255 // FIXME: What about dependent types?
3256 assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3256, __extension__ __PRETTY_FUNCTION__
))
;
3257 assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3257, __extension__ __PRETTY_FUNCTION__
))
;
3258
3259 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3260 /*DetectVirtual=*/true);
3261 bool DerivationOkay =
3262 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3263 assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3264, __extension__ __PRETTY_FUNCTION__
))
3264 "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3264, __extension__ __PRETTY_FUNCTION__
))
;
3265 (void)DerivationOkay;
3266
3267 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3268 getUnqualifiedType())) {
3269 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3270 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3271 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3272 return true;
3273 }
3274
3275 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3276 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3277 << FromClass << ToClass << QualType(VBase, 0)
3278 << From->getSourceRange();
3279 return true;
3280 }
3281
3282 if (!IgnoreBaseAccess)
3283 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3284 Paths.front(),
3285 diag::err_downcast_from_inaccessible_base);
3286
3287 // Must be a base to derived member conversion.
3288 BuildBasePathArray(Paths, BasePath);
3289 Kind = CK_BaseToDerivedMemberPointer;
3290 return false;
3291}
3292
3293/// Determine whether the lifetime conversion between the two given
3294/// qualifiers sets is nontrivial.
3295static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3296 Qualifiers ToQuals) {
3297 // Converting anything to const __unsafe_unretained is trivial.
3298 if (ToQuals.hasConst() &&
3299 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3300 return false;
3301
3302 return true;
3303}
3304
3305/// Perform a single iteration of the loop for checking if a qualification
3306/// conversion is valid.
3307///
3308/// Specifically, check whether any change between the qualifiers of \p
3309/// FromType and \p ToType is permissible, given knowledge about whether every
3310/// outer layer is const-qualified.
3311static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3312 bool CStyle, bool IsTopLevel,
3313 bool &PreviousToQualsIncludeConst,
3314 bool &ObjCLifetimeConversion) {
3315 Qualifiers FromQuals = FromType.getQualifiers();
3316 Qualifiers ToQuals = ToType.getQualifiers();
3317
3318 // Ignore __unaligned qualifier.
3319 FromQuals.removeUnaligned();
3320
3321 // Objective-C ARC:
3322 // Check Objective-C lifetime conversions.
3323 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3324 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3325 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3326 ObjCLifetimeConversion = true;
3327 FromQuals.removeObjCLifetime();
3328 ToQuals.removeObjCLifetime();
3329 } else {
3330 // Qualification conversions cannot cast between different
3331 // Objective-C lifetime qualifiers.
3332 return false;
3333 }
3334 }
3335
3336 // Allow addition/removal of GC attributes but not changing GC attributes.
3337 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3338 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3339 FromQuals.removeObjCGCAttr();
3340 ToQuals.removeObjCGCAttr();
3341 }
3342
3343 // -- for every j > 0, if const is in cv 1,j then const is in cv
3344 // 2,j, and similarly for volatile.
3345 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3346 return false;
3347
3348 // If address spaces mismatch:
3349 // - in top level it is only valid to convert to addr space that is a
3350 // superset in all cases apart from C-style casts where we allow
3351 // conversions between overlapping address spaces.
3352 // - in non-top levels it is not a valid conversion.
3353 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3354 (!IsTopLevel ||
3355 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3356 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3357 return false;
3358
3359 // -- if the cv 1,j and cv 2,j are different, then const is in
3360 // every cv for 0 < k < j.
3361 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3362 !PreviousToQualsIncludeConst)
3363 return false;
3364
3365 // The following wording is from C++20, where the result of the conversion
3366 // is T3, not T2.
3367 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3368 // "array of unknown bound of"
3369 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3370 return false;
3371
3372 // -- if the resulting P3,i is different from P1,i [...], then const is
3373 // added to every cv 3_k for 0 < k < i.
3374 if (!CStyle && FromType->isConstantArrayType() &&
3375 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3376 return false;
3377
3378 // Keep track of whether all prior cv-qualifiers in the "to" type
3379 // include const.
3380 PreviousToQualsIncludeConst =
3381 PreviousToQualsIncludeConst && ToQuals.hasConst();
3382 return true;
3383}
3384
3385/// IsQualificationConversion - Determines whether the conversion from
3386/// an rvalue of type FromType to ToType is a qualification conversion
3387/// (C++ 4.4).
3388///
3389/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3390/// when the qualification conversion involves a change in the Objective-C
3391/// object lifetime.
3392bool
3393Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3394 bool CStyle, bool &ObjCLifetimeConversion) {
3395 FromType = Context.getCanonicalType(FromType);
3396 ToType = Context.getCanonicalType(ToType);
3397 ObjCLifetimeConversion = false;
3398
3399 // If FromType and ToType are the same type, this is not a
3400 // qualification conversion.
3401 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3402 return false;
3403
3404 // (C++ 4.4p4):
3405 // A conversion can add cv-qualifiers at levels other than the first
3406 // in multi-level pointers, subject to the following rules: [...]
3407 bool PreviousToQualsIncludeConst = true;
3408 bool UnwrappedAnyPointer = false;
3409 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3410 if (!isQualificationConversionStep(
3411 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3412 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3413 return false;
3414 UnwrappedAnyPointer = true;
3415 }
3416
3417 // We are left with FromType and ToType being the pointee types
3418 // after unwrapping the original FromType and ToType the same number
3419 // of times. If we unwrapped any pointers, and if FromType and
3420 // ToType have the same unqualified type (since we checked
3421 // qualifiers above), then this is a qualification conversion.
3422 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3423}
3424
3425/// - Determine whether this is a conversion from a scalar type to an
3426/// atomic type.
3427///
3428/// If successful, updates \c SCS's second and third steps in the conversion
3429/// sequence to finish the conversion.
3430static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3431 bool InOverloadResolution,
3432 StandardConversionSequence &SCS,
3433 bool CStyle) {
3434 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3435 if (!ToAtomic)
3436 return false;
3437
3438 StandardConversionSequence InnerSCS;
3439 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3440 InOverloadResolution, InnerSCS,
3441 CStyle, /*AllowObjCWritebackConversion=*/false))
3442 return false;
3443
3444 SCS.Second = InnerSCS.Second;
3445 SCS.setToType(1, InnerSCS.getToType(1));
3446 SCS.Third = InnerSCS.Third;
3447 SCS.QualificationIncludesObjCLifetime
3448 = InnerSCS.QualificationIncludesObjCLifetime;
3449 SCS.setToType(2, InnerSCS.getToType(2));
3450 return true;
3451}
3452
3453static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3454 CXXConstructorDecl *Constructor,
3455 QualType Type) {
3456 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3457 if (CtorType->getNumParams() > 0) {
3458 QualType FirstArg = CtorType->getParamType(0);
3459 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3460 return true;
3461 }
3462 return false;
3463}
3464
3465static OverloadingResult
3466IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3467 CXXRecordDecl *To,
3468 UserDefinedConversionSequence &User,
3469 OverloadCandidateSet &CandidateSet,
3470 bool AllowExplicit) {
3471 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3472 for (auto *D : S.LookupConstructors(To)) {
3473 auto Info = getConstructorInfo(D);
3474 if (!Info)
3475 continue;
3476
3477 bool Usable = !Info.Constructor->isInvalidDecl() &&
3478 S.isInitListConstructor(Info.Constructor);
3479 if (Usable) {
3480 bool SuppressUserConversions = false;
3481 if (Info.ConstructorTmpl)
3482 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3483 /*ExplicitArgs*/ nullptr, From,
3484 CandidateSet, SuppressUserConversions,
3485 /*PartialOverloading*/ false,
3486 AllowExplicit);
3487 else
3488 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3489 CandidateSet, SuppressUserConversions,
3490 /*PartialOverloading*/ false, AllowExplicit);
3491 }
3492 }
3493
3494 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3495
3496 OverloadCandidateSet::iterator Best;
3497 switch (auto Result =
3498 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3499 case OR_Deleted:
3500 case OR_Success: {
3501 // Record the standard conversion we used and the conversion function.
3502 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3503 QualType ThisType = Constructor->getThisType();
3504 // Initializer lists don't have conversions as such.
3505 User.Before.setAsIdentityConversion();
3506 User.HadMultipleCandidates = HadMultipleCandidates;
3507 User.ConversionFunction = Constructor;
3508 User.FoundConversionFunction = Best->FoundDecl;
3509 User.After.setAsIdentityConversion();
3510 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3511 User.After.setAllToTypes(ToType);
3512 return Result;
3513 }
3514
3515 case OR_No_Viable_Function:
3516 return OR_No_Viable_Function;
3517 case OR_Ambiguous:
3518 return OR_Ambiguous;
3519 }
3520
3521 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3521)
;
3522}
3523
3524/// Determines whether there is a user-defined conversion sequence
3525/// (C++ [over.ics.user]) that converts expression From to the type
3526/// ToType. If such a conversion exists, User will contain the
3527/// user-defined conversion sequence that performs such a conversion
3528/// and this routine will return true. Otherwise, this routine returns
3529/// false and User is unspecified.
3530///
3531/// \param AllowExplicit true if the conversion should consider C++0x
3532/// "explicit" conversion functions as well as non-explicit conversion
3533/// functions (C++0x [class.conv.fct]p2).
3534///
3535/// \param AllowObjCConversionOnExplicit true if the conversion should
3536/// allow an extra Objective-C pointer conversion on uses of explicit
3537/// constructors. Requires \c AllowExplicit to also be set.
3538static OverloadingResult
3539IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3540 UserDefinedConversionSequence &User,
3541 OverloadCandidateSet &CandidateSet,
3542 AllowedExplicit AllowExplicit,
3543 bool AllowObjCConversionOnExplicit) {
3544 assert(AllowExplicit != AllowedExplicit::None ||(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3545, __extension__ __PRETTY_FUNCTION__
))
3545 !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3545, __extension__ __PRETTY_FUNCTION__
))
;
3546 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3547
3548 // Whether we will only visit constructors.
3549 bool ConstructorsOnly = false;
3550
3551 // If the type we are conversion to is a class type, enumerate its
3552 // constructors.
3553 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3554 // C++ [over.match.ctor]p1:
3555 // When objects of class type are direct-initialized (8.5), or
3556 // copy-initialized from an expression of the same or a
3557 // derived class type (8.5), overload resolution selects the
3558 // constructor. [...] For copy-initialization, the candidate
3559 // functions are all the converting constructors (12.3.1) of
3560 // that class. The argument list is the expression-list within
3561 // the parentheses of the initializer.
3562 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3563 (From->getType()->getAs<RecordType>() &&
3564 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3565 ConstructorsOnly = true;
3566
3567 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3568 // We're not going to find any constructors.
3569 } else if (CXXRecordDecl *ToRecordDecl
3570 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3571
3572 Expr **Args = &From;
3573 unsigned NumArgs = 1;
3574 bool ListInitializing = false;
3575 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3576 // But first, see if there is an init-list-constructor that will work.
3577 OverloadingResult Result = IsInitializerListConstructorConversion(
3578 S, From, ToType, ToRecordDecl, User, CandidateSet,
3579 AllowExplicit == AllowedExplicit::All);
3580 if (Result != OR_No_Viable_Function)
3581 return Result;
3582 // Never mind.
3583 CandidateSet.clear(
3584 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3585
3586 // If we're list-initializing, we pass the individual elements as
3587 // arguments, not the entire list.
3588 Args = InitList->getInits();
3589 NumArgs = InitList->getNumInits();
3590 ListInitializing = true;
3591 }
3592
3593 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3594 auto Info = getConstructorInfo(D);
3595 if (!Info)
3596 continue;
3597
3598 bool Usable = !Info.Constructor->isInvalidDecl();
3599 if (!ListInitializing)
3600 Usable = Usable && Info.Constructor->isConvertingConstructor(
3601 /*AllowExplicit*/ true);
3602 if (Usable) {
3603 bool SuppressUserConversions = !ConstructorsOnly;
3604 // C++20 [over.best.ics.general]/4.5:
3605 // if the target is the first parameter of a constructor [of class
3606 // X] and the constructor [...] is a candidate by [...] the second
3607 // phase of [over.match.list] when the initializer list has exactly
3608 // one element that is itself an initializer list, [...] and the
3609 // conversion is to X or reference to cv X, user-defined conversion
3610 // sequences are not cnosidered.
3611 if (SuppressUserConversions && ListInitializing) {
3612 SuppressUserConversions =
3613 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3614 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3615 ToType);
3616 }
3617 if (Info.ConstructorTmpl)
3618 S.AddTemplateOverloadCandidate(
3619 Info.ConstructorTmpl, Info.FoundDecl,
3620 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3621 CandidateSet, SuppressUserConversions,
3622 /*PartialOverloading*/ false,
3623 AllowExplicit == AllowedExplicit::All);
3624 else
3625 // Allow one user-defined conversion when user specifies a
3626 // From->ToType conversion via an static cast (c-style, etc).
3627 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3628 llvm::makeArrayRef(Args, NumArgs),
3629 CandidateSet, SuppressUserConversions,
3630 /*PartialOverloading*/ false,
3631 AllowExplicit == AllowedExplicit::All);
3632 }
3633 }
3634 }
3635 }
3636
3637 // Enumerate conversion functions, if we're allowed to.
3638 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3639 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3640 // No conversion functions from incomplete types.
3641 } else if (const RecordType *FromRecordType =
3642 From->getType()->getAs<RecordType>()) {
3643 if (CXXRecordDecl *FromRecordDecl
3644 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3645 // Add all of the conversion functions as candidates.
3646 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3647 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3648 DeclAccessPair FoundDecl = I.getPair();
3649 NamedDecl *D = FoundDecl.getDecl();
3650 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3651 if (isa<UsingShadowDecl>(D))
3652 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3653
3654 CXXConversionDecl *Conv;
3655 FunctionTemplateDecl *ConvTemplate;
3656 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3657 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3658 else
3659 Conv = cast<CXXConversionDecl>(D);
3660
3661 if (ConvTemplate)
3662 S.AddTemplateConversionCandidate(
3663 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3664 CandidateSet, AllowObjCConversionOnExplicit,
3665 AllowExplicit != AllowedExplicit::None);
3666 else
3667 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3668 CandidateSet, AllowObjCConversionOnExplicit,
3669 AllowExplicit != AllowedExplicit::None);
3670 }
3671 }
3672 }
3673
3674 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3675
3676 OverloadCandidateSet::iterator Best;
3677 switch (auto Result =
3678 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3679 case OR_Success:
3680 case OR_Deleted:
3681 // Record the standard conversion we used and the conversion function.
3682 if (CXXConstructorDecl *Constructor
3683 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3684 // C++ [over.ics.user]p1:
3685 // If the user-defined conversion is specified by a
3686 // constructor (12.3.1), the initial standard conversion
3687 // sequence converts the source type to the type required by
3688 // the argument of the constructor.
3689 //
3690 QualType ThisType = Constructor->getThisType();
3691 if (isa<InitListExpr>(From)) {
3692 // Initializer lists don't have conversions as such.
3693 User.Before.setAsIdentityConversion();
3694 } else {
3695 if (Best->Conversions[0].isEllipsis())
3696 User.EllipsisConversion = true;
3697 else {
3698 User.Before = Best->Conversions[0].Standard;
3699 User.EllipsisConversion = false;
3700 }
3701 }
3702 User.HadMultipleCandidates = HadMultipleCandidates;
3703 User.ConversionFunction = Constructor;
3704 User.FoundConversionFunction = Best->FoundDecl;
3705 User.After.setAsIdentityConversion();
3706 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3707 User.After.setAllToTypes(ToType);
3708 return Result;
3709 }
3710 if (CXXConversionDecl *Conversion
3711 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3712 // C++ [over.ics.user]p1:
3713 //
3714 // [...] If the user-defined conversion is specified by a
3715 // conversion function (12.3.2), the initial standard
3716 // conversion sequence converts the source type to the
3717 // implicit object parameter of the conversion function.
3718 User.Before = Best->Conversions[0].Standard;
3719 User.HadMultipleCandidates = HadMultipleCandidates;
3720 User.ConversionFunction = Conversion;
3721 User.FoundConversionFunction = Best->FoundDecl;
3722 User.EllipsisConversion = false;
3723
3724 // C++ [over.ics.user]p2:
3725 // The second standard conversion sequence converts the
3726 // result of the user-defined conversion to the target type
3727 // for the sequence. Since an implicit conversion sequence
3728 // is an initialization, the special rules for
3729 // initialization by user-defined conversion apply when
3730 // selecting the best user-defined conversion for a
3731 // user-defined conversion sequence (see 13.3.3 and
3732 // 13.3.3.1).
3733 User.After = Best->FinalConversion;
3734 return Result;
3735 }
3736 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "clang/lib/Sema/SemaOverload.cpp", 3736)
;
3737
3738 case OR_No_Viable_Function:
3739 return OR_No_Viable_Function;
3740
3741 case OR_Ambiguous:
3742 return OR_Ambiguous;
3743 }
3744
3745 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3745)
;
3746}
3747
3748bool
3749Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3750 ImplicitConversionSequence ICS;
3751 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3752 OverloadCandidateSet::CSK_Normal);
3753 OverloadingResult OvResult =
3754 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3755 CandidateSet, AllowedExplicit::None, false);
3756
3757 if (!(OvResult == OR_Ambiguous ||
3758 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3759 return false;
3760
3761 auto Cands = CandidateSet.CompleteCandidates(
3762 *this,
3763 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3764 From);
3765 if (OvResult == OR_Ambiguous)
3766 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3767 << From->getType() << ToType << From->getSourceRange();
3768 else { // OR_No_Viable_Function && !CandidateSet.empty()
3769 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3770 diag::err_typecheck_nonviable_condition_incomplete,
3771 From->getType(), From->getSourceRange()))
3772 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3773 << false << From->getType() << From->getSourceRange() << ToType;
3774 }
3775
3776 CandidateSet.NoteCandidates(
3777 *this, From, Cands);
3778 return true;
3779}
3780
3781// Helper for compareConversionFunctions that gets the FunctionType that the
3782// conversion-operator return value 'points' to, or nullptr.
3783static const FunctionType *
3784getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3785 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3786 const PointerType *RetPtrTy =
3787 ConvFuncTy->getReturnType()->getAs<PointerType>();
3788
3789 if (!RetPtrTy)
3790 return nullptr;
3791
3792 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3793}
3794
3795/// Compare the user-defined conversion functions or constructors
3796/// of two user-defined conversion sequences to determine whether any ordering
3797/// is possible.
3798static ImplicitConversionSequence::CompareKind
3799compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3800 FunctionDecl *Function2) {
3801 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3802 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3803 if (!Conv1 || !Conv2)
3804 return ImplicitConversionSequence::Indistinguishable;
3805
3806 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3807 return ImplicitConversionSequence::Indistinguishable;
3808
3809 // Objective-C++:
3810 // If both conversion functions are implicitly-declared conversions from
3811 // a lambda closure type to a function pointer and a block pointer,
3812 // respectively, always prefer the conversion to a function pointer,
3813 // because the function pointer is more lightweight and is more likely
3814 // to keep code working.
3815 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3816 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3817 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3818 if (Block1 != Block2)
3819 return Block1 ? ImplicitConversionSequence::Worse
3820 : ImplicitConversionSequence::Better;
3821 }
3822
3823 // In order to support multiple calling conventions for the lambda conversion
3824 // operator (such as when the free and member function calling convention is
3825 // different), prefer the 'free' mechanism, followed by the calling-convention
3826 // of operator(). The latter is in place to support the MSVC-like solution of
3827 // defining ALL of the possible conversions in regards to calling-convention.
3828 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3829 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3830
3831 if (Conv1FuncRet && Conv2FuncRet &&
3832 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3833 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3834 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3835
3836 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3837 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3838
3839 CallingConv CallOpCC =
3840 CallOp->getType()->castAs<FunctionType>()->getCallConv();
3841 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3842 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3843 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3844 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3845
3846 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3847 for (CallingConv CC : PrefOrder) {
3848 if (Conv1CC == CC)
3849 return ImplicitConversionSequence::Better;
3850 if (Conv2CC == CC)
3851 return ImplicitConversionSequence::Worse;
3852 }
3853 }
3854
3855 return ImplicitConversionSequence::Indistinguishable;
3856}
3857
3858static bool hasDeprecatedStringLiteralToCharPtrConversion(
3859 const ImplicitConversionSequence &ICS) {
3860 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3861 (ICS.isUserDefined() &&
3862 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3863}
3864
3865/// CompareImplicitConversionSequences - Compare two implicit
3866/// conversion sequences to determine whether one is better than the
3867/// other or if they are indistinguishable (C++ 13.3.3.2).
3868static ImplicitConversionSequence::CompareKind
3869CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3870 const ImplicitConversionSequence& ICS1,
3871 const ImplicitConversionSequence& ICS2)
3872{
3873 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3874 // conversion sequences (as defined in 13.3.3.1)
3875 // -- a standard conversion sequence (13.3.3.1.1) is a better
3876 // conversion sequence than a user-defined conversion sequence or
3877 // an ellipsis conversion sequence, and
3878 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3879 // conversion sequence than an ellipsis conversion sequence
3880 // (13.3.3.1.3).
3881 //
3882 // C++0x [over.best.ics]p10:
3883 // For the purpose of ranking implicit conversion sequences as
3884 // described in 13.3.3.2, the ambiguous conversion sequence is
3885 // treated as a user-defined sequence that is indistinguishable
3886 // from any other user-defined conversion sequence.
3887
3888 // String literal to 'char *' conversion has been deprecated in C++03. It has
3889 // been removed from C++11. We still accept this conversion, if it happens at
3890 // the best viable function. Otherwise, this conversion is considered worse
3891 // than ellipsis conversion. Consider this as an extension; this is not in the
3892 // standard. For example:
3893 //
3894 // int &f(...); // #1
3895 // void f(char*); // #2
3896 // void g() { int &r = f("foo"); }
3897 //
3898 // In C++03, we pick #2 as the best viable function.
3899 // In C++11, we pick #1 as the best viable function, because ellipsis
3900 // conversion is better than string-literal to char* conversion (since there
3901 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3902 // convert arguments, #2 would be the best viable function in C++11.
3903 // If the best viable function has this conversion, a warning will be issued
3904 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3905
3906 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3907 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3908 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3909 // Ill-formedness must not differ
3910 ICS1.isBad() == ICS2.isBad())
3911 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3912 ? ImplicitConversionSequence::Worse
3913 : ImplicitConversionSequence::Better;
3914
3915 if (ICS1.getKindRank() < ICS2.getKindRank())
3916 return ImplicitConversionSequence::Better;
3917 if (ICS2.getKindRank() < ICS1.getKindRank())
3918 return ImplicitConversionSequence::Worse;
3919
3920 // The following checks require both conversion sequences to be of
3921 // the same kind.
3922 if (ICS1.getKind() != ICS2.getKind())
3923 return ImplicitConversionSequence::Indistinguishable;
3924
3925 ImplicitConversionSequence::CompareKind Result =
3926 ImplicitConversionSequence::Indistinguishable;
3927
3928 // Two implicit conversion sequences of the same form are
3929 // indistinguishable conversion sequences unless one of the
3930 // following rules apply: (C++ 13.3.3.2p3):
3931
3932 // List-initialization sequence L1 is a better conversion sequence than
3933 // list-initialization sequence L2 if:
3934 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3935 // if not that,
3936 // — L1 and L2 convert to arrays of the same element type, and either the
3937 // number of elements n_1 initialized by L1 is less than the number of
3938 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3939 // an array of unknown bound and L1 does not,
3940 // even if one of the other rules in this paragraph would otherwise apply.
3941 if (!ICS1.isBad()) {
3942 bool StdInit1 = false, StdInit2 = false;
3943 if (ICS1.hasInitializerListContainerType())
3944 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3945 nullptr);
3946 if (ICS2.hasInitializerListContainerType())
3947 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3948 nullptr);
3949 if (StdInit1 != StdInit2)
3950 return StdInit1 ? ImplicitConversionSequence::Better
3951 : ImplicitConversionSequence::Worse;
3952
3953 if (ICS1.hasInitializerListContainerType() &&
3954 ICS2.hasInitializerListContainerType())
3955 if (auto *CAT1 = S.Context.getAsConstantArrayType(
3956 ICS1.getInitializerListContainerType()))
3957 if (auto *CAT2 = S.Context.getAsConstantArrayType(
3958 ICS2.getInitializerListContainerType())) {
3959 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3960 CAT2->getElementType())) {
3961 // Both to arrays of the same element type
3962 if (CAT1->getSize() != CAT2->getSize())
3963 // Different sized, the smaller wins
3964 return CAT1->getSize().ult(CAT2->getSize())
3965 ? ImplicitConversionSequence::Better
3966 : ImplicitConversionSequence::Worse;
3967 if (ICS1.isInitializerListOfIncompleteArray() !=
3968 ICS2.isInitializerListOfIncompleteArray())
3969 // One is incomplete, it loses
3970 return ICS2.isInitializerListOfIncompleteArray()
3971 ? ImplicitConversionSequence::Better
3972 : ImplicitConversionSequence::Worse;
3973 }
3974 }
3975 }
3976
3977 if (ICS1.isStandard())
3978 // Standard conversion sequence S1 is a better conversion sequence than
3979 // standard conversion sequence S2 if [...]
3980 Result = CompareStandardConversionSequences(S, Loc,
3981 ICS1.Standard, ICS2.Standard);
3982 else if (ICS1.isUserDefined()) {
3983 // User-defined conversion sequence U1 is a better conversion
3984 // sequence than another user-defined conversion sequence U2 if
3985 // they contain the same user-defined conversion function or
3986 // constructor and if the second standard conversion sequence of
3987 // U1 is better than the second standard conversion sequence of
3988 // U2 (C++ 13.3.3.2p3).
3989 if (ICS1.UserDefined.ConversionFunction ==
3990 ICS2.UserDefined.ConversionFunction)
3991 Result = CompareStandardConversionSequences(S, Loc,
3992 ICS1.UserDefined.After,
3993 ICS2.UserDefined.After);
3994 else
3995 Result = compareConversionFunctions(S,
3996 ICS1.UserDefined.ConversionFunction,
3997 ICS2.UserDefined.ConversionFunction);
3998 }
3999
4000 return Result;
4001}
4002
4003// Per 13.3.3.2p3, compare the given standard conversion sequences to
4004// determine if one is a proper subset of the other.
4005static ImplicitConversionSequence::CompareKind
4006compareStandardConversionSubsets(ASTContext &Context,
4007 const StandardConversionSequence& SCS1,
4008 const StandardConversionSequence& SCS2) {
4009 ImplicitConversionSequence::CompareKind Result
4010 = ImplicitConversionSequence::Indistinguishable;
4011
4012 // the identity conversion sequence is considered to be a subsequence of
4013 // any non-identity conversion sequence
4014 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4015 return ImplicitConversionSequence::Better;
4016 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4017 return ImplicitConversionSequence::Worse;
4018
4019 if (SCS1.Second != SCS2.Second) {
4020 if (SCS1.Second == ICK_Identity)
4021 Result = ImplicitConversionSequence::Better;
4022 else if (SCS2.Second == ICK_Identity)
4023 Result = ImplicitConversionSequence::Worse;
4024 else
4025 return ImplicitConversionSequence::Indistinguishable;
4026 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4027 return ImplicitConversionSequence::Indistinguishable;
4028
4029 if (SCS1.Third == SCS2.Third) {
4030 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4031 : ImplicitConversionSequence::Indistinguishable;
4032 }
4033
4034 if (SCS1.Third == ICK_Identity)
4035 return Result == ImplicitConversionSequence::Worse
4036 ? ImplicitConversionSequence::Indistinguishable
4037 : ImplicitConversionSequence::Better;
4038
4039 if (SCS2.Third == ICK_Identity)
4040 return Result == ImplicitConversionSequence::Better
4041 ? ImplicitConversionSequence::Indistinguishable
4042 : ImplicitConversionSequence::Worse;
4043
4044 return ImplicitConversionSequence::Indistinguishable;
4045}
4046
4047/// Determine whether one of the given reference bindings is better
4048/// than the other based on what kind of bindings they are.
4049static bool
4050isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4051 const StandardConversionSequence &SCS2) {
4052 // C++0x [over.ics.rank]p3b4:
4053 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4054 // implicit object parameter of a non-static member function declared
4055 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4056 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4057 // lvalue reference to a function lvalue and S2 binds an rvalue
4058 // reference*.
4059 //
4060 // FIXME: Rvalue references. We're going rogue with the above edits,
4061 // because the semantics in the current C++0x working paper (N3225 at the
4062 // time of this writing) break the standard definition of std::forward
4063 // and std::reference_wrapper when dealing with references to functions.
4064 // Proposed wording changes submitted to CWG for consideration.
4065 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4066 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4067 return false;
4068
4069 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4070 SCS2.IsLvalueReference) ||
4071 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4072 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4073}
4074
4075enum class FixedEnumPromotion {
4076 None,
4077 ToUnderlyingType,
4078 ToPromotedUnderlyingType
4079};
4080
4081/// Returns kind of fixed enum promotion the \a SCS uses.
4082static FixedEnumPromotion
4083getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4084
4085 if (SCS.Second != ICK_Integral_Promotion)
4086 return FixedEnumPromotion::None;
4087
4088 QualType FromType = SCS.getFromType();
4089 if (!FromType->isEnumeralType())
4090 return FixedEnumPromotion::None;
4091
4092 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4093 if (!Enum->isFixed())
4094 return FixedEnumPromotion::None;
4095
4096 QualType UnderlyingType = Enum->getIntegerType();
4097 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4098 return FixedEnumPromotion::ToUnderlyingType;
4099
4100 return FixedEnumPromotion::ToPromotedUnderlyingType;
4101}
4102
4103/// CompareStandardConversionSequences - Compare two standard
4104/// conversion sequences to determine whether one is better than the
4105/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4106static ImplicitConversionSequence::CompareKind
4107CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4108 const StandardConversionSequence& SCS1,
4109 const StandardConversionSequence& SCS2)
4110{
4111 // Standard conversion sequence S1 is a better conversion sequence
4112 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4113
4114 // -- S1 is a proper subsequence of S2 (comparing the conversion
4115 // sequences in the canonical form defined by 13.3.3.1.1,
4116 // excluding any Lvalue Transformation; the identity conversion
4117 // sequence is considered to be a subsequence of any
4118 // non-identity conversion sequence) or, if not that,
4119 if (ImplicitConversionSequence::CompareKind CK
4120 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4121 return CK;
4122
4123 // -- the rank of S1 is better than the rank of S2 (by the rules
4124 // defined below), or, if not that,
4125 ImplicitConversionRank Rank1 = SCS1.getRank();
4126 ImplicitConversionRank Rank2 = SCS2.getRank();
4127 if (Rank1 < Rank2)
4128 return ImplicitConversionSequence::Better;
4129 else if (Rank2 < Rank1)
4130 return ImplicitConversionSequence::Worse;
4131
4132 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4133 // are indistinguishable unless one of the following rules
4134 // applies:
4135
4136 // A conversion that is not a conversion of a pointer, or
4137 // pointer to member, to bool is better than another conversion
4138 // that is such a conversion.
4139 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4140 return SCS2.isPointerConversionToBool()
4141 ? ImplicitConversionSequence::Better
4142 : ImplicitConversionSequence::Worse;
4143
4144 // C++14 [over.ics.rank]p4b2:
4145 // This is retroactively applied to C++11 by CWG 1601.
4146 //
4147 // A conversion that promotes an enumeration whose underlying type is fixed
4148 // to its underlying type is better than one that promotes to the promoted
4149 // underlying type, if the two are different.
4150 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4151 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4152 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4153 FEP1 != FEP2)
4154 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4155 ? ImplicitConversionSequence::Better
4156 : ImplicitConversionSequence::Worse;
4157
4158 // C++ [over.ics.rank]p4b2:
4159 //
4160 // If class B is derived directly or indirectly from class A,
4161 // conversion of B* to A* is better than conversion of B* to
4162 // void*, and conversion of A* to void* is better than conversion
4163 // of B* to void*.
4164 bool SCS1ConvertsToVoid
4165 = SCS1.isPointerConversionToVoidPointer(S.Context);
4166 bool SCS2ConvertsToVoid
4167 = SCS2.isPointerConversionToVoidPointer(S.Context);
4168 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4169 // Exactly one of the conversion sequences is a conversion to
4170 // a void pointer; it's the worse conversion.
4171 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4172 : ImplicitConversionSequence::Worse;
4173 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4174 // Neither conversion sequence converts to a void pointer; compare
4175 // their derived-to-base conversions.
4176 if (ImplicitConversionSequence::CompareKind DerivedCK
4177 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4178 return DerivedCK;
4179 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4180 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4181 // Both conversion sequences are conversions to void
4182 // pointers. Compare the source types to determine if there's an
4183 // inheritance relationship in their sources.
4184 QualType FromType1 = SCS1.getFromType();
4185 QualType FromType2 = SCS2.getFromType();
4186
4187 // Adjust the types we're converting from via the array-to-pointer
4188 // conversion, if we need to.
4189 if (SCS1.First == ICK_Array_To_Pointer)
4190 FromType1 = S.Context.getArrayDecayedType(FromType1);
4191 if (SCS2.First == ICK_Array_To_Pointer)
4192 FromType2 = S.Context.getArrayDecayedType(FromType2);
4193
4194 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4195 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4196
4197 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4198 return ImplicitConversionSequence::Better;
4199 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4200 return ImplicitConversionSequence::Worse;
4201
4202 // Objective-C++: If one interface is more specific than the
4203 // other, it is the better one.
4204 const ObjCObjectPointerType* FromObjCPtr1
4205 = FromType1->getAs<ObjCObjectPointerType>();
4206 const ObjCObjectPointerType* FromObjCPtr2
4207 = FromType2->getAs<ObjCObjectPointerType>();
4208 if (FromObjCPtr1 && FromObjCPtr2) {
4209 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4210 FromObjCPtr2);
4211 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4212 FromObjCPtr1);
4213 if (AssignLeft != AssignRight) {
4214 return AssignLeft? ImplicitConversionSequence::Better
4215 : ImplicitConversionSequence::Worse;
4216 }
4217 }
4218 }
4219
4220 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4221 // Check for a better reference binding based on the kind of bindings.
4222 if (isBetterReferenceBindingKind(SCS1, SCS2))
4223 return ImplicitConversionSequence::Better;
4224 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4225 return ImplicitConversionSequence::Worse;
4226 }
4227
4228 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4229 // bullet 3).
4230 if (ImplicitConversionSequence::CompareKind QualCK
4231 = CompareQualificationConversions(S, SCS1, SCS2))
4232 return QualCK;
4233
4234 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4235 // C++ [over.ics.rank]p3b4:
4236 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4237 // which the references refer are the same type except for
4238 // top-level cv-qualifiers, and the type to which the reference
4239 // initialized by S2 refers is more cv-qualified than the type
4240 // to which the reference initialized by S1 refers.
4241 QualType T1 = SCS1.getToType(2);
4242 QualType T2 = SCS2.getToType(2);
4243 T1 = S.Context.getCanonicalType(T1);
4244 T2 = S.Context.getCanonicalType(T2);
4245 Qualifiers T1Quals, T2Quals;
4246 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4247 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4248 if (UnqualT1 == UnqualT2) {
4249 // Objective-C++ ARC: If the references refer to objects with different
4250 // lifetimes, prefer bindings that don't change lifetime.
4251 if (SCS1.ObjCLifetimeConversionBinding !=
4252 SCS2.ObjCLifetimeConversionBinding) {
4253 return SCS1.ObjCLifetimeConversionBinding
4254 ? ImplicitConversionSequence::Worse
4255 : ImplicitConversionSequence::Better;
4256 }
4257
4258 // If the type is an array type, promote the element qualifiers to the
4259 // type for comparison.
4260 if (isa<ArrayType>(T1) && T1Quals)
4261 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4262 if (isa<ArrayType>(T2) && T2Quals)
4263 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4264 if (T2.isMoreQualifiedThan(T1))
4265 return ImplicitConversionSequence::Better;
4266 if (T1.isMoreQualifiedThan(T2))
4267 return ImplicitConversionSequence::Worse;
4268 }
4269 }
4270
4271 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4272 // floating-to-integral conversion if the integral conversion
4273 // is between types of the same size.
4274 // For example:
4275 // void f(float);
4276 // void f(int);
4277 // int main {
4278 // long a;
4279 // f(a);
4280 // }
4281 // Here, MSVC will call f(int) instead of generating a compile error
4282 // as clang will do in standard mode.
4283 if (S.getLangOpts().MSVCCompat &&
4284 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4285 SCS1.Second == ICK_Integral_Conversion &&
4286 SCS2.Second == ICK_Floating_Integral &&
4287 S.Context.getTypeSize(SCS1.getFromType()) ==
4288 S.Context.getTypeSize(SCS1.getToType(2)))
4289 return ImplicitConversionSequence::Better;
4290
4291 // Prefer a compatible vector conversion over a lax vector conversion
4292 // For example:
4293 //
4294 // typedef float __v4sf __attribute__((__vector_size__(16)));
4295 // void f(vector float);
4296 // void f(vector signed int);
4297 // int main() {
4298 // __v4sf a;
4299 // f(a);
4300 // }
4301 // Here, we'd like to choose f(vector float) and not
4302 // report an ambiguous call error
4303 if (SCS1.Second == ICK_Vector_Conversion &&
4304 SCS2.Second == ICK_Vector_Conversion) {
4305 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4306 SCS1.getFromType(), SCS1.getToType(2));
4307 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4308 SCS2.getFromType(), SCS2.getToType(2));
4309
4310 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4311 return SCS1IsCompatibleVectorConversion
4312 ? ImplicitConversionSequence::Better
4313 : ImplicitConversionSequence::Worse;
4314 }
4315
4316 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4317 SCS2.Second == ICK_SVE_Vector_Conversion) {
4318 bool SCS1IsCompatibleSVEVectorConversion =
4319 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4320 bool SCS2IsCompatibleSVEVectorConversion =
4321 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4322
4323 if (SCS1IsCompatibleSVEVectorConversion !=
4324 SCS2IsCompatibleSVEVectorConversion)
4325 return SCS1IsCompatibleSVEVectorConversion
4326 ? ImplicitConversionSequence::Better
4327 : ImplicitConversionSequence::Worse;
4328 }
4329
4330 return ImplicitConversionSequence::Indistinguishable;
4331}
4332
4333/// CompareQualificationConversions - Compares two standard conversion
4334/// sequences to determine whether they can be ranked based on their
4335/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4336static ImplicitConversionSequence::CompareKind
4337CompareQualificationConversions(Sema &S,
4338 const StandardConversionSequence& SCS1,
4339 const StandardConversionSequence& SCS2) {
4340 // C++ [over.ics.rank]p3:
4341 // -- S1 and S2 differ only in their qualification conversion and
4342 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4343 // [C++98]
4344 // [...] and the cv-qualification signature of type T1 is a proper subset
4345 // of the cv-qualification signature of type T2, and S1 is not the
4346 // deprecated string literal array-to-pointer conversion (4.2).
4347 // [C++2a]
4348 // [...] where T1 can be converted to T2 by a qualification conversion.
4349 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4350 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4351 return ImplicitConversionSequence::Indistinguishable;
4352
4353 // FIXME: the example in the standard doesn't use a qualification
4354 // conversion (!)
4355 QualType T1 = SCS1.getToType(2);
4356 QualType T2 = SCS2.getToType(2);
4357 T1 = S.Context.getCanonicalType(T1);
4358 T2 = S.Context.getCanonicalType(T2);
4359 assert(!T1->isReferenceType() && !T2->isReferenceType())(static_cast <bool> (!T1->isReferenceType() &&
!T2->isReferenceType()) ? void (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "clang/lib/Sema/SemaOverload.cpp", 4359, __extension__ __PRETTY_FUNCTION__
))
;
4360 Qualifiers T1Quals, T2Quals;
4361 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4362 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4363
4364 // If the types are the same, we won't learn anything by unwrapping
4365 // them.
4366 if (UnqualT1 == UnqualT2)
4367 return ImplicitConversionSequence::Indistinguishable;
4368
4369 // Don't ever prefer a standard conversion sequence that uses the deprecated
4370 // string literal array to pointer conversion.
4371 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4372 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4373
4374 // Objective-C++ ARC:
4375 // Prefer qualification conversions not involving a change in lifetime
4376 // to qualification conversions that do change lifetime.
4377 if (SCS1.QualificationIncludesObjCLifetime &&
4378 !SCS2.QualificationIncludesObjCLifetime)
4379 CanPick1 = false;
4380 if (SCS2.QualificationIncludesObjCLifetime &&
4381 !SCS1.QualificationIncludesObjCLifetime)
4382 CanPick2 = false;
4383
4384 bool ObjCLifetimeConversion;
4385 if (CanPick1 &&
4386 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4387 CanPick1 = false;
4388 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4389 // directions, so we can't short-cut this second check in general.
4390 if (CanPick2 &&
4391 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4392 CanPick2 = false;
4393
4394 if (CanPick1 != CanPick2)
4395 return CanPick1 ? ImplicitConversionSequence::Better
4396 : ImplicitConversionSequence::Worse;
4397 return ImplicitConversionSequence::Indistinguishable;
4398}
4399
4400/// CompareDerivedToBaseConversions - Compares two standard conversion
4401/// sequences to determine whether they can be ranked based on their
4402/// various kinds of derived-to-base conversions (C++
4403/// [over.ics.rank]p4b3). As part of these checks, we also look at
4404/// conversions between Objective-C interface types.
4405static ImplicitConversionSequence::CompareKind
4406CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4407 const StandardConversionSequence& SCS1,
4408 const StandardConversionSequence& SCS2) {
4409 QualType FromType1 = SCS1.getFromType();
4410 QualType ToType1 = SCS1.getToType(1);
4411 QualType FromType2 = SCS2.getFromType();
4412 QualType ToType2 = SCS2.getToType(1);
4413
4414 // Adjust the types we're converting from via the array-to-pointer
4415 // conversion, if we need to.
4416 if (SCS1.First == ICK_Array_To_Pointer)
4417 FromType1 = S.Context.getArrayDecayedType(FromType1);
4418 if (SCS2.First == ICK_Array_To_Pointer)
4419 FromType2 = S.Context.getArrayDecayedType(FromType2);
4420
4421 // Canonicalize all of the types.
4422 FromType1 = S.Context.getCanonicalType(FromType1);
4423 ToType1 = S.Context.getCanonicalType(ToType1);
4424 FromType2 = S.Context.getCanonicalType(FromType2);
4425 ToType2 = S.Context.getCanonicalType(ToType2);
4426
4427 // C++ [over.ics.rank]p4b3:
4428 //
4429 // If class B is derived directly or indirectly from class A and
4430 // class C is derived directly or indirectly from B,
4431 //
4432 // Compare based on pointer conversions.
4433 if (SCS1.Second == ICK_Pointer_Conversion &&
4434 SCS2.Second == ICK_Pointer_Conversion &&
4435 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4436 FromType1->isPointerType() && FromType2->isPointerType() &&
4437 ToType1->isPointerType() && ToType2->isPointerType()) {
4438 QualType FromPointee1 =
4439 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4440 QualType ToPointee1 =
4441 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4442 QualType FromPointee2 =
4443 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4444 QualType ToPointee2 =
4445 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4446
4447 // -- conversion of C* to B* is better than conversion of C* to A*,
4448 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4449 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4450 return ImplicitConversionSequence::Better;
4451 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4452 return ImplicitConversionSequence::Worse;
4453 }
4454
4455 // -- conversion of B* to A* is better than conversion of C* to A*,
4456 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4457 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4458 return ImplicitConversionSequence::Better;
4459 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4460 return ImplicitConversionSequence::Worse;
4461 }
4462 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4463 SCS2.Second == ICK_Pointer_Conversion) {
4464 const ObjCObjectPointerType *FromPtr1
4465 = FromType1->getAs<ObjCObjectPointerType>();
4466 const ObjCObjectPointerType *FromPtr2
4467 = FromType2->getAs<ObjCObjectPointerType>();
4468 const ObjCObjectPointerType *ToPtr1
4469 = ToType1->getAs<ObjCObjectPointerType>();
4470 const ObjCObjectPointerType *ToPtr2
4471 = ToType2->getAs<ObjCObjectPointerType>();
4472
4473 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4474 // Apply the same conversion ranking rules for Objective-C pointer types
4475 // that we do for C++ pointers to class types. However, we employ the
4476 // Objective-C pseudo-subtyping relationship used for assignment of
4477 // Objective-C pointer types.
4478 bool FromAssignLeft
4479 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4480 bool FromAssignRight
4481 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4482 bool ToAssignLeft
4483 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4484 bool ToAssignRight
4485 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4486
4487 // A conversion to an a non-id object pointer type or qualified 'id'
4488 // type is better than a conversion to 'id'.
4489 if (ToPtr1->isObjCIdType() &&
4490 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4491 return ImplicitConversionSequence::Worse;
4492 if (ToPtr2->isObjCIdType() &&
4493 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4494 return ImplicitConversionSequence::Better;
4495
4496 // A conversion to a non-id object pointer type is better than a
4497 // conversion to a qualified 'id' type
4498 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4499 return ImplicitConversionSequence::Worse;
4500 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4501 return ImplicitConversionSequence::Better;
4502
4503 // A conversion to an a non-Class object pointer type or qualified 'Class'
4504 // type is better than a conversion to 'Class'.
4505 if (ToPtr1->isObjCClassType() &&
4506 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4507 return ImplicitConversionSequence::Worse;
4508 if (ToPtr2->isObjCClassType() &&
4509 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4510 return ImplicitConversionSequence::Better;
4511
4512 // A conversion to a non-Class object pointer type is better than a
4513 // conversion to a qualified 'Class' type.
4514 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4515 return ImplicitConversionSequence::Worse;
4516 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4517 return ImplicitConversionSequence::Better;
4518
4519 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4520 if (S.Context.hasSameType(FromType1, FromType2) &&
4521 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4522 (ToAssignLeft != ToAssignRight)) {
4523 if (FromPtr1->isSpecialized()) {
4524 // "conversion of B<A> * to B * is better than conversion of B * to
4525 // C *.
4526 bool IsFirstSame =
4527 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4528 bool IsSecondSame =
4529 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4530 if (IsFirstSame) {
4531 if (!IsSecondSame)
4532 return ImplicitConversionSequence::Better;
4533 } else if (IsSecondSame)
4534 return ImplicitConversionSequence::Worse;
4535 }
4536 return ToAssignLeft? ImplicitConversionSequence::Worse
4537 : ImplicitConversionSequence::Better;
4538 }
4539
4540 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4541 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4542 (FromAssignLeft != FromAssignRight))
4543 return FromAssignLeft? ImplicitConversionSequence::Better
4544 : ImplicitConversionSequence::Worse;
4545 }
4546 }
4547
4548 // Ranking of member-pointer types.
4549 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4550 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4551 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4552 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4553 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4554 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4555 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4556 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4557 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4558 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4559 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4560 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4561 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4562 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4563 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4564 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4565 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4566 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4567 return ImplicitConversionSequence::Worse;
4568 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4569 return ImplicitConversionSequence::Better;
4570 }
4571 // conversion of B::* to C::* is better than conversion of A::* to C::*
4572 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4573 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4574 return ImplicitConversionSequence::Better;
4575 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4576 return ImplicitConversionSequence::Worse;
4577 }
4578 }
4579
4580 if (SCS1.Second == ICK_Derived_To_Base) {
4581 // -- conversion of C to B is better than conversion of C to A,
4582 // -- binding of an expression of type C to a reference of type
4583 // B& is better than binding an expression of type C to a
4584 // reference of type A&,
4585 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4586 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4587 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4588 return ImplicitConversionSequence::Better;
4589 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4590 return ImplicitConversionSequence::Worse;
4591 }
4592
4593 // -- conversion of B to A is better than conversion of C to A.
4594 // -- binding of an expression of type B to a reference of type
4595 // A& is better than binding an expression of type C to a
4596 // reference of type A&,
4597 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4598 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4599 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4600 return ImplicitConversionSequence::Better;
4601 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4602 return ImplicitConversionSequence::Worse;
4603 }
4604 }
4605
4606 return ImplicitConversionSequence::Indistinguishable;
4607}
4608
4609static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4610 if (!T.getQualifiers().hasUnaligned())
4611 return T;
4612
4613 Qualifiers Q;
4614 T = Ctx.getUnqualifiedArrayType(T, Q);
4615 Q.removeUnaligned();
4616 return Ctx.getQualifiedType(T, Q);
4617}
4618
4619/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4620/// determine whether they are reference-compatible,
4621/// reference-related, or incompatible, for use in C++ initialization by
4622/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4623/// type, and the first type (T1) is the pointee type of the reference
4624/// type being initialized.
4625Sema::ReferenceCompareResult
4626Sema::CompareReferenceRelationship(SourceLocation Loc,
4627 QualType OrigT1, QualType OrigT2,
4628 ReferenceConversions *ConvOut) {
4629 assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4630, __extension__ __PRETTY_FUNCTION__
))
4630 "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4630, __extension__ __PRETTY_FUNCTION__
))
;
4631 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() &&
"T2 cannot be a reference type") ? void (0) : __assert_fail (
"!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4631, __extension__ __PRETTY_FUNCTION__
))
;
4632
4633 QualType T1 = Context.getCanonicalType(OrigT1);
4634 QualType T2 = Context.getCanonicalType(OrigT2);
4635 Qualifiers T1Quals, T2Quals;
4636 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4637 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4638
4639 ReferenceConversions ConvTmp;
4640 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4641 Conv = ReferenceConversions();
4642
4643 // C++2a [dcl.init.ref]p4:
4644 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4645 // reference-related to "cv2 T2" if T1 is similar to T2, or
4646 // T1 is a base class of T2.
4647 // "cv1 T1" is reference-compatible with "cv2 T2" if
4648 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4649 // "pointer to cv1 T1" via a standard conversion sequence.
4650
4651 // Check for standard conversions we can apply to pointers: derived-to-base
4652 // conversions, ObjC pointer conversions, and function pointer conversions.
4653 // (Qualification conversions are checked last.)
4654 QualType ConvertedT2;
4655 if (UnqualT1 == UnqualT2) {
4656 // Nothing to do.
4657 } else if (isCompleteType(Loc, OrigT2) &&
4658 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4659 Conv |= ReferenceConversions::DerivedToBase;
4660 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4661 UnqualT2->isObjCObjectOrInterfaceType() &&
4662 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4663 Conv |= ReferenceConversions::ObjC;
4664 else if (UnqualT2->isFunctionType() &&
4665 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4666 Conv |= ReferenceConversions::Function;
4667 // No need to check qualifiers; function types don't have them.
4668 return Ref_Compatible;
4669 }
4670 bool ConvertedReferent = Conv != 0;
4671
4672 // We can have a qualification conversion. Compute whether the types are
4673 // similar at the same time.
4674 bool PreviousToQualsIncludeConst = true;
4675 bool TopLevel = true;
4676 do {
4677 if (T1 == T2)
4678 break;
4679
4680 // We will need a qualification conversion.
4681 Conv |= ReferenceConversions::Qualification;
4682
4683 // Track whether we performed a qualification conversion anywhere other
4684 // than the top level. This matters for ranking reference bindings in
4685 // overload resolution.
4686 if (!TopLevel)
4687 Conv |= ReferenceConversions::NestedQualification;
4688
4689 // MS compiler ignores __unaligned qualifier for references; do the same.
4690 T1 = withoutUnaligned(Context, T1);
4691 T2 = withoutUnaligned(Context, T2);
4692
4693 // If we find a qualifier mismatch, the types are not reference-compatible,
4694 // but are still be reference-related if they're similar.
4695 bool ObjCLifetimeConversion = false;
4696 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4697 PreviousToQualsIncludeConst,
4698 ObjCLifetimeConversion))
4699 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4700 ? Ref_Related
4701 : Ref_Incompatible;
4702
4703 // FIXME: Should we track this for any level other than the first?
4704 if (ObjCLifetimeConversion)
4705 Conv |= ReferenceConversions::ObjCLifetime;
4706
4707 TopLevel = false;
4708 } while (Context.UnwrapSimilarTypes(T1, T2));
4709
4710 // At this point, if the types are reference-related, we must either have the
4711 // same inner type (ignoring qualifiers), or must have already worked out how
4712 // to convert the referent.
4713 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4714 ? Ref_Compatible
4715 : Ref_Incompatible;
4716}
4717
4718/// Look for a user-defined conversion to a value reference-compatible
4719/// with DeclType. Return true if something definite is found.
4720static bool
4721FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4722 QualType DeclType, SourceLocation DeclLoc,
4723 Expr *Init, QualType T2, bool AllowRvalues,
4724 bool AllowExplicit) {
4725 assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types."
) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "clang/lib/Sema/SemaOverload.cpp", 4725, __extension__ __PRETTY_FUNCTION__
))
;
4726 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4727
4728 OverloadCandidateSet CandidateSet(
4729 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4730 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4731 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4732 NamedDecl *D = *I;
4733 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4734 if (isa<UsingShadowDecl>(D))
4735 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4736
4737 FunctionTemplateDecl *ConvTemplate
4738 = dyn_cast<FunctionTemplateDecl>(D);
4739 CXXConversionDecl *Conv;
4740 if (ConvTemplate)
4741 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4742 else
4743 Conv = cast<CXXConversionDecl>(D);
4744
4745 if (AllowRvalues) {
4746 // If we are initializing an rvalue reference, don't permit conversion
4747 // functions that return lvalues.
4748 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4749 const ReferenceType *RefType
4750 = Conv->getConversionType()->getAs<LValueReferenceType>();
4751 if (RefType && !RefType->getPointeeType()->isFunctionType())
4752 continue;
4753 }
4754
4755 if (!ConvTemplate &&
4756 S.CompareReferenceRelationship(
4757 DeclLoc,
4758 Conv->getConversionType()
4759 .getNonReferenceType()
4760 .getUnqualifiedType(),
4761 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4762 Sema::Ref_Incompatible)
4763 continue;
4764 } else {
4765 // If the conversion function doesn't return a reference type,
4766 // it can't be considered for this conversion. An rvalue reference
4767 // is only acceptable if its referencee is a function type.
4768
4769 const ReferenceType *RefType =
4770 Conv->getConversionType()->getAs<ReferenceType>();
4771 if (!RefType ||
4772 (!RefType->isLValueReferenceType() &&
4773 !RefType->getPointeeType()->isFunctionType()))
4774 continue;
4775 }
4776
4777 if (ConvTemplate)
4778 S.AddTemplateConversionCandidate(
4779 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4780 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4781 else
4782 S.AddConversionCandidate(
4783 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4784 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4785 }
4786
4787 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4788
4789 OverloadCandidateSet::iterator Best;
4790 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4791 case OR_Success:
4792 // C++ [over.ics.ref]p1:
4793 //
4794 // [...] If the parameter binds directly to the result of
4795 // applying a conversion function to the argument
4796 // expression, the implicit conversion sequence is a
4797 // user-defined conversion sequence (13.3.3.1.2), with the
4798 // second standard conversion sequence either an identity
4799 // conversion or, if the conversion function returns an
4800 // entity of a type that is a derived class of the parameter
4801 // type, a derived-to-base Conversion.
4802 if (!Best->FinalConversion.DirectBinding)
4803 return false;
4804
4805 ICS.setUserDefined();
4806 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4807 ICS.UserDefined.After = Best->FinalConversion;
4808 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4809 ICS.UserDefined.ConversionFunction = Best->Function;
4810 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4811 ICS.UserDefined.EllipsisConversion = false;
4812 assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4814, __extension__ __PRETTY_FUNCTION__
))
4813 ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4814, __extension__ __PRETTY_FUNCTION__
))
4814 "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4814, __extension__ __PRETTY_FUNCTION__
))
;
4815 return true;
4816
4817 case OR_Ambiguous:
4818 ICS.setAmbiguous();
4819 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4820 Cand != CandidateSet.end(); ++Cand)
4821 if (Cand->Best)
4822 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4823 return true;
4824
4825 case OR_No_Viable_Function:
4826 case OR_Deleted:
4827 // There was no suitable conversion, or we found a deleted
4828 // conversion; continue with other checks.
4829 return false;
4830 }
4831
4832 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 4832)
;
4833}
4834
4835/// Compute an implicit conversion sequence for reference
4836/// initialization.
4837static ImplicitConversionSequence
4838TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4839 SourceLocation DeclLoc,
4840 bool SuppressUserConversions,
4841 bool AllowExplicit) {
4842 assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() &&
"Reference init needs a reference") ? void (0) : __assert_fail
("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "clang/lib/Sema/SemaOverload.cpp", 4842, __extension__ __PRETTY_FUNCTION__
))
;
4843
4844 // Most paths end in a failed conversion.
4845 ImplicitConversionSequence ICS;
4846 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4847
4848 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4849 QualType T2 = Init->getType();
4850
4851 // If the initializer is the address of an overloaded function, try
4852 // to resolve the overloaded function. If all goes well, T2 is the
4853 // type of the resulting function.
4854 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4855 DeclAccessPair Found;
4856 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4857 false, Found))
4858 T2 = Fn->getType();
4859 }
4860
4861 // Compute some basic properties of the types and the initializer.
4862 bool isRValRef = DeclType->isRValueReferenceType();
4863 Expr::Classification InitCategory = Init->Classify(S.Context);
4864
4865 Sema::ReferenceConversions RefConv;
4866 Sema::ReferenceCompareResult RefRelationship =
4867 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4868
4869 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4870 ICS.setStandard();
4871 ICS.Standard.First = ICK_Identity;
4872 // FIXME: A reference binding can be a function conversion too. We should
4873 // consider that when ordering reference-to-function bindings.
4874 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4875 ? ICK_Derived_To_Base
4876 : (RefConv & Sema::ReferenceConversions::ObjC)
4877 ? ICK_Compatible_Conversion
4878 : ICK_Identity;
4879 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4880 // a reference binding that performs a non-top-level qualification
4881 // conversion as a qualification conversion, not as an identity conversion.
4882 ICS.Standard.Third = (RefConv &
4883 Sema::ReferenceConversions::NestedQualification)
4884 ? ICK_Qualification
4885 : ICK_Identity;
4886 ICS.Standard.setFromType(T2);
4887 ICS.Standard.setToType(0, T2);
4888 ICS.Standard.setToType(1, T1);
4889 ICS.Standard.setToType(2, T1);
4890 ICS.Standard.ReferenceBinding = true;
4891 ICS.Standard.DirectBinding = BindsDirectly;
4892 ICS.Standard.IsLvalueReference = !isRValRef;
4893 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4894 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4895 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4896 ICS.Standard.ObjCLifetimeConversionBinding =
4897 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4898 ICS.Standard.CopyConstructor = nullptr;
4899 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4900 };
4901
4902 // C++0x [dcl.init.ref]p5:
4903 // A reference to type "cv1 T1" is initialized by an expression
4904 // of type "cv2 T2" as follows:
4905
4906 // -- If reference is an lvalue reference and the initializer expression
4907 if (!isRValRef) {
4908 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4909 // reference-compatible with "cv2 T2," or
4910 //
4911 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4912 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4913 // C++ [over.ics.ref]p1:
4914 // When a parameter of reference type binds directly (8.5.3)
4915 // to an argument expression, the implicit conversion sequence
4916 // is the identity conversion, unless the argument expression
4917 // has a type that is a derived class of the parameter type,
4918 // in which case the implicit conversion sequence is a
4919 // derived-to-base Conversion (13.3.3.1).
4920 SetAsReferenceBinding(/*BindsDirectly=*/true);
4921
4922 // Nothing more to do: the inaccessibility/ambiguity check for
4923 // derived-to-base conversions is suppressed when we're
4924 // computing the implicit conversion sequence (C++
4925 // [over.best.ics]p2).
4926 return ICS;
4927 }
4928
4929 // -- has a class type (i.e., T2 is a class type), where T1 is
4930 // not reference-related to T2, and can be implicitly
4931 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4932 // is reference-compatible with "cv3 T3" 92) (this
4933 // conversion is selected by enumerating the applicable
4934 // conversion functions (13.3.1.6) and choosing the best
4935 // one through overload resolution (13.3)),
4936 if (!SuppressUserConversions && T2->isRecordType() &&
4937 S.isCompleteType(DeclLoc, T2) &&
4938 RefRelationship == Sema::Ref_Incompatible) {
4939 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4940 Init, T2, /*AllowRvalues=*/false,
4941 AllowExplicit))
4942 return ICS;
4943 }
4944 }
4945
4946 // -- Otherwise, the reference shall be an lvalue reference to a
4947 // non-volatile const type (i.e., cv1 shall be const), or the reference
4948 // shall be an rvalue reference.
4949 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4950 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4951 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4952 return ICS;
4953 }
4954
4955 // -- If the initializer expression
4956 //
4957 // -- is an xvalue, class prvalue, array prvalue or function
4958 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4959 if (RefRelationship == Sema::Ref_Compatible &&
4960 (InitCategory.isXValue() ||
4961 (InitCategory.isPRValue() &&
4962 (T2->isRecordType() || T2->isArrayType())) ||
4963 (InitCategory.isLValue() && T2->isFunctionType()))) {
4964 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4965 // binding unless we're binding to a class prvalue.
4966 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4967 // allow the use of rvalue references in C++98/03 for the benefit of
4968 // standard library implementors; therefore, we need the xvalue check here.
4969 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4970 !(InitCategory.isPRValue() || T2->isRecordType()));
4971 return ICS;
4972 }
4973
4974 // -- has a class type (i.e., T2 is a class type), where T1 is not
4975 // reference-related to T2, and can be implicitly converted to
4976 // an xvalue, class prvalue, or function lvalue of type
4977 // "cv3 T3", where "cv1 T1" is reference-compatible with
4978 // "cv3 T3",
4979 //
4980 // then the reference is bound to the value of the initializer
4981 // expression in the first case and to the result of the conversion
4982 // in the second case (or, in either case, to an appropriate base
4983 // class subobject).
4984 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4985 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4986 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4987 Init, T2, /*AllowRvalues=*/true,
4988 AllowExplicit)) {
4989 // In the second case, if the reference is an rvalue reference
4990 // and the second standard conversion sequence of the
4991 // user-defined conversion sequence includes an lvalue-to-rvalue
4992 // conversion, the program is ill-formed.
4993 if (ICS.isUserDefined() && isRValRef &&
4994 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4995 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4996
4997 return ICS;
4998 }
4999
5000 // A temporary of function type cannot be created; don't even try.
5001 if (T1->isFunctionType())
5002 return ICS;
5003
5004 // -- Otherwise, a temporary of type "cv1 T1" is created and
5005 // initialized from the initializer expression using the
5006 // rules for a non-reference copy initialization (8.5). The
5007 // reference is then bound to the temporary. If T1 is
5008 // reference-related to T2, cv1 must be the same
5009 // cv-qualification as, or greater cv-qualification than,
5010 // cv2; otherwise, the program is ill-formed.
5011 if (RefRelationship == Sema::Ref_Related) {
5012 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5013 // we would be reference-compatible or reference-compatible with
5014 // added qualification. But that wasn't the case, so the reference
5015 // initialization fails.
5016 //
5017 // Note that we only want to check address spaces and cvr-qualifiers here.
5018 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5019 Qualifiers T1Quals = T1.getQualifiers();
5020 Qualifiers T2Quals = T2.getQualifiers();
5021 T1Quals.removeObjCGCAttr();
5022 T1Quals.removeObjCLifetime();
5023 T2Quals.removeObjCGCAttr();
5024 T2Quals.removeObjCLifetime();
5025 // MS compiler ignores __unaligned qualifier for references; do the same.
5026 T1Quals.removeUnaligned();
5027 T2Quals.removeUnaligned();
5028 if (!T1Quals.compatiblyIncludes(T2Quals))
5029 return ICS;
5030 }
5031
5032 // If at least one of the types is a class type, the types are not
5033 // related, and we aren't allowed any user conversions, the
5034 // reference binding fails. This case is important for breaking
5035 // recursion, since TryImplicitConversion below will attempt to
5036 // create a temporary through the use of a copy constructor.
5037 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5038 (T1->isRecordType() || T2->isRecordType()))
5039 return ICS;
5040
5041 // If T1 is reference-related to T2 and the reference is an rvalue
5042 // reference, the initializer expression shall not be an lvalue.
5043 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5044 Init->Classify(S.Context).isLValue()) {
5045 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5046 return ICS;
5047 }
5048
5049 // C++ [over.ics.ref]p2:
5050 // When a parameter of reference type is not bound directly to
5051 // an argument expression, the conversion sequence is the one
5052 // required to convert the argument expression to the
5053 // underlying type of the reference according to
5054 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5055 // to copy-initializing a temporary of the underlying type with
5056 // the argument expression. Any difference in top-level
5057 // cv-qualification is subsumed by the initialization itself
5058 // and does not constitute a conversion.
5059 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5060 AllowedExplicit::None,
5061 /*InOverloadResolution=*/false,
5062 /*CStyle=*/false,
5063 /*AllowObjCWritebackConversion=*/false,
5064 /*AllowObjCConversionOnExplicit=*/false);
5065
5066 // Of course, that's still a reference binding.
5067 if (ICS.isStandard()) {
5068 ICS.Standard.ReferenceBinding = true;
5069 ICS.Standard.IsLvalueReference = !isRValRef;
5070 ICS.Standard.BindsToFunctionLvalue = false;
5071 ICS.Standard.BindsToRvalue = true;
5072 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5073 ICS.Standard.ObjCLifetimeConversionBinding = false;
5074 } else if (ICS.isUserDefined()) {
5075 const ReferenceType *LValRefType =
5076 ICS.UserDefined.ConversionFunction->getReturnType()
5077 ->getAs<LValueReferenceType>();
5078
5079 // C++ [over.ics.ref]p3:
5080 // Except for an implicit object parameter, for which see 13.3.1, a
5081 // standard conversion sequence cannot be formed if it requires [...]
5082 // binding an rvalue reference to an lvalue other than a function
5083 // lvalue.
5084 // Note that the function case is not possible here.
5085 if (isRValRef && LValRefType) {
5086 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5087 return ICS;
5088 }
5089
5090 ICS.UserDefined.After.ReferenceBinding = true;
5091 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5092 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5093 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5094 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5095 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5096 }
5097
5098 return ICS;
5099}
5100
5101static ImplicitConversionSequence
5102TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5103 bool SuppressUserConversions,
5104 bool InOverloadResolution,
5105 bool AllowObjCWritebackConversion,
5106 bool AllowExplicit = false);
5107
5108/// TryListConversion - Try to copy-initialize a value of type ToType from the
5109/// initializer list From.
5110static ImplicitConversionSequence
5111TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5112 bool SuppressUserConversions,
5113 bool InOverloadResolution,
5114 bool AllowObjCWritebackConversion) {
5115 // C++11 [over.ics.list]p1:
5116 // When an argument is an initializer list, it is not an expression and
5117 // special rules apply for converting it to a parameter type.
5118
5119 ImplicitConversionSequence Result;
5120 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5121
5122 // We need a complete type for what follows. With one C++20 exception,
5123 // incomplete types can never be initialized from init lists.
5124 QualType InitTy = ToType;
5125 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5126 if (AT && S.getLangOpts().CPlusPlus20)
5127 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5128 // C++20 allows list initialization of an incomplete array type.
5129 InitTy = IAT->getElementType();
5130 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5131 return Result;
5132
5133 // Per DR1467:
5134 // If the parameter type is a class X and the initializer list has a single
5135 // element of type cv U, where U is X or a class derived from X, the
5136 // implicit conversion sequence is the one required to convert the element
5137 // to the parameter type.
5138 //
5139 // Otherwise, if the parameter type is a character array [... ]
5140 // and the initializer list has a single element that is an
5141 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5142 // implicit conversion sequence is the identity conversion.
5143 if (From->getNumInits() == 1) {
5144 if (ToType->isRecordType()) {
5145 QualType InitType = From->getInit(0)->getType();
5146 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5147 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5148 return TryCopyInitialization(S, From->getInit(0), ToType,
5149 SuppressUserConversions,
5150 InOverloadResolution,
5151 AllowObjCWritebackConversion);
5152 }
5153
5154 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5155 InitializedEntity Entity =
5156 InitializedEntity::InitializeParameter(S.Context, ToType,
5157 /*Consumed=*/false);
5158 if (S.CanPerformCopyInitialization(Entity, From)) {
5159 Result.setStandard();
5160 Result.Standard.setAsIdentityConversion();
5161 Result.Standard.setFromType(ToType);
5162 Result.Standard.setAllToTypes(ToType);
5163 return Result;
5164 }
5165 }
5166 }
5167
5168 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5169 // C++11 [over.ics.list]p2:
5170 // If the parameter type is std::initializer_list<X> or "array of X" and
5171 // all the elements can be implicitly converted to X, the implicit
5172 // conversion sequence is the worst conversion necessary to convert an
5173 // element of the list to X.
5174 //
5175 // C++14 [over.ics.list]p3:
5176 // Otherwise, if the parameter type is "array of N X", if the initializer
5177 // list has exactly N elements or if it has fewer than N elements and X is
5178 // default-constructible, and if all the elements of the initializer list
5179 // can be implicitly converted to X, the implicit conversion sequence is
5180 // the worst conversion necessary to convert an element of the list to X.
5181 if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5182 unsigned e = From->getNumInits();
5183 ImplicitConversionSequence DfltElt;
5184 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5185 QualType());
5186 QualType ContTy = ToType;
5187 bool IsUnbounded = false;
5188 if (AT) {
5189 InitTy = AT->getElementType();
5190 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5191 if (CT->getSize().ult(e)) {
5192 // Too many inits, fatally bad
5193 Result.setBad(BadConversionSequence::too_many_initializers, From,
5194 ToType);
5195 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5196 return Result;
5197 }
5198 if (CT->getSize().ugt(e)) {
5199 // Need an init from empty {}, is there one?
5200 InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5201 From->getEndLoc());
5202 EmptyList.setType(S.Context.VoidTy);
5203 DfltElt = TryListConversion(
5204 S, &EmptyList, InitTy, SuppressUserConversions,
5205 InOverloadResolution, AllowObjCWritebackConversion);
5206 if (DfltElt.isBad()) {
5207 // No {} init, fatally bad
5208 Result.setBad(BadConversionSequence::too_few_initializers, From,
5209 ToType);
5210 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5211 return Result;
5212 }
5213 }
5214 } else {
5215 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array")(static_cast <bool> (isa<IncompleteArrayType>(AT)
&& "Expected incomplete array") ? void (0) : __assert_fail
("isa<IncompleteArrayType>(AT) && \"Expected incomplete array\""
, "clang/lib/Sema/SemaOverload.cpp", 5215, __extension__ __PRETTY_FUNCTION__
))
;
5216 IsUnbounded = true;
5217 if (!e) {
5218 // Cannot convert to zero-sized.
5219 Result.setBad(BadConversionSequence::too_few_initializers, From,
5220 ToType);
5221 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5222 return Result;
5223 }
5224 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5225 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5226 ArrayType::Normal, 0);
5227 }
5228 }
5229
5230 Result.setStandard();
5231 Result.Standard.setAsIdentityConversion();
5232 Result.Standard.setFromType(InitTy);
5233 Result.Standard.setAllToTypes(InitTy);
5234 for (unsigned i = 0; i < e; ++i) {
5235 Expr *Init = From->getInit(i);
5236 ImplicitConversionSequence ICS = TryCopyInitialization(
5237 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5238 AllowObjCWritebackConversion);
5239
5240 // Keep the worse conversion seen so far.
5241 // FIXME: Sequences are not totally ordered, so 'worse' can be
5242 // ambiguous. CWG has been informed.
5243 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5244 Result) ==
5245 ImplicitConversionSequence::Worse) {
5246 Result = ICS;
5247 // Bail as soon as we find something unconvertible.
5248 if (Result.isBad()) {
5249 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5250 return Result;
5251 }
5252 }
5253 }
5254
5255 // If we needed any implicit {} initialization, compare that now.
5256 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5257 // has been informed that this might not be the best thing.
5258 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5259 S, From->getEndLoc(), DfltElt, Result) ==
5260 ImplicitConversionSequence::Worse)
5261 Result = DfltElt;
5262 // Record the type being initialized so that we may compare sequences
5263 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5264 return Result;
5265 }
5266
5267 // C++14 [over.ics.list]p4:
5268 // C++11 [over.ics.list]p3:
5269 // Otherwise, if the parameter is a non-aggregate class X and overload
5270 // resolution chooses a single best constructor [...] the implicit
5271 // conversion sequence is a user-defined conversion sequence. If multiple
5272 // constructors are viable but none is better than the others, the
5273 // implicit conversion sequence is a user-defined conversion sequence.
5274 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5275 // This function can deal with initializer lists.
5276 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5277 AllowedExplicit::None,
5278 InOverloadResolution, /*CStyle=*/false,
5279 AllowObjCWritebackConversion,
5280 /*AllowObjCConversionOnExplicit=*/false);
5281 }
5282
5283 // C++14 [over.ics.list]p5:
5284 // C++11 [over.ics.list]p4:
5285 // Otherwise, if the parameter has an aggregate type which can be
5286 // initialized from the initializer list [...] the implicit conversion
5287 // sequence is a user-defined conversion sequence.
5288 if (ToType->isAggregateType()) {
5289 // Type is an aggregate, argument is an init list. At this point it comes
5290 // down to checking whether the initialization works.
5291 // FIXME: Find out whether this parameter is consumed or not.
5292 InitializedEntity Entity =
5293 InitializedEntity::InitializeParameter(S.Context, ToType,
5294 /*Consumed=*/false);
5295 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5296 From)) {
5297 Result.setUserDefined();
5298 Result.UserDefined.Before.setAsIdentityConversion();
5299 // Initializer lists don't have a type.
5300 Result.UserDefined.Before.setFromType(QualType());
5301 Result.UserDefined.Before.setAllToTypes(QualType());
5302
5303 Result.UserDefined.After.setAsIdentityConversion();
5304 Result.UserDefined.After.setFromType(ToType);
5305 Result.UserDefined.After.setAllToTypes(ToType);
5306 Result.UserDefined.ConversionFunction = nullptr;
5307 }
5308 return Result;
5309 }
5310
5311 // C++14 [over.ics.list]p6:
5312 // C++11 [over.ics.list]p5:
5313 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5314 if (ToType->isReferenceType()) {
5315 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5316 // mention initializer lists in any way. So we go by what list-
5317 // initialization would do and try to extrapolate from that.
5318
5319 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5320
5321 // If the initializer list has a single element that is reference-related
5322 // to the parameter type, we initialize the reference from that.
5323 if (From->getNumInits() == 1) {
5324 Expr *Init = From->getInit(0);
5325
5326 QualType T2 = Init->getType();
5327
5328 // If the initializer is the address of an overloaded function, try
5329 // to resolve the overloaded function. If all goes well, T2 is the
5330 // type of the resulting function.
5331 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5332 DeclAccessPair Found;
5333 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5334 Init, ToType, false, Found))
5335 T2 = Fn->getType();
5336 }
5337
5338 // Compute some basic properties of the types and the initializer.
5339 Sema::ReferenceCompareResult RefRelationship =
5340 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5341
5342 if (RefRelationship >= Sema::Ref_Related) {
5343 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5344 SuppressUserConversions,
5345 /*AllowExplicit=*/false);
5346 }
5347 }
5348
5349 // Otherwise, we bind the reference to a temporary created from the
5350 // initializer list.
5351 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5352 InOverloadResolution,
5353 AllowObjCWritebackConversion);
5354 if (Result.isFailure())
5355 return Result;
5356 assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5357, __extension__ __PRETTY_FUNCTION__
))
5357 "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5357, __extension__ __PRETTY_FUNCTION__
))
;
5358
5359 // Can we even bind to a temporary?
5360 if (ToType->isRValueReferenceType() ||
5361 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5362 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5363 Result.UserDefined.After;
5364 SCS.ReferenceBinding = true;
5365 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5366 SCS.BindsToRvalue = true;
5367 SCS.BindsToFunctionLvalue = false;
5368 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5369 SCS.ObjCLifetimeConversionBinding = false;
5370 } else
5371 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5372 From, ToType);
5373 return Result;
5374 }
5375
5376 // C++14 [over.ics.list]p7:
5377 // C++11 [over.ics.list]p6:
5378 // Otherwise, if the parameter type is not a class:
5379 if (!ToType->isRecordType()) {
5380 // - if the initializer list has one element that is not itself an
5381 // initializer list, the implicit conversion sequence is the one
5382 // required to convert the element to the parameter type.
5383 unsigned NumInits = From->getNumInits();
5384 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5385 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5386 SuppressUserConversions,
5387 InOverloadResolution,
5388 AllowObjCWritebackConversion);
5389 // - if the initializer list has no elements, the implicit conversion
5390 // sequence is the identity conversion.
5391 else if (NumInits == 0) {
5392 Result.setStandard();
5393 Result.Standard.setAsIdentityConversion();
5394 Result.Standard.setFromType(ToType);
5395 Result.Standard.setAllToTypes(ToType);
5396 }
5397 return Result;
5398 }
5399
5400 // C++14 [over.ics.list]p8:
5401 // C++11 [over.ics.list]p7:
5402 // In all cases other than those enumerated above, no conversion is possible
5403 return Result;
5404}
5405
5406/// TryCopyInitialization - Try to copy-initialize a value of type
5407/// ToType from the expression From. Return the implicit conversion
5408/// sequence required to pass this argument, which may be a bad
5409/// conversion sequence (meaning that the argument cannot be passed to
5410/// a parameter of this type). If @p SuppressUserConversions, then we
5411/// do not permit any user-defined conversion sequences.
5412static ImplicitConversionSequence
5413TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5414 bool SuppressUserConversions,
5415 bool InOverloadResolution,
5416 bool AllowObjCWritebackConversion,
5417 bool AllowExplicit) {
5418 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5419 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5420 InOverloadResolution,AllowObjCWritebackConversion);
5421
5422 if (ToType->isReferenceType())
5423 return TryReferenceInit(S, From, ToType,
5424 /*FIXME:*/ From->getBeginLoc(),
5425 SuppressUserConversions, AllowExplicit);
5426
5427 return TryImplicitConversion(S, From, ToType,
5428 SuppressUserConversions,
5429 AllowedExplicit::None,
5430 InOverloadResolution,
5431 /*CStyle=*/false,
5432 AllowObjCWritebackConversion,
5433 /*AllowObjCConversionOnExplicit=*/false);
5434}
5435
5436static bool TryCopyInitialization(const CanQualType FromQTy,
5437 const CanQualType ToQTy,
5438 Sema &S,
5439 SourceLocation Loc,
5440 ExprValueKind FromVK) {
5441 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5442 ImplicitConversionSequence ICS =
5443 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5444
5445 return !ICS.isBad();
5446}
5447
5448/// TryObjectArgumentInitialization - Try to initialize the object
5449/// parameter of the given member function (@c Method) from the
5450/// expression @p From.
5451static ImplicitConversionSequence
5452TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5453 Expr::Classification FromClassification,
5454 CXXMethodDecl *Method,
5455 CXXRecordDecl *ActingContext) {
5456 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5457 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5458 // const volatile object.
5459 Qualifiers Quals = Method->getMethodQualifiers();
5460 if (isa<CXXDestructorDecl>(Method)) {
5461 Quals.addConst();
5462 Quals.addVolatile();
5463 }
5464
5465 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5466
5467 // Set up the conversion sequence as a "bad" conversion, to allow us
5468 // to exit early.
5469 ImplicitConversionSequence ICS;
5470
5471 // We need to have an object of class type.
5472 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5473 FromType = PT->getPointeeType();
5474
5475 // When we had a pointer, it's implicitly dereferenced, so we
5476 // better have an lvalue.
5477 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "clang/lib/Sema/SemaOverload.cpp"
, 5477, __extension__ __PRETTY_FUNCTION__))
;
5478 }
5479
5480 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "clang/lib/Sema/SemaOverload.cpp"
, 5480, __extension__ __PRETTY_FUNCTION__))
;
5481
5482 // C++0x [over.match.funcs]p4:
5483 // For non-static member functions, the type of the implicit object
5484 // parameter is
5485 //
5486 // - "lvalue reference to cv X" for functions declared without a
5487 // ref-qualifier or with the & ref-qualifier
5488 // - "rvalue reference to cv X" for functions declared with the &&
5489 // ref-qualifier
5490 //
5491 // where X is the class of which the function is a member and cv is the
5492 // cv-qualification on the member function declaration.
5493 //
5494 // However, when finding an implicit conversion sequence for the argument, we
5495 // are not allowed to perform user-defined conversions
5496 // (C++ [over.match.funcs]p5). We perform a simplified version of
5497 // reference binding here, that allows class rvalues to bind to
5498 // non-constant references.
5499
5500 // First check the qualifiers.
5501 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5502 if (ImplicitParamType.getCVRQualifiers()
5503 != FromTypeCanon.getLocalCVRQualifiers() &&
5504 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5505 ICS.setBad(BadConversionSequence::bad_qualifiers,
5506 FromType, ImplicitParamType);
5507 return ICS;
5508 }
5509
5510 if (FromTypeCanon.hasAddressSpace()) {
5511 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5512 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5513 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5514 ICS.setBad(BadConversionSequence::bad_qualifiers,
5515 FromType, ImplicitParamType);
5516 return ICS;
5517 }
5518 }
5519
5520 // Check that we have either the same type or a derived type. It
5521 // affects the conversion rank.
5522 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5523 ImplicitConversionKind SecondKind;
5524 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5525 SecondKind = ICK_Identity;
5526 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5527 SecondKind = ICK_Derived_To_Base;
5528 else {
5529 ICS.setBad(BadConversionSequence::unrelated_class,
5530 FromType, ImplicitParamType);
5531 return ICS;
5532 }
5533
5534 // Check the ref-qualifier.
5535 switch (Method->getRefQualifier()) {
5536 case RQ_None:
5537 // Do nothing; we don't care about lvalueness or rvalueness.
5538 break;
5539
5540 case RQ_LValue:
5541 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5542 // non-const lvalue reference cannot bind to an rvalue
5543 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5544 ImplicitParamType);
5545 return ICS;
5546 }
5547 break;
5548
5549 case RQ_RValue:
5550 if (!FromClassification.isRValue()) {
5551 // rvalue reference cannot bind to an lvalue
5552 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5553 ImplicitParamType);
5554 return ICS;
5555 }
5556 break;
5557 }
5558
5559 // Success. Mark this as a reference binding.
5560 ICS.setStandard();
5561 ICS.Standard.setAsIdentityConversion();
5562 ICS.Standard.Second = SecondKind;
5563 ICS.Standard.setFromType(FromType);
5564 ICS.Standard.setAllToTypes(ImplicitParamType);
5565 ICS.Standard.ReferenceBinding = true;
5566 ICS.Standard.DirectBinding = true;
5567 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5568 ICS.Standard.BindsToFunctionLvalue = false;
5569 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5570 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5571 = (Method->getRefQualifier() == RQ_None);
5572 return ICS;
5573}
5574
5575/// PerformObjectArgumentInitialization - Perform initialization of
5576/// the implicit object parameter for the given Method with the given
5577/// expression.
5578ExprResult
5579Sema::PerformObjectArgumentInitialization(Expr *From,
5580 NestedNameSpecifier *Qualifier,
5581 NamedDecl *FoundDecl,
5582 CXXMethodDecl *Method) {
5583 QualType FromRecordType, DestType;
5584 QualType ImplicitParamRecordType =
5585 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5586
5587 Expr::Classification FromClassification;
5588 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5589 FromRecordType = PT->getPointeeType();
5590 DestType = Method->getThisType();
5591 FromClassification = Expr::Classification::makeSimpleLValue();
5592 } else {
5593 FromRecordType = From->getType();
5594 DestType = ImplicitParamRecordType;
5595 FromClassification = From->Classify(Context);
5596
5597 // When performing member access on a prvalue, materialize a temporary.
5598 if (From->isPRValue()) {
5599 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5600 Method->getRefQualifier() !=
5601 RefQualifierKind::RQ_RValue);
5602 }
5603 }
5604
5605 // Note that we always use the true parent context when performing
5606 // the actual argument initialization.
5607 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5608 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5609 Method->getParent());
5610 if (ICS.isBad()) {
5611 switch (ICS.Bad.Kind) {
5612 case BadConversionSequence::bad_qualifiers: {
5613 Qualifiers FromQs = FromRecordType.getQualifiers();
5614 Qualifiers ToQs = DestType.getQualifiers();
5615 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5616 if (CVR) {
5617 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5618 << Method->getDeclName() << FromRecordType << (CVR - 1)
5619 << From->getSourceRange();
5620 Diag(Method->getLocation(), diag::note_previous_decl)
5621 << Method->getDeclName();
5622 return ExprError();
5623 }
5624 break;
5625 }
5626
5627 case BadConversionSequence::lvalue_ref_to_rvalue:
5628 case BadConversionSequence::rvalue_ref_to_lvalue: {
5629 bool IsRValueQualified =
5630 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5631 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5632 << Method->getDeclName() << FromClassification.isRValue()
5633 << IsRValueQualified;
5634 Diag(Method->getLocation(), diag::note_previous_decl)
5635 << Method->getDeclName();
5636 return ExprError();
5637 }
5638
5639 case BadConversionSequence::no_conversion:
5640 case BadConversionSequence::unrelated_class:
5641 break;
5642
5643 case BadConversionSequence::too_few_initializers:
5644 case BadConversionSequence::too_many_initializers:
5645 llvm_unreachable("Lists are not objects")::llvm::llvm_unreachable_internal("Lists are not objects", "clang/lib/Sema/SemaOverload.cpp"
, 5645)
;
5646 }
5647
5648 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5649 << ImplicitParamRecordType << FromRecordType
5650 << From->getSourceRange();
5651 }
5652
5653 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5654 ExprResult FromRes =
5655 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5656 if (FromRes.isInvalid())
5657 return ExprError();
5658 From = FromRes.get();
5659 }
5660
5661 if (!Context.hasSameType(From->getType(), DestType)) {
5662 CastKind CK;
5663 QualType PteeTy = DestType->getPointeeType();
5664 LangAS DestAS =
5665 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5666 if (FromRecordType.getAddressSpace() != DestAS)
5667 CK = CK_AddressSpaceConversion;
5668 else
5669 CK = CK_NoOp;
5670 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5671 }
5672 return From;
5673}
5674
5675/// TryContextuallyConvertToBool - Attempt to contextually convert the
5676/// expression From to bool (C++0x [conv]p3).
5677static ImplicitConversionSequence
5678TryContextuallyConvertToBool(Sema &S, Expr *From) {
5679 // C++ [dcl.init]/17.8:
5680 // - Otherwise, if the initialization is direct-initialization, the source
5681 // type is std::nullptr_t, and the destination type is bool, the initial
5682 // value of the object being initialized is false.
5683 if (From->getType()->isNullPtrType())
5684 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5685 S.Context.BoolTy,
5686 From->isGLValue());
5687
5688 // All other direct-initialization of bool is equivalent to an implicit
5689 // conversion to bool in which explicit conversions are permitted.
5690 return TryImplicitConversion(S, From, S.Context.BoolTy,
5691 /*SuppressUserConversions=*/false,
5692 AllowedExplicit::Conversions,
5693 /*InOverloadResolution=*/false,
5694 /*CStyle=*/false,
5695 /*AllowObjCWritebackConversion=*/false,
5696 /*AllowObjCConversionOnExplicit=*/false);
5697}
5698
5699/// PerformContextuallyConvertToBool - Perform a contextual conversion
5700/// of the expression From to bool (C++0x [conv]p3).
5701ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5702 if (checkPlaceholderForOverload(*this, From))
5703 return ExprError();
5704
5705 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5706 if (!ICS.isBad())
5707 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5708
5709 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5710 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5711 << From->getType() << From->getSourceRange();
5712 return ExprError();
5713}
5714
5715/// Check that the specified conversion is permitted in a converted constant
5716/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5717/// is acceptable.
5718static bool CheckConvertedConstantConversions(Sema &S,
5719 StandardConversionSequence &SCS) {
5720 // Since we know that the target type is an integral or unscoped enumeration
5721 // type, most conversion kinds are impossible. All possible First and Third
5722 // conversions are fine.
5723 switch (SCS.Second) {
5724 case ICK_Identity:
5725 case ICK_Integral_Promotion:
5726 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5727 case ICK_Zero_Queue_Conversion:
5728 return true;
5729
5730 case ICK_Boolean_Conversion:
5731 // Conversion from an integral or unscoped enumeration type to bool is
5732 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5733 // conversion, so we allow it in a converted constant expression.
5734 //
5735 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5736 // a lot of popular code. We should at least add a warning for this
5737 // (non-conforming) extension.
5738 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5739 SCS.getToType(2)->isBooleanType();
5740
5741 case ICK_Pointer_Conversion:
5742 case ICK_Pointer_Member:
5743 // C++1z: null pointer conversions and null member pointer conversions are
5744 // only permitted if the source type is std::nullptr_t.
5745 return SCS.getFromType()->isNullPtrType();
5746
5747 case ICK_Floating_Promotion:
5748 case ICK_Complex_Promotion:
5749 case ICK_Floating_Conversion:
5750 case ICK_Complex_Conversion:
5751 case ICK_Floating_Integral:
5752 case ICK_Compatible_Conversion:
5753 case ICK_Derived_To_Base:
5754 case ICK_Vector_Conversion:
5755 case ICK_SVE_Vector_Conversion:
5756 case ICK_Vector_Splat:
5757 case ICK_Complex_Real:
5758 case ICK_Block_Pointer_Conversion:
5759 case ICK_TransparentUnionConversion:
5760 case ICK_Writeback_Conversion:
5761 case ICK_Zero_Event_Conversion:
5762 case ICK_C_Only_Conversion:
5763 case ICK_Incompatible_Pointer_Conversion:
5764 return false;
5765
5766 case ICK_Lvalue_To_Rvalue:
5767 case ICK_Array_To_Pointer:
5768 case ICK_Function_To_Pointer:
5769 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5769)
;
5770
5771 case ICK_Function_Conversion:
5772 case ICK_Qualification:
5773 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5773)
;
5774
5775 case ICK_Num_Conversion_Kinds:
5776 break;
5777 }
5778
5779 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "clang/lib/Sema/SemaOverload.cpp"
, 5779)
;
5780}
5781
5782/// CheckConvertedConstantExpression - Check that the expression From is a
5783/// converted constant expression of type T, perform the conversion and produce
5784/// the converted expression, per C++11 [expr.const]p3.
5785static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5786 QualType T, APValue &Value,
5787 Sema::CCEKind CCE,
5788 bool RequireInt,
5789 NamedDecl *Dest) {
5790 assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5791, __extension__ __PRETTY_FUNCTION__
))
5791 "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5791, __extension__ __PRETTY_FUNCTION__
))
;
5792
5793 if (checkPlaceholderForOverload(S, From))
5794 return ExprError();
5795
5796 // C++1z [expr.const]p3:
5797 // A converted constant expression of type T is an expression,
5798 // implicitly converted to type T, where the converted
5799 // expression is a constant expression and the implicit conversion
5800 // sequence contains only [... list of conversions ...].
5801 ImplicitConversionSequence ICS =
5802 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5803 ? TryContextuallyConvertToBool(S, From)
5804 : TryCopyInitialization(S, From, T,
5805 /*SuppressUserConversions=*/false,
5806 /*InOverloadResolution=*/false,
5807 /*AllowObjCWritebackConversion=*/false,
5808 /*AllowExplicit=*/false);
5809 StandardConversionSequence *SCS = nullptr;
5810 switch (ICS.getKind()) {
5811 case ImplicitConversionSequence::StandardConversion:
5812 SCS = &ICS.Standard;
5813 break;
5814 case ImplicitConversionSequence::UserDefinedConversion:
5815 if (T->isRecordType())
5816 SCS = &ICS.UserDefined.Before;
5817 else
5818 SCS = &ICS.UserDefined.After;
5819 break;
5820 case ImplicitConversionSequence::AmbiguousConversion:
5821 case ImplicitConversionSequence::BadConversion:
5822 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5823 return S.Diag(From->getBeginLoc(),
5824 diag::err_typecheck_converted_constant_expression)
5825 << From->getType() << From->getSourceRange() << T;
5826 return ExprError();
5827
5828 case ImplicitConversionSequence::EllipsisConversion:
5829 case ImplicitConversionSequence::StaticObjectArgumentConversion:
5830 llvm_unreachable("bad conversion in converted constant expression")::llvm::llvm_unreachable_internal("bad conversion in converted constant expression"
, "clang/lib/Sema/SemaOverload.cpp", 5830)
;
5831 }
5832
5833 // Check that we would only use permitted conversions.
5834 if (!CheckConvertedConstantConversions(S, *SCS)) {
5835 return S.Diag(From->getBeginLoc(),
5836 diag::err_typecheck_converted_constant_expression_disallowed)
5837 << From->getType() << From->getSourceRange() << T;
5838 }
5839 // [...] and where the reference binding (if any) binds directly.
5840 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5841 return S.Diag(From->getBeginLoc(),
5842 diag::err_typecheck_converted_constant_expression_indirect)
5843 << From->getType() << From->getSourceRange() << T;
5844 }
5845
5846 // Usually we can simply apply the ImplicitConversionSequence we formed
5847 // earlier, but that's not guaranteed to work when initializing an object of
5848 // class type.
5849 ExprResult Result;
5850 if (T->isRecordType()) {
5851 assert(CCE == Sema::CCEK_TemplateArg &&(static_cast <bool> (CCE == Sema::CCEK_TemplateArg &&
"unexpected class type converted constant expr") ? void (0) :
__assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "clang/lib/Sema/SemaOverload.cpp", 5852, __extension__ __PRETTY_FUNCTION__
))
5852 "unexpected class type converted constant expr")(static_cast <bool> (CCE == Sema::CCEK_TemplateArg &&
"unexpected class type converted constant expr") ? void (0) :
__assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "clang/lib/Sema/SemaOverload.cpp", 5852, __extension__ __PRETTY_FUNCTION__
))
;
5853 Result = S.PerformCopyInitialization(
5854 InitializedEntity::InitializeTemplateParameter(
5855 T, cast<NonTypeTemplateParmDecl>(Dest)),
5856 SourceLocation(), From);
5857 } else {
5858 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5859 }
5860 if (Result.isInvalid())
5861 return Result;
5862
5863 // C++2a [intro.execution]p5:
5864 // A full-expression is [...] a constant-expression [...]
5865 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5866 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
5867 CCE == Sema::CCEKind::CCEK_TemplateArg);
5868 if (Result.isInvalid())
5869 return Result;
5870
5871 // Check for a narrowing implicit conversion.
5872 bool ReturnPreNarrowingValue = false;
5873 APValue PreNarrowingValue;
5874 QualType PreNarrowingType;
5875 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5876 PreNarrowingType)) {
5877 case NK_Dependent_Narrowing:
5878 // Implicit conversion to a narrower type, but the expression is
5879 // value-dependent so we can't tell whether it's actually narrowing.
5880 case NK_Variable_Narrowing:
5881 // Implicit conversion to a narrower type, and the value is not a constant
5882 // expression. We'll diagnose this in a moment.
5883