Bug Summary

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

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