Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaOverload.cpp
Warning:line 9956, column 44
Called C++ object pointer is null

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