Bug Summary

File:tools/clang/lib/Sema/SemaOverload.cpp
Warning:line 12668, column 21
Although the value stored to 'RHS' is used in the enclosing expression, the value is never actually read from 'RHS'

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