Bug Summary

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