Bug Summary

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