Bug Summary

File:clang/include/clang/Sema/Sema.h
Warning:line 1776, column 12
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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaOverload.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaOverload.cpp

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