Bug Summary

File:clang/lib/Sema/SemaOverload.cpp
Warning:line 9476, column 44
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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