Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaOverload.cpp
Warning:line 13884, 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 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaOverload.cpp
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/CXXInheritance.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/DependenceFlags.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeOrdering.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/DiagnosticOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
32#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/Optional.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallPtrSet.h"
36#include "llvm/ADT/SmallString.h"
37#include <algorithm>
38#include <cstdlib>
39
40using namespace clang;
41using namespace sema;
42
43using AllowedExplicit = Sema::AllowedExplicit;
44
45static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47 return P->hasAttr<PassObjectSizeAttr>();
48 });
49}
50
51/// A convenience routine for creating a decayed reference to a function.
52static ExprResult CreateFunctionRefExpr(
53 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
54 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
55 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
56 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
57 return ExprError();
58 // If FoundDecl is different from Fn (such as if one is a template
59 // and the other a specialization), make sure DiagnoseUseOfDecl is
60 // called on both.
61 // FIXME: This would be more comprehensively addressed by modifying
62 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
63 // being used.
64 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
65 return ExprError();
66 DeclRefExpr *DRE = new (S.Context)
67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
70
71 S.MarkDeclRefReferenced(DRE, Base);
72 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
73 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
74 S.ResolveExceptionSpec(Loc, FPT);
75 DRE->setType(Fn->getType());
76 }
77 }
78 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
79 CK_FunctionToPointerDecay);
80}
81
82static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
85 bool CStyle,
86 bool AllowObjCWritebackConversion);
87
88static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
89 QualType &ToType,
90 bool InOverloadResolution,
91 StandardConversionSequence &SCS,
92 bool CStyle);
93static OverloadingResult
94IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
95 UserDefinedConversionSequence& User,
96 OverloadCandidateSet& Conversions,
97 AllowedExplicit AllowExplicit,
98 bool AllowObjCConversionOnExplicit);
99
100static ImplicitConversionSequence::CompareKind
101CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
106CompareQualificationConversions(Sema &S,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
110static ImplicitConversionSequence::CompareKind
111CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
115/// GetConversionRank - Retrieve the implicit conversion rank
116/// corresponding to the given implicit conversion kind.
117ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
118 static const ImplicitConversionRank
119 Rank[(int)ICK_Num_Conversion_Kinds] = {
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Promotion,
127 ICR_Promotion,
128 ICR_Promotion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_OCL_Scalar_Widening,
141 ICR_Complex_Real_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Writeback_Conversion,
145 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146 // it was omitted by the patch that added
147 // ICK_Zero_Event_Conversion
148 ICR_C_Conversion,
149 ICR_C_Conversion_Extension
150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
162 "Function pointer conversion",
163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
166 "Complex promotion",
167 "Integral conversion",
168 "Floating conversion",
169 "Complex conversion",
170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
173 "Boolean conversion",
174 "Compatible-types conversion",
175 "Derived-to-base conversion",
176 "Vector conversion",
177 "SVE Vector conversion",
178 "Vector splat",
179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion",
182 "Writeback conversion",
183 "OpenCL Zero Event Conversion",
184 "C specific type conversion",
185 "Incompatible pointer conversion"
186 };
187 return Name[Kind];
188}
189
190/// StandardConversionSequence - Set the standard conversion
191/// sequence to the identity conversion.
192void StandardConversionSequence::setAsIdentityConversion() {
193 First = ICK_Identity;
194 Second = ICK_Identity;
195 Third = ICK_Identity;
196 DeprecatedStringLiteralToCharPtr = false;
197 QualificationIncludesObjCLifetime = false;
198 ReferenceBinding = false;
199 DirectBinding = false;
200 IsLvalueReference = true;
201 BindsToFunctionLvalue = false;
202 BindsToRvalue = false;
203 BindsImplicitObjectArgumentWithoutRefQualifier = false;
204 ObjCLifetimeConversionBinding = false;
205 CopyConstructor = nullptr;
206}
207
208/// getRank - Retrieve the rank of this standard conversion sequence
209/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
210/// implicit conversions.
211ImplicitConversionRank StandardConversionSequence::getRank() const {
212 ImplicitConversionRank Rank = ICR_Exact_Match;
213 if (GetConversionRank(First) > Rank)
214 Rank = GetConversionRank(First);
215 if (GetConversionRank(Second) > Rank)
216 Rank = GetConversionRank(Second);
217 if (GetConversionRank(Third) > Rank)
218 Rank = GetConversionRank(Third);
219 return Rank;
220}
221
222/// isPointerConversionToBool - Determines whether this conversion is
223/// a conversion of a pointer or pointer-to-member to bool. This is
224/// used as part of the ranking of standard conversion sequences
225/// (C++ 13.3.3.2p4).
226bool StandardConversionSequence::isPointerConversionToBool() const {
227 // Note that FromType has not necessarily been transformed by the
228 // array-to-pointer or function-to-pointer implicit conversions, so
229 // check for their presence as well as checking whether FromType is
230 // a pointer.
231 if (getToType(1)->isBooleanType() &&
232 (getFromType()->isPointerType() ||
233 getFromType()->isMemberPointerType() ||
234 getFromType()->isObjCObjectPointerType() ||
235 getFromType()->isBlockPointerType() ||
236 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
237 return true;
238
239 return false;
240}
241
242/// isPointerConversionToVoidPointer - Determines whether this
243/// conversion is a conversion of a pointer to a void pointer. This is
244/// used as part of the ranking of standard conversion sequences (C++
245/// 13.3.3.2p4).
246bool
247StandardConversionSequence::
248isPointerConversionToVoidPointer(ASTContext& Context) const {
249 QualType FromType = getFromType();
250 QualType ToType = getToType(1);
251
252 // Note that FromType has not necessarily been transformed by the
253 // array-to-pointer implicit conversion, so check for its presence
254 // and redo the conversion to get a pointer.
255 if (First == ICK_Array_To_Pointer)
256 FromType = Context.getArrayDecayedType(FromType);
257
258 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
259 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
260 return ToPtrType->getPointeeType()->isVoidType();
261
262 return false;
263}
264
265/// Skip any implicit casts which could be either part of a narrowing conversion
266/// or after one in an implicit conversion.
267static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
268 const Expr *Converted) {
269 // We can have cleanups wrapping the converted expression; these need to be
270 // preserved so that destructors run if necessary.
271 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
272 Expr *Inner =
273 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
274 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
275 EWC->getObjects());
276 }
277
278 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
279 switch (ICE->getCastKind()) {
280 case CK_NoOp:
281 case CK_IntegralCast:
282 case CK_IntegralToBoolean:
283 case CK_IntegralToFloating:
284 case CK_BooleanToSignedIntegral:
285 case CK_FloatingToIntegral:
286 case CK_FloatingToBoolean:
287 case CK_FloatingCast:
288 Converted = ICE->getSubExpr();
289 continue;
290
291 default:
292 return Converted;
293 }
294 }
295
296 return Converted;
297}
298
299/// Check if this standard conversion sequence represents a narrowing
300/// conversion, according to C++11 [dcl.init.list]p7.
301///
302/// \param Ctx The AST context.
303/// \param Converted The result of applying this standard conversion sequence.
304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305/// value of the expression prior to the narrowing conversion.
306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307/// type of the expression prior to the narrowing conversion.
308/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
309/// from floating point types to integral types should be ignored.
310NarrowingKind StandardConversionSequence::getNarrowingKind(
311 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
312 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus &&
"narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "clang/lib/Sema/SemaOverload.cpp", 313, __extension__ __PRETTY_FUNCTION__
))
;
314
315 // C++11 [dcl.init.list]p7:
316 // A narrowing conversion is an implicit conversion ...
317 QualType FromType = getToType(0);
318 QualType ToType = getToType(1);
319
320 // A conversion to an enumeration type is narrowing if the conversion to
321 // the underlying type is narrowing. This only arises for expressions of
322 // the form 'Enum{init}'.
323 if (auto *ET = ToType->getAs<EnumType>())
324 ToType = ET->getDecl()->getIntegerType();
325
326 switch (Second) {
327 // 'bool' is an integral type; dispatch to the right place to handle it.
328 case ICK_Boolean_Conversion:
329 if (FromType->isRealFloatingType())
330 goto FloatingIntegralConversion;
331 if (FromType->isIntegralOrUnscopedEnumerationType())
332 goto IntegralConversion;
333 // -- from a pointer type or pointer-to-member type to bool, or
334 return NK_Type_Narrowing;
335
336 // -- from a floating-point type to an integer type, or
337 //
338 // -- from an integer type or unscoped enumeration type to a floating-point
339 // type, except where the source is a constant expression and the actual
340 // value after conversion will fit into the target type and will produce
341 // the original value when converted back to the original type, or
342 case ICK_Floating_Integral:
343 FloatingIntegralConversion:
344 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
345 return NK_Type_Narrowing;
346 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
347 ToType->isRealFloatingType()) {
348 if (IgnoreFloatToIntegralConversion)
349 return NK_Not_Narrowing;
350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351 assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression"
) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "clang/lib/Sema/SemaOverload.cpp", 351, __extension__ __PRETTY_FUNCTION__
))
;
352
353 // If it's value-dependent, we can't tell whether it's narrowing.
354 if (Initializer->isValueDependent())
355 return NK_Dependent_Narrowing;
356
357 if (Optional<llvm::APSInt> IntConstantValue =
358 Initializer->getIntegerConstantExpr(Ctx)) {
359 // Convert the integer to the floating type.
360 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
361 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
362 llvm::APFloat::rmNearestTiesToEven);
363 // And back.
364 llvm::APSInt ConvertedValue = *IntConstantValue;
365 bool ignored;
366 Result.convertToInteger(ConvertedValue,
367 llvm::APFloat::rmTowardZero, &ignored);
368 // If the resulting value is different, this was a narrowing conversion.
369 if (*IntConstantValue != ConvertedValue) {
370 ConstantValue = APValue(*IntConstantValue);
371 ConstantType = Initializer->getType();
372 return NK_Constant_Narrowing;
373 }
374 } else {
375 // Variables are always narrowings.
376 return NK_Variable_Narrowing;
377 }
378 }
379 return NK_Not_Narrowing;
380
381 // -- from long double to double or float, or from double to float, except
382 // where the source is a constant expression and the actual value after
383 // conversion is within the range of values that can be represented (even
384 // if it cannot be represented exactly), or
385 case ICK_Floating_Conversion:
386 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
387 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
388 // FromType is larger than ToType.
389 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
390
391 // If it's value-dependent, we can't tell whether it's narrowing.
392 if (Initializer->isValueDependent())
393 return NK_Dependent_Narrowing;
394
395 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
396 // Constant!
397 assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0
) : __assert_fail ("ConstantValue.isFloat()", "clang/lib/Sema/SemaOverload.cpp"
, 397, __extension__ __PRETTY_FUNCTION__))
;
398 llvm::APFloat FloatVal = ConstantValue.getFloat();
399 // Convert the source value into the target type.
400 bool ignored;
401 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
402 Ctx.getFloatTypeSemantics(ToType),
403 llvm::APFloat::rmNearestTiesToEven, &ignored);
404 // If there was no overflow, the source value is within the range of
405 // values that can be represented.
406 if (ConvertStatus & llvm::APFloat::opOverflow) {
407 ConstantType = Initializer->getType();
408 return NK_Constant_Narrowing;
409 }
410 } else {
411 return NK_Variable_Narrowing;
412 }
413 }
414 return NK_Not_Narrowing;
415
416 // -- from an integer type or unscoped enumeration type to an integer type
417 // that cannot represent all the values of the original type, except where
418 // the source is a constant expression and the actual value after
419 // conversion will fit into the target type and will produce the original
420 // value when converted back to the original type.
421 case ICK_Integral_Conversion:
422 IntegralConversion: {
423 assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 423, __extension__ __PRETTY_FUNCTION__
))
;
424 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 424, __extension__ __PRETTY_FUNCTION__
))
;
425 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
426 const unsigned FromWidth = Ctx.getIntWidth(FromType);
427 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
428 const unsigned ToWidth = Ctx.getIntWidth(ToType);
429
430 if (FromWidth > ToWidth ||
431 (FromWidth == ToWidth && FromSigned != ToSigned) ||
432 (FromSigned && !ToSigned)) {
433 // Not all values of FromType can be represented in ToType.
434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435
436 // If it's value-dependent, we can't tell whether it's narrowing.
437 if (Initializer->isValueDependent())
438 return NK_Dependent_Narrowing;
439
440 Optional<llvm::APSInt> OptInitializerValue;
441 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
442 // Such conversions on variables are always narrowing.
443 return NK_Variable_Narrowing;
444 }
445 llvm::APSInt &InitializerValue = *OptInitializerValue;
446 bool Narrowing = false;
447 if (FromWidth < ToWidth) {
448 // Negative -> unsigned is narrowing. Otherwise, more bits is never
449 // narrowing.
450 if (InitializerValue.isSigned() && InitializerValue.isNegative())
451 Narrowing = true;
452 } else {
453 // Add a bit to the InitializerValue so we don't have to worry about
454 // signed vs. unsigned comparisons.
455 InitializerValue = InitializerValue.extend(
456 InitializerValue.getBitWidth() + 1);
457 // Convert the initializer to and from the target width and signed-ness.
458 llvm::APSInt ConvertedValue = InitializerValue;
459 ConvertedValue = ConvertedValue.trunc(ToWidth);
460 ConvertedValue.setIsSigned(ToSigned);
461 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
462 ConvertedValue.setIsSigned(InitializerValue.isSigned());
463 // If the result is different, this was a narrowing conversion.
464 if (ConvertedValue != InitializerValue)
465 Narrowing = true;
466 }
467 if (Narrowing) {
468 ConstantType = Initializer->getType();
469 ConstantValue = APValue(InitializerValue);
470 return NK_Constant_Narrowing;
471 }
472 }
473 return NK_Not_Narrowing;
474 }
475
476 default:
477 // Other kinds of conversions are not narrowings.
478 return NK_Not_Narrowing;
479 }
480}
481
482/// dump - Print this standard conversion sequence to standard
483/// error. Useful for debugging overloading issues.
484LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
485 raw_ostream &OS = llvm::errs();
486 bool PrintedSomething = false;
487 if (First != ICK_Identity) {
488 OS << GetImplicitConversionName(First);
489 PrintedSomething = true;
490 }
491
492 if (Second != ICK_Identity) {
493 if (PrintedSomething) {
494 OS << " -> ";
495 }
496 OS << GetImplicitConversionName(Second);
497
498 if (CopyConstructor) {
499 OS << " (by copy constructor)";
500 } else if (DirectBinding) {
501 OS << " (direct reference binding)";
502 } else if (ReferenceBinding) {
503 OS << " (reference binding)";
504 }
505 PrintedSomething = true;
506 }
507
508 if (Third != ICK_Identity) {
509 if (PrintedSomething) {
510 OS << " -> ";
511 }
512 OS << GetImplicitConversionName(Third);
513 PrintedSomething = true;
514 }
515
516 if (!PrintedSomething) {
517 OS << "No conversions required";
518 }
519}
520
521/// dump - Print this user-defined conversion sequence to standard
522/// error. Useful for debugging overloading issues.
523void UserDefinedConversionSequence::dump() const {
524 raw_ostream &OS = llvm::errs();
525 if (Before.First || Before.Second || Before.Third) {
526 Before.dump();
527 OS << " -> ";
528 }
529 if (ConversionFunction)
530 OS << '\'' << *ConversionFunction << '\'';
531 else
532 OS << "aggregate initialization";
533 if (After.First || After.Second || After.Third) {
534 OS << " -> ";
535 After.dump();
536 }
537}
538
539/// dump - Print this implicit conversion sequence to standard
540/// error. Useful for debugging overloading issues.
541void ImplicitConversionSequence::dump() const {
542 raw_ostream &OS = llvm::errs();
543 if (hasInitializerListContainerType())
544 OS << "Worst list element conversion: ";
545 switch (ConversionKind) {
546 case StandardConversion:
547 OS << "Standard conversion: ";
548 Standard.dump();
549 break;
550 case UserDefinedConversion:
551 OS << "User-defined conversion: ";
552 UserDefined.dump();
553 break;
554 case EllipsisConversion:
555 OS << "Ellipsis conversion";
556 break;
557 case AmbiguousConversion:
558 OS << "Ambiguous conversion";
559 break;
560 case BadConversion:
561 OS << "Bad conversion";
562 break;
563 }
564
565 OS << "\n";
566}
567
568void AmbiguousConversionSequence::construct() {
569 new (&conversions()) ConversionSet();
570}
571
572void AmbiguousConversionSequence::destruct() {
573 conversions().~ConversionSet();
574}
575
576void
577AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
578 FromTypePtr = O.FromTypePtr;
579 ToTypePtr = O.ToTypePtr;
580 new (&conversions()) ConversionSet(O.conversions());
581}
582
583namespace {
584 // Structure used by DeductionFailureInfo to store
585 // template argument information.
586 struct DFIArguments {
587 TemplateArgument FirstArg;
588 TemplateArgument SecondArg;
589 };
590 // Structure used by DeductionFailureInfo to store
591 // template parameter and template argument information.
592 struct DFIParamWithArguments : DFIArguments {
593 TemplateParameter Param;
594 };
595 // Structure used by DeductionFailureInfo to store template argument
596 // information and the index of the problematic call argument.
597 struct DFIDeducedMismatchArgs : DFIArguments {
598 TemplateArgumentList *TemplateArgs;
599 unsigned CallArgIndex;
600 };
601 // Structure used by DeductionFailureInfo to store information about
602 // unsatisfied constraints.
603 struct CNSInfo {
604 TemplateArgumentList *TemplateArgs;
605 ConstraintSatisfaction Satisfaction;
606 };
607}
608
609/// Convert from Sema's representation of template deduction information
610/// to the form used in overload-candidate information.
611DeductionFailureInfo
612clang::MakeDeductionFailureInfo(ASTContext &Context,
613 Sema::TemplateDeductionResult TDK,
614 TemplateDeductionInfo &Info) {
615 DeductionFailureInfo Result;
616 Result.Result = static_cast<unsigned>(TDK);
617 Result.HasDiagnostic = false;
618 switch (TDK) {
619 case Sema::TDK_Invalid:
620 case Sema::TDK_InstantiationDepth:
621 case Sema::TDK_TooManyArguments:
622 case Sema::TDK_TooFewArguments:
623 case Sema::TDK_MiscellaneousDeductionFailure:
624 case Sema::TDK_CUDATargetMismatch:
625 Result.Data = nullptr;
626 break;
627
628 case Sema::TDK_Incomplete:
629 case Sema::TDK_InvalidExplicitArguments:
630 Result.Data = Info.Param.getOpaqueValue();
631 break;
632
633 case Sema::TDK_DeducedMismatch:
634 case Sema::TDK_DeducedMismatchNested: {
635 // FIXME: Should allocate from normal heap so that we can free this later.
636 auto *Saved = new (Context) DFIDeducedMismatchArgs;
637 Saved->FirstArg = Info.FirstArg;
638 Saved->SecondArg = Info.SecondArg;
639 Saved->TemplateArgs = Info.take();
640 Saved->CallArgIndex = Info.CallArgIndex;
641 Result.Data = Saved;
642 break;
643 }
644
645 case Sema::TDK_NonDeducedMismatch: {
646 // FIXME: Should allocate from normal heap so that we can free this later.
647 DFIArguments *Saved = new (Context) DFIArguments;
648 Saved->FirstArg = Info.FirstArg;
649 Saved->SecondArg = Info.SecondArg;
650 Result.Data = Saved;
651 break;
652 }
653
654 case Sema::TDK_IncompletePack:
655 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
656 case Sema::TDK_Inconsistent:
657 case Sema::TDK_Underqualified: {
658 // FIXME: Should allocate from normal heap so that we can free this later.
659 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
660 Saved->Param = Info.Param;
661 Saved->FirstArg = Info.FirstArg;
662 Saved->SecondArg = Info.SecondArg;
663 Result.Data = Saved;
664 break;
665 }
666
667 case Sema::TDK_SubstitutionFailure:
668 Result.Data = Info.take();
669 if (Info.hasSFINAEDiagnostic()) {
670 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
671 SourceLocation(), PartialDiagnostic::NullDiagnostic());
672 Info.takeSFINAEDiagnostic(*Diag);
673 Result.HasDiagnostic = true;
674 }
675 break;
676
677 case Sema::TDK_ConstraintsNotSatisfied: {
678 CNSInfo *Saved = new (Context) CNSInfo;
679 Saved->TemplateArgs = Info.take();
680 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
681 Result.Data = Saved;
682 break;
683 }
684
685 case Sema::TDK_Success:
686 case Sema::TDK_NonDependentConversionFailure:
687 case Sema::TDK_AlreadyDiagnosed:
688 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "clang/lib/Sema/SemaOverload.cpp"
, 688)
;
689 }
690
691 return Result;
692}
693
694void DeductionFailureInfo::Destroy() {
695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696 case Sema::TDK_Success:
697 case Sema::TDK_Invalid:
698 case Sema::TDK_InstantiationDepth:
699 case Sema::TDK_Incomplete:
700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
702 case Sema::TDK_InvalidExplicitArguments:
703 case Sema::TDK_CUDATargetMismatch:
704 case Sema::TDK_NonDependentConversionFailure:
705 break;
706
707 case Sema::TDK_IncompletePack:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_DeducedMismatch:
711 case Sema::TDK_DeducedMismatchNested:
712 case Sema::TDK_NonDeducedMismatch:
713 // FIXME: Destroy the data?
714 Data = nullptr;
715 break;
716
717 case Sema::TDK_SubstitutionFailure:
718 // FIXME: Destroy the template argument list?
719 Data = nullptr;
720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721 Diag->~PartialDiagnosticAt();
722 HasDiagnostic = false;
723 }
724 break;
725
726 case Sema::TDK_ConstraintsNotSatisfied:
727 // FIXME: Destroy the template argument list?
728 Data = nullptr;
729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730 Diag->~PartialDiagnosticAt();
731 HasDiagnostic = false;
732 }
733 break;
734
735 // Unhandled
736 case Sema::TDK_MiscellaneousDeductionFailure:
737 case Sema::TDK_AlreadyDiagnosed:
738 break;
739 }
740}
741
742PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
743 if (HasDiagnostic)
744 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
745 return nullptr;
746}
747
748TemplateParameter DeductionFailureInfo::getTemplateParameter() {
749 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
750 case Sema::TDK_Success:
751 case Sema::TDK_Invalid:
752 case Sema::TDK_InstantiationDepth:
753 case Sema::TDK_TooManyArguments:
754 case Sema::TDK_TooFewArguments:
755 case Sema::TDK_SubstitutionFailure:
756 case Sema::TDK_DeducedMismatch:
757 case Sema::TDK_DeducedMismatchNested:
758 case Sema::TDK_NonDeducedMismatch:
759 case Sema::TDK_CUDATargetMismatch:
760 case Sema::TDK_NonDependentConversionFailure:
761 case Sema::TDK_ConstraintsNotSatisfied:
762 return TemplateParameter();
763
764 case Sema::TDK_Incomplete:
765 case Sema::TDK_InvalidExplicitArguments:
766 return TemplateParameter::getFromOpaqueValue(Data);
767
768 case Sema::TDK_IncompletePack:
769 case Sema::TDK_Inconsistent:
770 case Sema::TDK_Underqualified:
771 return static_cast<DFIParamWithArguments*>(Data)->Param;
772
773 // Unhandled
774 case Sema::TDK_MiscellaneousDeductionFailure:
775 case Sema::TDK_AlreadyDiagnosed:
776 break;
777 }
778
779 return TemplateParameter();
780}
781
782TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
783 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
784 case Sema::TDK_Success:
785 case Sema::TDK_Invalid:
786 case Sema::TDK_InstantiationDepth:
787 case Sema::TDK_TooManyArguments:
788 case Sema::TDK_TooFewArguments:
789 case Sema::TDK_Incomplete:
790 case Sema::TDK_IncompletePack:
791 case Sema::TDK_InvalidExplicitArguments:
792 case Sema::TDK_Inconsistent:
793 case Sema::TDK_Underqualified:
794 case Sema::TDK_NonDeducedMismatch:
795 case Sema::TDK_CUDATargetMismatch:
796 case Sema::TDK_NonDependentConversionFailure:
797 return nullptr;
798
799 case Sema::TDK_DeducedMismatch:
800 case Sema::TDK_DeducedMismatchNested:
801 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
802
803 case Sema::TDK_SubstitutionFailure:
804 return static_cast<TemplateArgumentList*>(Data);
805
806 case Sema::TDK_ConstraintsNotSatisfied:
807 return static_cast<CNSInfo*>(Data)->TemplateArgs;
808
809 // Unhandled
810 case Sema::TDK_MiscellaneousDeductionFailure:
811 case Sema::TDK_AlreadyDiagnosed:
812 break;
813 }
814
815 return nullptr;
816}
817
818const TemplateArgument *DeductionFailureInfo::getFirstArg() {
819 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
820 case Sema::TDK_Success:
821 case Sema::TDK_Invalid:
822 case Sema::TDK_InstantiationDepth:
823 case Sema::TDK_Incomplete:
824 case Sema::TDK_TooManyArguments:
825 case Sema::TDK_TooFewArguments:
826 case Sema::TDK_InvalidExplicitArguments:
827 case Sema::TDK_SubstitutionFailure:
828 case Sema::TDK_CUDATargetMismatch:
829 case Sema::TDK_NonDependentConversionFailure:
830 case Sema::TDK_ConstraintsNotSatisfied:
831 return nullptr;
832
833 case Sema::TDK_IncompletePack:
834 case Sema::TDK_Inconsistent:
835 case Sema::TDK_Underqualified:
836 case Sema::TDK_DeducedMismatch:
837 case Sema::TDK_DeducedMismatchNested:
838 case Sema::TDK_NonDeducedMismatch:
839 return &static_cast<DFIArguments*>(Data)->FirstArg;
840
841 // Unhandled
842 case Sema::TDK_MiscellaneousDeductionFailure:
843 case Sema::TDK_AlreadyDiagnosed:
844 break;
845 }
846
847 return nullptr;
848}
849
850const TemplateArgument *DeductionFailureInfo::getSecondArg() {
851 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
852 case Sema::TDK_Success:
853 case Sema::TDK_Invalid:
854 case Sema::TDK_InstantiationDepth:
855 case Sema::TDK_Incomplete:
856 case Sema::TDK_IncompletePack:
857 case Sema::TDK_TooManyArguments:
858 case Sema::TDK_TooFewArguments:
859 case Sema::TDK_InvalidExplicitArguments:
860 case Sema::TDK_SubstitutionFailure:
861 case Sema::TDK_CUDATargetMismatch:
862 case Sema::TDK_NonDependentConversionFailure:
863 case Sema::TDK_ConstraintsNotSatisfied:
864 return nullptr;
865
866 case Sema::TDK_Inconsistent:
867 case Sema::TDK_Underqualified:
868 case Sema::TDK_DeducedMismatch:
869 case Sema::TDK_DeducedMismatchNested:
870 case Sema::TDK_NonDeducedMismatch:
871 return &static_cast<DFIArguments*>(Data)->SecondArg;
872
873 // Unhandled
874 case Sema::TDK_MiscellaneousDeductionFailure:
875 case Sema::TDK_AlreadyDiagnosed:
876 break;
877 }
878
879 return nullptr;
880}
881
882llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
883 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
884 case Sema::TDK_DeducedMismatch:
885 case Sema::TDK_DeducedMismatchNested:
886 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
887
888 default:
889 return llvm::None;
890 }
891}
892
893bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
894 OverloadedOperatorKind Op) {
895 if (!AllowRewrittenCandidates)
896 return false;
897 return Op == OO_EqualEqual || Op == OO_Spaceship;
898}
899
900bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
901 ASTContext &Ctx, const FunctionDecl *FD) {
902 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
903 return false;
904 // Don't bother adding a reversed candidate that can never be a better
905 // match than the non-reversed version.
906 return FD->getNumParams() != 2 ||
907 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
908 FD->getParamDecl(1)->getType()) ||
909 FD->hasAttr<EnableIfAttr>();
910}
911
912void OverloadCandidateSet::destroyCandidates() {
913 for (iterator i = begin(), e = end(); i != e; ++i) {
914 for (auto &C : i->Conversions)
915 C.~ImplicitConversionSequence();
916 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
917 i->DeductionFailure.Destroy();
918 }
919}
920
921void OverloadCandidateSet::clear(CandidateSetKind CSK) {
922 destroyCandidates();
923 SlabAllocator.Reset();
924 NumInlineBytesUsed = 0;
925 Candidates.clear();
926 Functions.clear();
927 Kind = CSK;
928}
929
930namespace {
931 class UnbridgedCastsSet {
932 struct Entry {
933 Expr **Addr;
934 Expr *Saved;
935 };
936 SmallVector<Entry, 2> Entries;
937
938 public:
939 void save(Sema &S, Expr *&E) {
940 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType
::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "clang/lib/Sema/SemaOverload.cpp", 940, __extension__ __PRETTY_FUNCTION__
))
;
941 Entry entry = { &E, E };
942 Entries.push_back(entry);
943 E = S.stripARCUnbridgedCast(E);
944 }
945
946 void restore() {
947 for (SmallVectorImpl<Entry>::iterator
948 i = Entries.begin(), e = Entries.end(); i != e; ++i)
949 *i->Addr = i->Saved;
950 }
951 };
952}
953
954/// checkPlaceholderForOverload - Do any interesting placeholder-like
955/// preprocessing on the given expression.
956///
957/// \param unbridgedCasts a collection to which to add unbridged casts;
958/// without this, they will be immediately diagnosed as errors
959///
960/// Return true on unrecoverable error.
961static bool
962checkPlaceholderForOverload(Sema &S, Expr *&E,
963 UnbridgedCastsSet *unbridgedCasts = nullptr) {
964 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
965 // We can't handle overloaded expressions here because overload
966 // resolution might reasonably tweak them.
967 if (placeholder->getKind() == BuiltinType::Overload) return false;
968
969 // If the context potentially accepts unbridged ARC casts, strip
970 // the unbridged cast and add it to the collection for later restoration.
971 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
972 unbridgedCasts) {
973 unbridgedCasts->save(S, E);
974 return false;
975 }
976
977 // Go ahead and check everything else.
978 ExprResult result = S.CheckPlaceholderExpr(E);
979 if (result.isInvalid())
980 return true;
981
982 E = result.get();
983 return false;
984 }
985
986 // Nothing to do.
987 return false;
988}
989
990/// checkArgPlaceholdersForOverload - Check a set of call operands for
991/// placeholders.
992static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
993 UnbridgedCastsSet &unbridged) {
994 for (unsigned i = 0, e = Args.size(); i != e; ++i)
995 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
996 return true;
997
998 return false;
999}
1000
1001/// Determine whether the given New declaration is an overload of the
1002/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1003/// New and Old cannot be overloaded, e.g., if New has the same signature as
1004/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1005/// functions (or function templates) at all. When it does return Ovl_Match or
1006/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1007/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1008/// declaration.
1009///
1010/// Example: Given the following input:
1011///
1012/// void f(int, float); // #1
1013/// void f(int, int); // #2
1014/// int f(int, int); // #3
1015///
1016/// When we process #1, there is no previous declaration of "f", so IsOverload
1017/// will not be used.
1018///
1019/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1020/// the parameter types, we see that #1 and #2 are overloaded (since they have
1021/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1022/// unchanged.
1023///
1024/// When we process #3, Old is an overload set containing #1 and #2. We compare
1025/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1026/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1027/// functions are not part of the signature), IsOverload returns Ovl_Match and
1028/// MatchedDecl will be set to point to the FunctionDecl for #2.
1029///
1030/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1031/// by a using declaration. The rules for whether to hide shadow declarations
1032/// ignore some properties which otherwise figure into a function template's
1033/// signature.
1034Sema::OverloadKind
1035Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1036 NamedDecl *&Match, bool NewIsUsingDecl) {
1037 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1038 I != E; ++I) {
1039 NamedDecl *OldD = *I;
1040
1041 bool OldIsUsingDecl = false;
1042 if (isa<UsingShadowDecl>(OldD)) {
1043 OldIsUsingDecl = true;
1044
1045 // We can always introduce two using declarations into the same
1046 // context, even if they have identical signatures.
1047 if (NewIsUsingDecl) continue;
1048
1049 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1050 }
1051
1052 // A using-declaration does not conflict with another declaration
1053 // if one of them is hidden.
1054 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1055 continue;
1056
1057 // If either declaration was introduced by a using declaration,
1058 // we'll need to use slightly different rules for matching.
1059 // Essentially, these rules are the normal rules, except that
1060 // function templates hide function templates with different
1061 // return types or template parameter lists.
1062 bool UseMemberUsingDeclRules =
1063 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1064 !New->getFriendObjectKind();
1065
1066 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1067 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1068 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1069 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1070 continue;
1071 }
1072
1073 if (!isa<FunctionTemplateDecl>(OldD) &&
1074 !shouldLinkPossiblyHiddenDecl(*I, New))
1075 continue;
1076
1077 // C++20 [temp.friend] p9: A non-template friend declaration with a
1078 // requires-clause shall be a definition. A friend function template
1079 // with a constraint that depends on a template parameter from an
1080 // enclosing template shall be a definition. Such a constrained friend
1081 // function or function template declaration does not declare the same
1082 // function or function template as a declaration in any other scope.
1083 if (Context.FriendsDifferByConstraints(OldF, New))
1084 continue;
1085
1086 Match = *I;
1087 return Ovl_Match;
1088 }
1089
1090 // Builtins that have custom typechecking or have a reference should
1091 // not be overloadable or redeclarable.
1092 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1093 Match = *I;
1094 return Ovl_NonFunction;
1095 }
1096 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1097 // We can overload with these, which can show up when doing
1098 // redeclaration checks for UsingDecls.
1099 assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "clang/lib/Sema/SemaOverload.cpp", 1099, __extension__ __PRETTY_FUNCTION__
))
;
1100 } else if (isa<TagDecl>(OldD)) {
1101 // We can always overload with tags by hiding them.
1102 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1103 // Optimistically assume that an unresolved using decl will
1104 // overload; if it doesn't, we'll have to diagnose during
1105 // template instantiation.
1106 //
1107 // Exception: if the scope is dependent and this is not a class
1108 // member, the using declaration can only introduce an enumerator.
1109 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1110 Match = *I;
1111 return Ovl_NonFunction;
1112 }
1113 } else {
1114 // (C++ 13p1):
1115 // Only function declarations can be overloaded; object and type
1116 // declarations cannot be overloaded.
1117 Match = *I;
1118 return Ovl_NonFunction;
1119 }
1120 }
1121
1122 // C++ [temp.friend]p1:
1123 // For a friend function declaration that is not a template declaration:
1124 // -- if the name of the friend is a qualified or unqualified template-id,
1125 // [...], otherwise
1126 // -- if the name of the friend is a qualified-id and a matching
1127 // non-template function is found in the specified class or namespace,
1128 // the friend declaration refers to that function, otherwise,
1129 // -- if the name of the friend is a qualified-id and a matching function
1130 // template is found in the specified class or namespace, the friend
1131 // declaration refers to the deduced specialization of that function
1132 // template, otherwise
1133 // -- the name shall be an unqualified-id [...]
1134 // If we get here for a qualified friend declaration, we've just reached the
1135 // third bullet. If the type of the friend is dependent, skip this lookup
1136 // until instantiation.
1137 if (New->getFriendObjectKind() && New->getQualifier() &&
1138 !New->getDescribedFunctionTemplate() &&
1139 !New->getDependentSpecializationInfo() &&
1140 !New->getType()->isDependentType()) {
1141 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1142 TemplateSpecResult.addAllDecls(Old);
1143 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1144 /*QualifiedFriend*/true)) {
1145 New->setInvalidDecl();
1146 return Ovl_Overload;
1147 }
1148
1149 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1150 return Ovl_Match;
1151 }
1152
1153 return Ovl_Overload;
1154}
1155
1156bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1157 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1158 bool ConsiderRequiresClauses) {
1159 // C++ [basic.start.main]p2: This function shall not be overloaded.
1160 if (New->isMain())
1161 return false;
1162
1163 // MSVCRT user defined entry points cannot be overloaded.
1164 if (New->isMSVCRTEntryPoint())
1165 return false;
1166
1167 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1168 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1169
1170 // C++ [temp.fct]p2:
1171 // A function template can be overloaded with other function templates
1172 // and with normal (non-template) functions.
1173 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1174 return true;
1175
1176 // Is the function New an overload of the function Old?
1177 QualType OldQType = Context.getCanonicalType(Old->getType());
1178 QualType NewQType = Context.getCanonicalType(New->getType());
1179
1180 // Compare the signatures (C++ 1.3.10) of the two functions to
1181 // determine whether they are overloads. If we find any mismatch
1182 // in the signature, they are overloads.
1183
1184 // If either of these functions is a K&R-style function (no
1185 // prototype), then we consider them to have matching signatures.
1186 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1187 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1188 return false;
1189
1190 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1191 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1192
1193 // The signature of a function includes the types of its
1194 // parameters (C++ 1.3.10), which includes the presence or absence
1195 // of the ellipsis; see C++ DR 357).
1196 if (OldQType != NewQType &&
1197 (OldType->getNumParams() != NewType->getNumParams() ||
1198 OldType->isVariadic() != NewType->isVariadic() ||
1199 !FunctionParamTypesAreEqual(OldType, NewType)))
1200 return true;
1201
1202 // C++ [temp.over.link]p4:
1203 // The signature of a function template consists of its function
1204 // signature, its return type and its template parameter list. The names
1205 // of the template parameters are significant only for establishing the
1206 // relationship between the template parameters and the rest of the
1207 // signature.
1208 //
1209 // We check the return type and template parameter lists for function
1210 // templates first; the remaining checks follow.
1211 //
1212 // However, we don't consider either of these when deciding whether
1213 // a member introduced by a shadow declaration is hidden.
1214 if (!UseMemberUsingDeclRules && NewTemplate &&
1215 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1216 OldTemplate->getTemplateParameters(),
1217 false, TPL_TemplateMatch) ||
1218 !Context.hasSameType(Old->getDeclaredReturnType(),
1219 New->getDeclaredReturnType())))
1220 return true;
1221
1222 // If the function is a class member, its signature includes the
1223 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1224 //
1225 // As part of this, also check whether one of the member functions
1226 // is static, in which case they are not overloads (C++
1227 // 13.1p2). While not part of the definition of the signature,
1228 // this check is important to determine whether these functions
1229 // can be overloaded.
1230 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1231 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1232 if (OldMethod && NewMethod &&
1233 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1234 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1235 if (!UseMemberUsingDeclRules &&
1236 (OldMethod->getRefQualifier() == RQ_None ||
1237 NewMethod->getRefQualifier() == RQ_None)) {
1238 // C++0x [over.load]p2:
1239 // - Member function declarations with the same name and the same
1240 // parameter-type-list as well as member function template
1241 // declarations with the same name, the same parameter-type-list, and
1242 // the same template parameter lists cannot be overloaded if any of
1243 // them, but not all, have a ref-qualifier (8.3.5).
1244 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1245 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1246 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1247 }
1248 return true;
1249 }
1250
1251 // We may not have applied the implicit const for a constexpr member
1252 // function yet (because we haven't yet resolved whether this is a static
1253 // or non-static member function). Add it now, on the assumption that this
1254 // is a redeclaration of OldMethod.
1255 auto OldQuals = OldMethod->getMethodQualifiers();
1256 auto NewQuals = NewMethod->getMethodQualifiers();
1257 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1258 !isa<CXXConstructorDecl>(NewMethod))
1259 NewQuals.addConst();
1260 // We do not allow overloading based off of '__restrict'.
1261 OldQuals.removeRestrict();
1262 NewQuals.removeRestrict();
1263 if (OldQuals != NewQuals)
1264 return true;
1265 }
1266
1267 // Though pass_object_size is placed on parameters and takes an argument, we
1268 // consider it to be a function-level modifier for the sake of function
1269 // identity. Either the function has one or more parameters with
1270 // pass_object_size or it doesn't.
1271 if (functionHasPassObjectSizeParams(New) !=
1272 functionHasPassObjectSizeParams(Old))
1273 return true;
1274
1275 // enable_if attributes are an order-sensitive part of the signature.
1276 for (specific_attr_iterator<EnableIfAttr>
1277 NewI = New->specific_attr_begin<EnableIfAttr>(),
1278 NewE = New->specific_attr_end<EnableIfAttr>(),
1279 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1280 OldE = Old->specific_attr_end<EnableIfAttr>();
1281 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1282 if (NewI == NewE || OldI == OldE)
1283 return true;
1284 llvm::FoldingSetNodeID NewID, OldID;
1285 NewI->getCond()->Profile(NewID, Context, true);
1286 OldI->getCond()->Profile(OldID, Context, true);
1287 if (NewID != OldID)
1288 return true;
1289 }
1290
1291 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1292 // Don't allow overloading of destructors. (In theory we could, but it
1293 // would be a giant change to clang.)
1294 if (!isa<CXXDestructorDecl>(New)) {
1295 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1296 OldTarget = IdentifyCUDATarget(Old);
1297 if (NewTarget != CFT_InvalidTarget) {
1298 assert((OldTarget != CFT_InvalidTarget) &&(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1299, __extension__ __PRETTY_FUNCTION__
))
1299 "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1299, __extension__ __PRETTY_FUNCTION__
))
;
1300
1301 // Allow overloading of functions with same signature and different CUDA
1302 // target attributes.
1303 if (NewTarget != OldTarget)
1304 return true;
1305 }
1306 }
1307 }
1308
1309 if (ConsiderRequiresClauses) {
1310 Expr *NewRC = New->getTrailingRequiresClause(),
1311 *OldRC = Old->getTrailingRequiresClause();
1312 if ((NewRC != nullptr) != (OldRC != nullptr))
1313 // RC are most certainly different - these are overloads.
1314 return true;
1315
1316 if (NewRC) {
1317 llvm::FoldingSetNodeID NewID, OldID;
1318 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1319 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1320 if (NewID != OldID)
1321 // RCs are not equivalent - these are overloads.
1322 return true;
1323 }
1324 }
1325
1326 // The signatures match; this is not an overload.
1327 return false;
1328}
1329
1330/// Tries a user-defined conversion from From to ToType.
1331///
1332/// Produces an implicit conversion sequence for when a standard conversion
1333/// is not an option. See TryImplicitConversion for more information.
1334static ImplicitConversionSequence
1335TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1336 bool SuppressUserConversions,
1337 AllowedExplicit AllowExplicit,
1338 bool InOverloadResolution,
1339 bool CStyle,
1340 bool AllowObjCWritebackConversion,
1341 bool AllowObjCConversionOnExplicit) {
1342 ImplicitConversionSequence ICS;
1343
1344 if (SuppressUserConversions) {
1345 // We're not in the case above, so there is no conversion that
1346 // we can perform.
1347 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1348 return ICS;
1349 }
1350
1351 // Attempt user-defined conversion.
1352 OverloadCandidateSet Conversions(From->getExprLoc(),
1353 OverloadCandidateSet::CSK_Normal);
1354 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1355 Conversions, AllowExplicit,
1356 AllowObjCConversionOnExplicit)) {
1357 case OR_Success:
1358 case OR_Deleted:
1359 ICS.setUserDefined();
1360 // C++ [over.ics.user]p4:
1361 // A conversion of an expression of class type to the same class
1362 // type is given Exact Match rank, and a conversion of an
1363 // expression of class type to a base class of that type is
1364 // given Conversion rank, in spite of the fact that a copy
1365 // constructor (i.e., a user-defined conversion function) is
1366 // called for those cases.
1367 if (CXXConstructorDecl *Constructor
1368 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1369 QualType FromCanon
1370 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1371 QualType ToCanon
1372 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1373 if (Constructor->isCopyConstructor() &&
1374 (FromCanon == ToCanon ||
1375 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1376 // Turn this into a "standard" conversion sequence, so that it
1377 // gets ranked with standard conversion sequences.
1378 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1379 ICS.setStandard();
1380 ICS.Standard.setAsIdentityConversion();
1381 ICS.Standard.setFromType(From->getType());
1382 ICS.Standard.setAllToTypes(ToType);
1383 ICS.Standard.CopyConstructor = Constructor;
1384 ICS.Standard.FoundCopyConstructor = Found;
1385 if (ToCanon != FromCanon)
1386 ICS.Standard.Second = ICK_Derived_To_Base;
1387 }
1388 }
1389 break;
1390
1391 case OR_Ambiguous:
1392 ICS.setAmbiguous();
1393 ICS.Ambiguous.setFromType(From->getType());
1394 ICS.Ambiguous.setToType(ToType);
1395 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1396 Cand != Conversions.end(); ++Cand)
1397 if (Cand->Best)
1398 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1399 break;
1400
1401 // Fall through.
1402 case OR_No_Viable_Function:
1403 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1404 break;
1405 }
1406
1407 return ICS;
1408}
1409
1410/// TryImplicitConversion - Attempt to perform an implicit conversion
1411/// from the given expression (Expr) to the given type (ToType). This
1412/// function returns an implicit conversion sequence that can be used
1413/// to perform the initialization. Given
1414///
1415/// void f(float f);
1416/// void g(int i) { f(i); }
1417///
1418/// this routine would produce an implicit conversion sequence to
1419/// describe the initialization of f from i, which will be a standard
1420/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1421/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1422//
1423/// Note that this routine only determines how the conversion can be
1424/// performed; it does not actually perform the conversion. As such,
1425/// it will not produce any diagnostics if no conversion is available,
1426/// but will instead return an implicit conversion sequence of kind
1427/// "BadConversion".
1428///
1429/// If @p SuppressUserConversions, then user-defined conversions are
1430/// not permitted.
1431/// If @p AllowExplicit, then explicit user-defined conversions are
1432/// permitted.
1433///
1434/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1435/// writeback conversion, which allows __autoreleasing id* parameters to
1436/// be initialized with __strong id* or __weak id* arguments.
1437static ImplicitConversionSequence
1438TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1439 bool SuppressUserConversions,
1440 AllowedExplicit AllowExplicit,
1441 bool InOverloadResolution,
1442 bool CStyle,
1443 bool AllowObjCWritebackConversion,
1444 bool AllowObjCConversionOnExplicit) {
1445 ImplicitConversionSequence ICS;
1446 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1447 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1448 ICS.setStandard();
1449 return ICS;
1450 }
1451
1452 if (!S.getLangOpts().CPlusPlus) {
1453 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1454 return ICS;
1455 }
1456
1457 // C++ [over.ics.user]p4:
1458 // A conversion of an expression of class type to the same class
1459 // type is given Exact Match rank, and a conversion of an
1460 // expression of class type to a base class of that type is
1461 // given Conversion rank, in spite of the fact that a copy/move
1462 // constructor (i.e., a user-defined conversion function) is
1463 // called for those cases.
1464 QualType FromType = From->getType();
1465 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1466 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1467 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1468 ICS.setStandard();
1469 ICS.Standard.setAsIdentityConversion();
1470 ICS.Standard.setFromType(FromType);
1471 ICS.Standard.setAllToTypes(ToType);
1472
1473 // We don't actually check at this point whether there is a valid
1474 // copy/move constructor, since overloading just assumes that it
1475 // exists. When we actually perform initialization, we'll find the
1476 // appropriate constructor to copy the returned object, if needed.
1477 ICS.Standard.CopyConstructor = nullptr;
1478
1479 // Determine whether this is considered a derived-to-base conversion.
1480 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1481 ICS.Standard.Second = ICK_Derived_To_Base;
1482
1483 return ICS;
1484 }
1485
1486 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1487 AllowExplicit, InOverloadResolution, CStyle,
1488 AllowObjCWritebackConversion,
1489 AllowObjCConversionOnExplicit);
1490}
1491
1492ImplicitConversionSequence
1493Sema::TryImplicitConversion(Expr *From, QualType ToType,
1494 bool SuppressUserConversions,
1495 AllowedExplicit AllowExplicit,
1496 bool InOverloadResolution,
1497 bool CStyle,
1498 bool AllowObjCWritebackConversion) {
1499 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1500 AllowExplicit, InOverloadResolution, CStyle,
1501 AllowObjCWritebackConversion,
1502 /*AllowObjCConversionOnExplicit=*/false);
1503}
1504
1505/// PerformImplicitConversion - Perform an implicit conversion of the
1506/// expression From to the type ToType. Returns the
1507/// converted expression. Flavor is the kind of conversion we're
1508/// performing, used in the error message. If @p AllowExplicit,
1509/// explicit user-defined conversions are permitted.
1510ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1511 AssignmentAction Action,
1512 bool AllowExplicit) {
1513 if (checkPlaceholderForOverload(*this, From))
1514 return ExprError();
1515
1516 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1517 bool AllowObjCWritebackConversion
1518 = getLangOpts().ObjCAutoRefCount &&
1519 (Action == AA_Passing || Action == AA_Sending);
1520 if (getLangOpts().ObjC)
1521 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1522 From->getType(), From);
1523 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1524 *this, From, ToType,
1525 /*SuppressUserConversions=*/false,
1526 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1527 /*InOverloadResolution=*/false,
1528 /*CStyle=*/false, AllowObjCWritebackConversion,
1529 /*AllowObjCConversionOnExplicit=*/false);
1530 return PerformImplicitConversion(From, ToType, ICS, Action);
1531}
1532
1533/// Determine whether the conversion from FromType to ToType is a valid
1534/// conversion that strips "noexcept" or "noreturn" off the nested function
1535/// type.
1536bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1537 QualType &ResultTy) {
1538 if (Context.hasSameUnqualifiedType(FromType, ToType))
1539 return false;
1540
1541 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1542 // or F(t noexcept) -> F(t)
1543 // where F adds one of the following at most once:
1544 // - a pointer
1545 // - a member pointer
1546 // - a block pointer
1547 // Changes here need matching changes in FindCompositePointerType.
1548 CanQualType CanTo = Context.getCanonicalType(ToType);
1549 CanQualType CanFrom = Context.getCanonicalType(FromType);
1550 Type::TypeClass TyClass = CanTo->getTypeClass();
1551 if (TyClass != CanFrom->getTypeClass()) return false;
1552 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1553 if (TyClass == Type::Pointer) {
1554 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1555 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1556 } else if (TyClass == Type::BlockPointer) {
1557 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1558 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1559 } else if (TyClass == Type::MemberPointer) {
1560 auto ToMPT = CanTo.castAs<MemberPointerType>();
1561 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1562 // A function pointer conversion cannot change the class of the function.
1563 if (ToMPT->getClass() != FromMPT->getClass())
1564 return false;
1565 CanTo = ToMPT->getPointeeType();
1566 CanFrom = FromMPT->getPointeeType();
1567 } else {
1568 return false;
1569 }
1570
1571 TyClass = CanTo->getTypeClass();
1572 if (TyClass != CanFrom->getTypeClass()) return false;
1573 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1574 return false;
1575 }
1576
1577 const auto *FromFn = cast<FunctionType>(CanFrom);
1578 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1579
1580 const auto *ToFn = cast<FunctionType>(CanTo);
1581 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1582
1583 bool Changed = false;
1584
1585 // Drop 'noreturn' if not present in target type.
1586 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1587 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1588 Changed = true;
1589 }
1590
1591 // Drop 'noexcept' if not present in target type.
1592 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1593 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1594 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1595 FromFn = cast<FunctionType>(
1596 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1597 EST_None)
1598 .getTypePtr());
1599 Changed = true;
1600 }
1601
1602 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1603 // only if the ExtParameterInfo lists of the two function prototypes can be
1604 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1605 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1606 bool CanUseToFPT, CanUseFromFPT;
1607 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1608 CanUseFromFPT, NewParamInfos) &&
1609 CanUseToFPT && !CanUseFromFPT) {
1610 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1611 ExtInfo.ExtParameterInfos =
1612 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1613 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1614 FromFPT->getParamTypes(), ExtInfo);
1615 FromFn = QT->getAs<FunctionType>();
1616 Changed = true;
1617 }
1618 }
1619
1620 if (!Changed)
1621 return false;
1622
1623 assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical())
? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()"
, "clang/lib/Sema/SemaOverload.cpp", 1623, __extension__ __PRETTY_FUNCTION__
))
;
1624 if (QualType(FromFn, 0) != CanTo) return false;
1625
1626 ResultTy = ToType;
1627 return true;
1628}
1629
1630/// Determine whether the conversion from FromType to ToType is a valid
1631/// vector conversion.
1632///
1633/// \param ICK Will be set to the vector conversion kind, if this is a vector
1634/// conversion.
1635static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1636 ImplicitConversionKind &ICK, Expr *From,
1637 bool InOverloadResolution) {
1638 // We need at least one of these types to be a vector type to have a vector
1639 // conversion.
1640 if (!ToType->isVectorType() && !FromType->isVectorType())
1641 return false;
1642
1643 // Identical types require no conversions.
1644 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1645 return false;
1646
1647 // There are no conversions between extended vector types, only identity.
1648 if (ToType->isExtVectorType()) {
1649 // There are no conversions between extended vector types other than the
1650 // identity conversion.
1651 if (FromType->isExtVectorType())
1652 return false;
1653
1654 // Vector splat from any arithmetic type to a vector.
1655 if (FromType->isArithmeticType()) {
1656 ICK = ICK_Vector_Splat;
1657 return true;
1658 }
1659 }
1660
1661 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1662 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1663 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1664 ICK = ICK_SVE_Vector_Conversion;
1665 return true;
1666 }
1667
1668 // We can perform the conversion between vector types in the following cases:
1669 // 1)vector types are equivalent AltiVec and GCC vector types
1670 // 2)lax vector conversions are permitted and the vector types are of the
1671 // same size
1672 // 3)the destination type does not have the ARM MVE strict-polymorphism
1673 // attribute, which inhibits lax vector conversion for overload resolution
1674 // only
1675 if (ToType->isVectorType() && FromType->isVectorType()) {
1676 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1677 (S.isLaxVectorConversion(FromType, ToType) &&
1678 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1679 if (S.isLaxVectorConversion(FromType, ToType) &&
1680 S.anyAltivecTypes(FromType, ToType) &&
1681 !S.areSameVectorElemTypes(FromType, ToType) &&
1682 !InOverloadResolution) {
1683 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1684 << FromType << ToType;
1685 }
1686 ICK = ICK_Vector_Conversion;
1687 return true;
1688 }
1689 }
1690
1691 return false;
1692}
1693
1694static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1695 bool InOverloadResolution,
1696 StandardConversionSequence &SCS,
1697 bool CStyle);
1698
1699/// IsStandardConversion - Determines whether there is a standard
1700/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1701/// expression From to the type ToType. Standard conversion sequences
1702/// only consider non-class types; for conversions that involve class
1703/// types, use TryImplicitConversion. If a conversion exists, SCS will
1704/// contain the standard conversion sequence required to perform this
1705/// conversion and this routine will return true. Otherwise, this
1706/// routine will return false and the value of SCS is unspecified.
1707static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1708 bool InOverloadResolution,
1709 StandardConversionSequence &SCS,
1710 bool CStyle,
1711 bool AllowObjCWritebackConversion) {
1712 QualType FromType = From->getType();
1713
1714 // Standard conversions (C++ [conv])
1715 SCS.setAsIdentityConversion();
1716 SCS.IncompatibleObjC = false;
1717 SCS.setFromType(FromType);
1718 SCS.CopyConstructor = nullptr;
1719
1720 // There are no standard conversions for class types in C++, so
1721 // abort early. When overloading in C, however, we do permit them.
1722 if (S.getLangOpts().CPlusPlus &&
1723 (FromType->isRecordType() || ToType->isRecordType()))
1724 return false;
1725
1726 // The first conversion can be an lvalue-to-rvalue conversion,
1727 // array-to-pointer conversion, or function-to-pointer conversion
1728 // (C++ 4p1).
1729
1730 if (FromType == S.Context.OverloadTy) {
1731 DeclAccessPair AccessPair;
1732 if (FunctionDecl *Fn
1733 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1734 AccessPair)) {
1735 // We were able to resolve the address of the overloaded function,
1736 // so we can convert to the type of that function.
1737 FromType = Fn->getType();
1738 SCS.setFromType(FromType);
1739
1740 // we can sometimes resolve &foo<int> regardless of ToType, so check
1741 // if the type matches (identity) or we are converting to bool
1742 if (!S.Context.hasSameUnqualifiedType(
1743 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1744 QualType resultTy;
1745 // if the function type matches except for [[noreturn]], it's ok
1746 if (!S.IsFunctionConversion(FromType,
1747 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1748 // otherwise, only a boolean conversion is standard
1749 if (!ToType->isBooleanType())
1750 return false;
1751 }
1752
1753 // Check if the "from" expression is taking the address of an overloaded
1754 // function and recompute the FromType accordingly. Take advantage of the
1755 // fact that non-static member functions *must* have such an address-of
1756 // expression.
1757 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1758 if (Method && !Method->isStatic()) {
1759 assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1760, __extension__ __PRETTY_FUNCTION__
))
1760 "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1760, __extension__ __PRETTY_FUNCTION__
))
;
1761 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1763, __extension__ __PRETTY_FUNCTION__
))
1762 == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1763, __extension__ __PRETTY_FUNCTION__
))
1763 "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1763, __extension__ __PRETTY_FUNCTION__
))
;
1764 const Type *ClassType
1765 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1766 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1767 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1768 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1770, __extension__ __PRETTY_FUNCTION__
))
1769 UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1770, __extension__ __PRETTY_FUNCTION__
))
1770 "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1770, __extension__ __PRETTY_FUNCTION__
))
;
1771 FromType = S.Context.getPointerType(FromType);
1772 }
1773 } else {
1774 return false;
1775 }
1776 }
1777 // Lvalue-to-rvalue conversion (C++11 4.1):
1778 // A glvalue (3.10) of a non-function, non-array type T can
1779 // be converted to a prvalue.
1780 bool argIsLValue = From->isGLValue();
1781 if (argIsLValue &&
1782 !FromType->isFunctionType() && !FromType->isArrayType() &&
1783 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1784 SCS.First = ICK_Lvalue_To_Rvalue;
1785
1786 // C11 6.3.2.1p2:
1787 // ... if the lvalue has atomic type, the value has the non-atomic version
1788 // of the type of the lvalue ...
1789 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1790 FromType = Atomic->getValueType();
1791
1792 // If T is a non-class type, the type of the rvalue is the
1793 // cv-unqualified version of T. Otherwise, the type of the rvalue
1794 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1795 // just strip the qualifiers because they don't matter.
1796 FromType = FromType.getUnqualifiedType();
1797 } else if (FromType->isArrayType()) {
1798 // Array-to-pointer conversion (C++ 4.2)
1799 SCS.First = ICK_Array_To_Pointer;
1800
1801 // An lvalue or rvalue of type "array of N T" or "array of unknown
1802 // bound of T" can be converted to an rvalue of type "pointer to
1803 // T" (C++ 4.2p1).
1804 FromType = S.Context.getArrayDecayedType(FromType);
1805
1806 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1807 // This conversion is deprecated in C++03 (D.4)
1808 SCS.DeprecatedStringLiteralToCharPtr = true;
1809
1810 // For the purpose of ranking in overload resolution
1811 // (13.3.3.1.1), this conversion is considered an
1812 // array-to-pointer conversion followed by a qualification
1813 // conversion (4.4). (C++ 4.2p2)
1814 SCS.Second = ICK_Identity;
1815 SCS.Third = ICK_Qualification;
1816 SCS.QualificationIncludesObjCLifetime = false;
1817 SCS.setAllToTypes(FromType);
1818 return true;
1819 }
1820 } else if (FromType->isFunctionType() && argIsLValue) {
1821 // Function-to-pointer conversion (C++ 4.3).
1822 SCS.First = ICK_Function_To_Pointer;
1823
1824 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1825 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1826 if (!S.checkAddressOfFunctionIsAvailable(FD))
1827 return false;
1828
1829 // An lvalue of function type T can be converted to an rvalue of
1830 // type "pointer to T." The result is a pointer to the
1831 // function. (C++ 4.3p1).
1832 FromType = S.Context.getPointerType(FromType);
1833 } else {
1834 // We don't require any conversions for the first step.
1835 SCS.First = ICK_Identity;
1836 }
1837 SCS.setToType(0, FromType);
1838
1839 // The second conversion can be an integral promotion, floating
1840 // point promotion, integral conversion, floating point conversion,
1841 // floating-integral conversion, pointer conversion,
1842 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1843 // For overloading in C, this can also be a "compatible-type"
1844 // conversion.
1845 bool IncompatibleObjC = false;
1846 ImplicitConversionKind SecondICK = ICK_Identity;
1847 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1848 // The unqualified versions of the types are the same: there's no
1849 // conversion to do.
1850 SCS.Second = ICK_Identity;
1851 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1852 // Integral promotion (C++ 4.5).
1853 SCS.Second = ICK_Integral_Promotion;
1854 FromType = ToType.getUnqualifiedType();
1855 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1856 // Floating point promotion (C++ 4.6).
1857 SCS.Second = ICK_Floating_Promotion;
1858 FromType = ToType.getUnqualifiedType();
1859 } else if (S.IsComplexPromotion(FromType, ToType)) {
1860 // Complex promotion (Clang extension)
1861 SCS.Second = ICK_Complex_Promotion;
1862 FromType = ToType.getUnqualifiedType();
1863 } else if (ToType->isBooleanType() &&
1864 (FromType->isArithmeticType() ||
1865 FromType->isAnyPointerType() ||
1866 FromType->isBlockPointerType() ||
1867 FromType->isMemberPointerType())) {
1868 // Boolean conversions (C++ 4.12).
1869 SCS.Second = ICK_Boolean_Conversion;
1870 FromType = S.Context.BoolTy;
1871 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1872 ToType->isIntegralType(S.Context)) {
1873 // Integral conversions (C++ 4.7).
1874 SCS.Second = ICK_Integral_Conversion;
1875 FromType = ToType.getUnqualifiedType();
1876 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1877 // Complex conversions (C99 6.3.1.6)
1878 SCS.Second = ICK_Complex_Conversion;
1879 FromType = ToType.getUnqualifiedType();
1880 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1881 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1882 // Complex-real conversions (C99 6.3.1.7)
1883 SCS.Second = ICK_Complex_Real;
1884 FromType = ToType.getUnqualifiedType();
1885 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1886 // FIXME: disable conversions between long double, __ibm128 and __float128
1887 // if their representation is different until there is back end support
1888 // We of course allow this conversion if long double is really double.
1889
1890 // Conversions between bfloat and other floats are not permitted.
1891 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1892 return false;
1893
1894 // Conversions between IEEE-quad and IBM-extended semantics are not
1895 // permitted.
1896 const llvm::fltSemantics &FromSem =
1897 S.Context.getFloatTypeSemantics(FromType);
1898 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1899 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1900 &ToSem == &llvm::APFloat::IEEEquad()) ||
1901 (&FromSem == &llvm::APFloat::IEEEquad() &&
1902 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1903 return false;
1904
1905 // Floating point conversions (C++ 4.8).
1906 SCS.Second = ICK_Floating_Conversion;
1907 FromType = ToType.getUnqualifiedType();
1908 } else if ((FromType->isRealFloatingType() &&
1909 ToType->isIntegralType(S.Context)) ||
1910 (FromType->isIntegralOrUnscopedEnumerationType() &&
1911 ToType->isRealFloatingType())) {
1912 // Conversions between bfloat and int are not permitted.
1913 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1914 return false;
1915
1916 // Floating-integral conversions (C++ 4.9).
1917 SCS.Second = ICK_Floating_Integral;
1918 FromType = ToType.getUnqualifiedType();
1919 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1920 SCS.Second = ICK_Block_Pointer_Conversion;
1921 } else if (AllowObjCWritebackConversion &&
1922 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1923 SCS.Second = ICK_Writeback_Conversion;
1924 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1925 FromType, IncompatibleObjC)) {
1926 // Pointer conversions (C++ 4.10).
1927 SCS.Second = ICK_Pointer_Conversion;
1928 SCS.IncompatibleObjC = IncompatibleObjC;
1929 FromType = FromType.getUnqualifiedType();
1930 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1931 InOverloadResolution, FromType)) {
1932 // Pointer to member conversions (4.11).
1933 SCS.Second = ICK_Pointer_Member;
1934 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
1935 InOverloadResolution)) {
1936 SCS.Second = SecondICK;
1937 FromType = ToType.getUnqualifiedType();
1938 } else if (!S.getLangOpts().CPlusPlus &&
1939 S.Context.typesAreCompatible(ToType, FromType)) {
1940 // Compatible conversions (Clang extension for C function overloading)
1941 SCS.Second = ICK_Compatible_Conversion;
1942 FromType = ToType.getUnqualifiedType();
1943 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1944 InOverloadResolution,
1945 SCS, CStyle)) {
1946 SCS.Second = ICK_TransparentUnionConversion;
1947 FromType = ToType;
1948 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1949 CStyle)) {
1950 // tryAtomicConversion has updated the standard conversion sequence
1951 // appropriately.
1952 return true;
1953 } else if (ToType->isEventT() &&
1954 From->isIntegerConstantExpr(S.getASTContext()) &&
1955 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1956 SCS.Second = ICK_Zero_Event_Conversion;
1957 FromType = ToType;
1958 } else if (ToType->isQueueT() &&
1959 From->isIntegerConstantExpr(S.getASTContext()) &&
1960 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1961 SCS.Second = ICK_Zero_Queue_Conversion;
1962 FromType = ToType;
1963 } else if (ToType->isSamplerT() &&
1964 From->isIntegerConstantExpr(S.getASTContext())) {
1965 SCS.Second = ICK_Compatible_Conversion;
1966 FromType = ToType;
1967 } else {
1968 // No second conversion required.
1969 SCS.Second = ICK_Identity;
1970 }
1971 SCS.setToType(1, FromType);
1972
1973 // The third conversion can be a function pointer conversion or a
1974 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1975 bool ObjCLifetimeConversion;
1976 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1977 // Function pointer conversions (removing 'noexcept') including removal of
1978 // 'noreturn' (Clang extension).
1979 SCS.Third = ICK_Function_Conversion;
1980 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1981 ObjCLifetimeConversion)) {
1982 SCS.Third = ICK_Qualification;
1983 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1984 FromType = ToType;
1985 } else {
1986 // No conversion required
1987 SCS.Third = ICK_Identity;
1988 }
1989
1990 // C++ [over.best.ics]p6:
1991 // [...] Any difference in top-level cv-qualification is
1992 // subsumed by the initialization itself and does not constitute
1993 // a conversion. [...]
1994 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1995 QualType CanonTo = S.Context.getCanonicalType(ToType);
1996 if (CanonFrom.getLocalUnqualifiedType()
1997 == CanonTo.getLocalUnqualifiedType() &&
1998 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1999 FromType = ToType;
2000 CanonFrom = CanonTo;
2001 }
2002
2003 SCS.setToType(2, FromType);
2004
2005 if (CanonFrom == CanonTo)
2006 return true;
2007
2008 // If we have not converted the argument type to the parameter type,
2009 // this is a bad conversion sequence, unless we're resolving an overload in C.
2010 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2011 return false;
2012
2013 ExprResult ER = ExprResult{From};
2014 Sema::AssignConvertType Conv =
2015 S.CheckSingleAssignmentConstraints(ToType, ER,
2016 /*Diagnose=*/false,
2017 /*DiagnoseCFAudited=*/false,
2018 /*ConvertRHS=*/false);
2019 ImplicitConversionKind SecondConv;
2020 switch (Conv) {
2021 case Sema::Compatible:
2022 SecondConv = ICK_C_Only_Conversion;
2023 break;
2024 // For our purposes, discarding qualifiers is just as bad as using an
2025 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2026 // qualifiers, as well.
2027 case Sema::CompatiblePointerDiscardsQualifiers:
2028 case Sema::IncompatiblePointer:
2029 case Sema::IncompatiblePointerSign:
2030 SecondConv = ICK_Incompatible_Pointer_Conversion;
2031 break;
2032 default:
2033 return false;
2034 }
2035
2036 // First can only be an lvalue conversion, so we pretend that this was the
2037 // second conversion. First should already be valid from earlier in the
2038 // function.
2039 SCS.Second = SecondConv;
2040 SCS.setToType(1, ToType);
2041
2042 // Third is Identity, because Second should rank us worse than any other
2043 // conversion. This could also be ICK_Qualification, but it's simpler to just
2044 // lump everything in with the second conversion, and we don't gain anything
2045 // from making this ICK_Qualification.
2046 SCS.Third = ICK_Identity;
2047 SCS.setToType(2, ToType);
2048 return true;
2049}
2050
2051static bool
2052IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2053 QualType &ToType,
2054 bool InOverloadResolution,
2055 StandardConversionSequence &SCS,
2056 bool CStyle) {
2057
2058 const RecordType *UT = ToType->getAsUnionType();
2059 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2060 return false;
2061 // The field to initialize within the transparent union.
2062 RecordDecl *UD = UT->getDecl();
2063 // It's compatible if the expression matches any of the fields.
2064 for (const auto *it : UD->fields()) {
2065 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2066 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2067 ToType = it->getType();
2068 return true;
2069 }
2070 }
2071 return false;
2072}
2073
2074/// IsIntegralPromotion - Determines whether the conversion from the
2075/// expression From (whose potentially-adjusted type is FromType) to
2076/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2077/// sets PromotedType to the promoted type.
2078bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2079 const BuiltinType *To = ToType->getAs<BuiltinType>();
2080 // All integers are built-in.
2081 if (!To) {
2082 return false;
2083 }
2084
2085 // An rvalue of type char, signed char, unsigned char, short int, or
2086 // unsigned short int can be converted to an rvalue of type int if
2087 // int can represent all the values of the source type; otherwise,
2088 // the source rvalue can be converted to an rvalue of type unsigned
2089 // int (C++ 4.5p1).
2090 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2091 !FromType->isEnumeralType()) {
2092 if (// We can promote any signed, promotable integer type to an int
2093 (FromType->isSignedIntegerType() ||
2094 // We can promote any unsigned integer type whose size is
2095 // less than int to an int.
2096 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2097 return To->getKind() == BuiltinType::Int;
2098 }
2099
2100 return To->getKind() == BuiltinType::UInt;
2101 }
2102
2103 // C++11 [conv.prom]p3:
2104 // A prvalue of an unscoped enumeration type whose underlying type is not
2105 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2106 // following types that can represent all the values of the enumeration
2107 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2108 // unsigned int, long int, unsigned long int, long long int, or unsigned
2109 // long long int. If none of the types in that list can represent all the
2110 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2111 // type can be converted to an rvalue a prvalue of the extended integer type
2112 // with lowest integer conversion rank (4.13) greater than the rank of long
2113 // long in which all the values of the enumeration can be represented. If
2114 // there are two such extended types, the signed one is chosen.
2115 // C++11 [conv.prom]p4:
2116 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2117 // can be converted to a prvalue of its underlying type. Moreover, if
2118 // integral promotion can be applied to its underlying type, a prvalue of an
2119 // unscoped enumeration type whose underlying type is fixed can also be
2120 // converted to a prvalue of the promoted underlying type.
2121 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2122 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2123 // provided for a scoped enumeration.
2124 if (FromEnumType->getDecl()->isScoped())
2125 return false;
2126
2127 // We can perform an integral promotion to the underlying type of the enum,
2128 // even if that's not the promoted type. Note that the check for promoting
2129 // the underlying type is based on the type alone, and does not consider
2130 // the bitfield-ness of the actual source expression.
2131 if (FromEnumType->getDecl()->isFixed()) {
2132 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2133 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2134 IsIntegralPromotion(nullptr, Underlying, ToType);
2135 }
2136
2137 // We have already pre-calculated the promotion type, so this is trivial.
2138 if (ToType->isIntegerType() &&
2139 isCompleteType(From->getBeginLoc(), FromType))
2140 return Context.hasSameUnqualifiedType(
2141 ToType, FromEnumType->getDecl()->getPromotionType());
2142
2143 // C++ [conv.prom]p5:
2144 // If the bit-field has an enumerated type, it is treated as any other
2145 // value of that type for promotion purposes.
2146 //
2147 // ... so do not fall through into the bit-field checks below in C++.
2148 if (getLangOpts().CPlusPlus)
2149 return false;
2150 }
2151
2152 // C++0x [conv.prom]p2:
2153 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2154 // to an rvalue a prvalue of the first of the following types that can
2155 // represent all the values of its underlying type: int, unsigned int,
2156 // long int, unsigned long int, long long int, or unsigned long long int.
2157 // If none of the types in that list can represent all the values of its
2158 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2159 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2160 // type.
2161 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2162 ToType->isIntegerType()) {
2163 // Determine whether the type we're converting from is signed or
2164 // unsigned.
2165 bool FromIsSigned = FromType->isSignedIntegerType();
2166 uint64_t FromSize = Context.getTypeSize(FromType);
2167
2168 // The types we'll try to promote to, in the appropriate
2169 // order. Try each of these types.
2170 QualType PromoteTypes[6] = {
2171 Context.IntTy, Context.UnsignedIntTy,
2172 Context.LongTy, Context.UnsignedLongTy ,
2173 Context.LongLongTy, Context.UnsignedLongLongTy
2174 };
2175 for (int Idx = 0; Idx < 6; ++Idx) {
2176 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2177 if (FromSize < ToSize ||
2178 (FromSize == ToSize &&
2179 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2180 // We found the type that we can promote to. If this is the
2181 // type we wanted, we have a promotion. Otherwise, no
2182 // promotion.
2183 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2184 }
2185 }
2186 }
2187
2188 // An rvalue for an integral bit-field (9.6) can be converted to an
2189 // rvalue of type int if int can represent all the values of the
2190 // bit-field; otherwise, it can be converted to unsigned int if
2191 // unsigned int can represent all the values of the bit-field. If
2192 // the bit-field is larger yet, no integral promotion applies to
2193 // it. If the bit-field has an enumerated type, it is treated as any
2194 // other value of that type for promotion purposes (C++ 4.5p3).
2195 // FIXME: We should delay checking of bit-fields until we actually perform the
2196 // conversion.
2197 //
2198 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2199 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2200 // bit-fields and those whose underlying type is larger than int) for GCC
2201 // compatibility.
2202 if (From) {
2203 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2204 Optional<llvm::APSInt> BitWidth;
2205 if (FromType->isIntegralType(Context) &&
2206 (BitWidth =
2207 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2208 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2209 ToSize = Context.getTypeSize(ToType);
2210
2211 // Are we promoting to an int from a bitfield that fits in an int?
2212 if (*BitWidth < ToSize ||
2213 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2214 return To->getKind() == BuiltinType::Int;
2215 }
2216
2217 // Are we promoting to an unsigned int from an unsigned bitfield
2218 // that fits into an unsigned int?
2219 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2220 return To->getKind() == BuiltinType::UInt;
2221 }
2222
2223 return false;
2224 }
2225 }
2226 }
2227
2228 // An rvalue of type bool can be converted to an rvalue of type int,
2229 // with false becoming zero and true becoming one (C++ 4.5p4).
2230 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2231 return true;
2232 }
2233
2234 return false;
2235}
2236
2237/// IsFloatingPointPromotion - Determines whether the conversion from
2238/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2239/// returns true and sets PromotedType to the promoted type.
2240bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2241 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2242 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2243 /// An rvalue of type float can be converted to an rvalue of type
2244 /// double. (C++ 4.6p1).
2245 if (FromBuiltin->getKind() == BuiltinType::Float &&
2246 ToBuiltin->getKind() == BuiltinType::Double)
2247 return true;
2248
2249 // C99 6.3.1.5p1:
2250 // When a float is promoted to double or long double, or a
2251 // double is promoted to long double [...].
2252 if (!getLangOpts().CPlusPlus &&
2253 (FromBuiltin->getKind() == BuiltinType::Float ||
2254 FromBuiltin->getKind() == BuiltinType::Double) &&
2255 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2256 ToBuiltin->getKind() == BuiltinType::Float128 ||
2257 ToBuiltin->getKind() == BuiltinType::Ibm128))
2258 return true;
2259
2260 // Half can be promoted to float.
2261 if (!getLangOpts().NativeHalfType &&
2262 FromBuiltin->getKind() == BuiltinType::Half &&
2263 ToBuiltin->getKind() == BuiltinType::Float)
2264 return true;
2265 }
2266
2267 return false;
2268}
2269
2270/// Determine if a conversion is a complex promotion.
2271///
2272/// A complex promotion is defined as a complex -> complex conversion
2273/// where the conversion between the underlying real types is a
2274/// floating-point or integral promotion.
2275bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2276 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2277 if (!FromComplex)
2278 return false;
2279
2280 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2281 if (!ToComplex)
2282 return false;
2283
2284 return IsFloatingPointPromotion(FromComplex->getElementType(),
2285 ToComplex->getElementType()) ||
2286 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2287 ToComplex->getElementType());
2288}
2289
2290/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2291/// the pointer type FromPtr to a pointer to type ToPointee, with the
2292/// same type qualifiers as FromPtr has on its pointee type. ToType,
2293/// if non-empty, will be a pointer to ToType that may or may not have
2294/// the right set of qualifiers on its pointee.
2295///
2296static QualType
2297BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2298 QualType ToPointee, QualType ToType,
2299 ASTContext &Context,
2300 bool StripObjCLifetime = false) {
2301 assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2303, __extension__ __PRETTY_FUNCTION__
))
2302 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2303, __extension__ __PRETTY_FUNCTION__
))
2303 "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2303, __extension__ __PRETTY_FUNCTION__
))
;
2304
2305 /// Conversions to 'id' subsume cv-qualifier conversions.
2306 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2307 return ToType.getUnqualifiedType();
2308
2309 QualType CanonFromPointee
2310 = Context.getCanonicalType(FromPtr->getPointeeType());
2311 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2312 Qualifiers Quals = CanonFromPointee.getQualifiers();
2313
2314 if (StripObjCLifetime)
2315 Quals.removeObjCLifetime();
2316
2317 // Exact qualifier match -> return the pointer type we're converting to.
2318 if (CanonToPointee.getLocalQualifiers() == Quals) {
2319 // ToType is exactly what we need. Return it.
2320 if (!ToType.isNull())
2321 return ToType.getUnqualifiedType();
2322
2323 // Build a pointer to ToPointee. It has the right qualifiers
2324 // already.
2325 if (isa<ObjCObjectPointerType>(ToType))
2326 return Context.getObjCObjectPointerType(ToPointee);
2327 return Context.getPointerType(ToPointee);
2328 }
2329
2330 // Just build a canonical type that has the right qualifiers.
2331 QualType QualifiedCanonToPointee
2332 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2333
2334 if (isa<ObjCObjectPointerType>(ToType))
2335 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2336 return Context.getPointerType(QualifiedCanonToPointee);
2337}
2338
2339static bool isNullPointerConstantForConversion(Expr *Expr,
2340 bool InOverloadResolution,
2341 ASTContext &Context) {
2342 // Handle value-dependent integral null pointer constants correctly.
2343 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2344 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2345 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2346 return !InOverloadResolution;
2347
2348 return Expr->isNullPointerConstant(Context,
2349 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2350 : Expr::NPC_ValueDependentIsNull);
2351}
2352
2353/// IsPointerConversion - Determines whether the conversion of the
2354/// expression From, which has the (possibly adjusted) type FromType,
2355/// can be converted to the type ToType via a pointer conversion (C++
2356/// 4.10). If so, returns true and places the converted type (that
2357/// might differ from ToType in its cv-qualifiers at some level) into
2358/// ConvertedType.
2359///
2360/// This routine also supports conversions to and from block pointers
2361/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2362/// pointers to interfaces. FIXME: Once we've determined the
2363/// appropriate overloading rules for Objective-C, we may want to
2364/// split the Objective-C checks into a different routine; however,
2365/// GCC seems to consider all of these conversions to be pointer
2366/// conversions, so for now they live here. IncompatibleObjC will be
2367/// set if the conversion is an allowed Objective-C conversion that
2368/// should result in a warning.
2369bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2370 bool InOverloadResolution,
2371 QualType& ConvertedType,
2372 bool &IncompatibleObjC) {
2373 IncompatibleObjC = false;
2374 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2375 IncompatibleObjC))
2376 return true;
2377
2378 // Conversion from a null pointer constant to any Objective-C pointer type.
2379 if (ToType->isObjCObjectPointerType() &&
2380 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2381 ConvertedType = ToType;
2382 return true;
2383 }
2384
2385 // Blocks: Block pointers can be converted to void*.
2386 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2387 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2388 ConvertedType = ToType;
2389 return true;
2390 }
2391 // Blocks: A null pointer constant can be converted to a block
2392 // pointer type.
2393 if (ToType->isBlockPointerType() &&
2394 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2395 ConvertedType = ToType;
2396 return true;
2397 }
2398
2399 // If the left-hand-side is nullptr_t, the right side can be a null
2400 // pointer constant.
2401 if (ToType->isNullPtrType() &&
2402 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2403 ConvertedType = ToType;
2404 return true;
2405 }
2406
2407 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2408 if (!ToTypePtr)
2409 return false;
2410
2411 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2412 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2413 ConvertedType = ToType;
2414 return true;
2415 }
2416
2417 // Beyond this point, both types need to be pointers
2418 // , including objective-c pointers.
2419 QualType ToPointeeType = ToTypePtr->getPointeeType();
2420 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2421 !getLangOpts().ObjCAutoRefCount) {
2422 ConvertedType = BuildSimilarlyQualifiedPointerType(
2423 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2424 Context);
2425 return true;
2426 }
2427 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2428 if (!FromTypePtr)
2429 return false;
2430
2431 QualType FromPointeeType = FromTypePtr->getPointeeType();
2432
2433 // If the unqualified pointee types are the same, this can't be a
2434 // pointer conversion, so don't do all of the work below.
2435 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2436 return false;
2437
2438 // An rvalue of type "pointer to cv T," where T is an object type,
2439 // can be converted to an rvalue of type "pointer to cv void" (C++
2440 // 4.10p2).
2441 if (FromPointeeType->isIncompleteOrObjectType() &&
2442 ToPointeeType->isVoidType()) {
2443 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2444 ToPointeeType,
2445 ToType, Context,
2446 /*StripObjCLifetime=*/true);
2447 return true;
2448 }
2449
2450 // MSVC allows implicit function to void* type conversion.
2451 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2452 ToPointeeType->isVoidType()) {
2453 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2454 ToPointeeType,
2455 ToType, Context);
2456 return true;
2457 }
2458
2459 // When we're overloading in C, we allow a special kind of pointer
2460 // conversion for compatible-but-not-identical pointee types.
2461 if (!getLangOpts().CPlusPlus &&
2462 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2463 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2464 ToPointeeType,
2465 ToType, Context);
2466 return true;
2467 }
2468
2469 // C++ [conv.ptr]p3:
2470 //
2471 // An rvalue of type "pointer to cv D," where D is a class type,
2472 // can be converted to an rvalue of type "pointer to cv B," where
2473 // B is a base class (clause 10) of D. If B is an inaccessible
2474 // (clause 11) or ambiguous (10.2) base class of D, a program that
2475 // necessitates this conversion is ill-formed. The result of the
2476 // conversion is a pointer to the base class sub-object of the
2477 // derived class object. The null pointer value is converted to
2478 // the null pointer value of the destination type.
2479 //
2480 // Note that we do not check for ambiguity or inaccessibility
2481 // here. That is handled by CheckPointerConversion.
2482 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2483 ToPointeeType->isRecordType() &&
2484 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2485 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2486 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2487 ToPointeeType,
2488 ToType, Context);
2489 return true;
2490 }
2491
2492 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2493 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2494 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2495 ToPointeeType,
2496 ToType, Context);
2497 return true;
2498 }
2499
2500 return false;
2501}
2502
2503/// Adopt the given qualifiers for the given type.
2504static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2505 Qualifiers TQs = T.getQualifiers();
2506
2507 // Check whether qualifiers already match.
2508 if (TQs == Qs)
2509 return T;
2510
2511 if (Qs.compatiblyIncludes(TQs))
2512 return Context.getQualifiedType(T, Qs);
2513
2514 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2515}
2516
2517/// isObjCPointerConversion - Determines whether this is an
2518/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2519/// with the same arguments and return values.
2520bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2521 QualType& ConvertedType,
2522 bool &IncompatibleObjC) {
2523 if (!getLangOpts().ObjC)
2524 return false;
2525
2526 // The set of qualifiers on the type we're converting from.
2527 Qualifiers FromQualifiers = FromType.getQualifiers();
2528
2529 // First, we handle all conversions on ObjC object pointer types.
2530 const ObjCObjectPointerType* ToObjCPtr =
2531 ToType->getAs<ObjCObjectPointerType>();
2532 const ObjCObjectPointerType *FromObjCPtr =
2533 FromType->getAs<ObjCObjectPointerType>();
2534
2535 if (ToObjCPtr && FromObjCPtr) {
2536 // If the pointee types are the same (ignoring qualifications),
2537 // then this is not a pointer conversion.
2538 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2539 FromObjCPtr->getPointeeType()))
2540 return false;
2541
2542 // Conversion between Objective-C pointers.
2543 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2544 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2545 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2546 if (getLangOpts().CPlusPlus && LHS && RHS &&
2547 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2548 FromObjCPtr->getPointeeType()))
2549 return false;
2550 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2551 ToObjCPtr->getPointeeType(),
2552 ToType, Context);
2553 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2554 return true;
2555 }
2556
2557 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2558 // Okay: this is some kind of implicit downcast of Objective-C
2559 // interfaces, which is permitted. However, we're going to
2560 // complain about it.
2561 IncompatibleObjC = true;
2562 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2563 ToObjCPtr->getPointeeType(),
2564 ToType, Context);
2565 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2566 return true;
2567 }
2568 }
2569 // Beyond this point, both types need to be C pointers or block pointers.
2570 QualType ToPointeeType;
2571 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2572 ToPointeeType = ToCPtr->getPointeeType();
2573 else if (const BlockPointerType *ToBlockPtr =
2574 ToType->getAs<BlockPointerType>()) {
2575 // Objective C++: We're able to convert from a pointer to any object
2576 // to a block pointer type.
2577 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2578 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2579 return true;
2580 }
2581 ToPointeeType = ToBlockPtr->getPointeeType();
2582 }
2583 else if (FromType->getAs<BlockPointerType>() &&
2584 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2585 // Objective C++: We're able to convert from a block pointer type to a
2586 // pointer to any object.
2587 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2588 return true;
2589 }
2590 else
2591 return false;
2592
2593 QualType FromPointeeType;
2594 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2595 FromPointeeType = FromCPtr->getPointeeType();
2596 else if (const BlockPointerType *FromBlockPtr =
2597 FromType->getAs<BlockPointerType>())
2598 FromPointeeType = FromBlockPtr->getPointeeType();
2599 else
2600 return false;
2601
2602 // If we have pointers to pointers, recursively check whether this
2603 // is an Objective-C conversion.
2604 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2605 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2606 IncompatibleObjC)) {
2607 // We always complain about this conversion.
2608 IncompatibleObjC = true;
2609 ConvertedType = Context.getPointerType(ConvertedType);
2610 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2611 return true;
2612 }
2613 // Allow conversion of pointee being objective-c pointer to another one;
2614 // as in I* to id.
2615 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2616 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2617 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2618 IncompatibleObjC)) {
2619
2620 ConvertedType = Context.getPointerType(ConvertedType);
2621 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2622 return true;
2623 }
2624
2625 // If we have pointers to functions or blocks, check whether the only
2626 // differences in the argument and result types are in Objective-C
2627 // pointer conversions. If so, we permit the conversion (but
2628 // complain about it).
2629 const FunctionProtoType *FromFunctionType
2630 = FromPointeeType->getAs<FunctionProtoType>();
2631 const FunctionProtoType *ToFunctionType
2632 = ToPointeeType->getAs<FunctionProtoType>();
2633 if (FromFunctionType && ToFunctionType) {
2634 // If the function types are exactly the same, this isn't an
2635 // Objective-C pointer conversion.
2636 if (Context.getCanonicalType(FromPointeeType)
2637 == Context.getCanonicalType(ToPointeeType))
2638 return false;
2639
2640 // Perform the quick checks that will tell us whether these
2641 // function types are obviously different.
2642 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2643 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2644 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2645 return false;
2646
2647 bool HasObjCConversion = false;
2648 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2649 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2650 // Okay, the types match exactly. Nothing to do.
2651 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2652 ToFunctionType->getReturnType(),
2653 ConvertedType, IncompatibleObjC)) {
2654 // Okay, we have an Objective-C pointer conversion.
2655 HasObjCConversion = true;
2656 } else {
2657 // Function types are too different. Abort.
2658 return false;
2659 }
2660
2661 // Check argument types.
2662 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2663 ArgIdx != NumArgs; ++ArgIdx) {
2664 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2665 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2666 if (Context.getCanonicalType(FromArgType)
2667 == Context.getCanonicalType(ToArgType)) {
2668 // Okay, the types match exactly. Nothing to do.
2669 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2670 ConvertedType, IncompatibleObjC)) {
2671 // Okay, we have an Objective-C pointer conversion.
2672 HasObjCConversion = true;
2673 } else {
2674 // Argument types are too different. Abort.
2675 return false;
2676 }
2677 }
2678
2679 if (HasObjCConversion) {
2680 // We had an Objective-C conversion. Allow this pointer
2681 // conversion, but complain about it.
2682 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2683 IncompatibleObjC = true;
2684 return true;
2685 }
2686 }
2687
2688 return false;
2689}
2690
2691/// Determine whether this is an Objective-C writeback conversion,
2692/// used for parameter passing when performing automatic reference counting.
2693///
2694/// \param FromType The type we're converting form.
2695///
2696/// \param ToType The type we're converting to.
2697///
2698/// \param ConvertedType The type that will be produced after applying
2699/// this conversion.
2700bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2701 QualType &ConvertedType) {
2702 if (!getLangOpts().ObjCAutoRefCount ||
2703 Context.hasSameUnqualifiedType(FromType, ToType))
2704 return false;
2705
2706 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2707 QualType ToPointee;
2708 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2709 ToPointee = ToPointer->getPointeeType();
2710 else
2711 return false;
2712
2713 Qualifiers ToQuals = ToPointee.getQualifiers();
2714 if (!ToPointee->isObjCLifetimeType() ||
2715 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2716 !ToQuals.withoutObjCLifetime().empty())
2717 return false;
2718
2719 // Argument must be a pointer to __strong to __weak.
2720 QualType FromPointee;
2721 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2722 FromPointee = FromPointer->getPointeeType();
2723 else
2724 return false;
2725
2726 Qualifiers FromQuals = FromPointee.getQualifiers();
2727 if (!FromPointee->isObjCLifetimeType() ||
2728 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2729 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2730 return false;
2731
2732 // Make sure that we have compatible qualifiers.
2733 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2734 if (!ToQuals.compatiblyIncludes(FromQuals))
2735 return false;
2736
2737 // Remove qualifiers from the pointee type we're converting from; they
2738 // aren't used in the compatibility check belong, and we'll be adding back
2739 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2740 FromPointee = FromPointee.getUnqualifiedType();
2741
2742 // The unqualified form of the pointee types must be compatible.
2743 ToPointee = ToPointee.getUnqualifiedType();
2744 bool IncompatibleObjC;
2745 if (Context.typesAreCompatible(FromPointee, ToPointee))
2746 FromPointee = ToPointee;
2747 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2748 IncompatibleObjC))
2749 return false;
2750
2751 /// Construct the type we're converting to, which is a pointer to
2752 /// __autoreleasing pointee.
2753 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2754 ConvertedType = Context.getPointerType(FromPointee);
2755 return true;
2756}
2757
2758bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2759 QualType& ConvertedType) {
2760 QualType ToPointeeType;
2761 if (const BlockPointerType *ToBlockPtr =
2762 ToType->getAs<BlockPointerType>())
2763 ToPointeeType = ToBlockPtr->getPointeeType();
2764 else
2765 return false;
2766
2767 QualType FromPointeeType;
2768 if (const BlockPointerType *FromBlockPtr =
2769 FromType->getAs<BlockPointerType>())
2770 FromPointeeType = FromBlockPtr->getPointeeType();
2771 else
2772 return false;
2773 // We have pointer to blocks, check whether the only
2774 // differences in the argument and result types are in Objective-C
2775 // pointer conversions. If so, we permit the conversion.
2776
2777 const FunctionProtoType *FromFunctionType
2778 = FromPointeeType->getAs<FunctionProtoType>();
2779 const FunctionProtoType *ToFunctionType
2780 = ToPointeeType->getAs<FunctionProtoType>();
2781
2782 if (!FromFunctionType || !ToFunctionType)
2783 return false;
2784
2785 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2786 return true;
2787
2788 // Perform the quick checks that will tell us whether these
2789 // function types are obviously different.
2790 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2791 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2792 return false;
2793
2794 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2795 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2796 if (FromEInfo != ToEInfo)
2797 return false;
2798
2799 bool IncompatibleObjC = false;
2800 if (Context.hasSameType(FromFunctionType->getReturnType(),
2801 ToFunctionType->getReturnType())) {
2802 // Okay, the types match exactly. Nothing to do.
2803 } else {
2804 QualType RHS = FromFunctionType->getReturnType();
2805 QualType LHS = ToFunctionType->getReturnType();
2806 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2807 !RHS.hasQualifiers() && LHS.hasQualifiers())
2808 LHS = LHS.getUnqualifiedType();
2809
2810 if (Context.hasSameType(RHS,LHS)) {
2811 // OK exact match.
2812 } else if (isObjCPointerConversion(RHS, LHS,
2813 ConvertedType, IncompatibleObjC)) {
2814 if (IncompatibleObjC)
2815 return false;
2816 // Okay, we have an Objective-C pointer conversion.
2817 }
2818 else
2819 return false;
2820 }
2821
2822 // Check argument types.
2823 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2824 ArgIdx != NumArgs; ++ArgIdx) {
2825 IncompatibleObjC = false;
2826 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2827 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2828 if (Context.hasSameType(FromArgType, ToArgType)) {
2829 // Okay, the types match exactly. Nothing to do.
2830 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2831 ConvertedType, IncompatibleObjC)) {
2832 if (IncompatibleObjC)
2833 return false;
2834 // Okay, we have an Objective-C pointer conversion.
2835 } else
2836 // Argument types are too different. Abort.
2837 return false;
2838 }
2839
2840 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2841 bool CanUseToFPT, CanUseFromFPT;
2842 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2843 CanUseToFPT, CanUseFromFPT,
2844 NewParamInfos))
2845 return false;
2846
2847 ConvertedType = ToType;
2848 return true;
2849}
2850
2851enum {
2852 ft_default,
2853 ft_different_class,
2854 ft_parameter_arity,
2855 ft_parameter_mismatch,
2856 ft_return_type,
2857 ft_qualifer_mismatch,
2858 ft_noexcept
2859};
2860
2861/// Attempts to get the FunctionProtoType from a Type. Handles
2862/// MemberFunctionPointers properly.
2863static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2864 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2865 return FPT;
2866
2867 if (auto *MPT = FromType->getAs<MemberPointerType>())
2868 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2869
2870 return nullptr;
2871}
2872
2873/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2874/// function types. Catches different number of parameter, mismatch in
2875/// parameter types, and different return types.
2876void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2877 QualType FromType, QualType ToType) {
2878 // If either type is not valid, include no extra info.
2879 if (FromType.isNull() || ToType.isNull()) {
2880 PDiag << ft_default;
2881 return;
2882 }
2883
2884 // Get the function type from the pointers.
2885 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2886 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2887 *ToMember = ToType->castAs<MemberPointerType>();
2888 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2889 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2890 << QualType(FromMember->getClass(), 0);
2891 return;
2892 }
2893 FromType = FromMember->getPointeeType();
2894 ToType = ToMember->getPointeeType();
2895 }
2896
2897 if (FromType->isPointerType())
2898 FromType = FromType->getPointeeType();
2899 if (ToType->isPointerType())
2900 ToType = ToType->getPointeeType();
2901
2902 // Remove references.
2903 FromType = FromType.getNonReferenceType();
2904 ToType = ToType.getNonReferenceType();
2905
2906 // Don't print extra info for non-specialized template functions.
2907 if (FromType->isInstantiationDependentType() &&
2908 !FromType->getAs<TemplateSpecializationType>()) {
2909 PDiag << ft_default;
2910 return;
2911 }
2912
2913 // No extra info for same types.
2914 if (Context.hasSameType(FromType, ToType)) {
2915 PDiag << ft_default;
2916 return;
2917 }
2918
2919 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2920 *ToFunction = tryGetFunctionProtoType(ToType);
2921
2922 // Both types need to be function types.
2923 if (!FromFunction || !ToFunction) {
2924 PDiag << ft_default;
2925 return;
2926 }
2927
2928 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2929 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2930 << FromFunction->getNumParams();
2931 return;
2932 }
2933
2934 // Handle different parameter types.
2935 unsigned ArgPos;
2936 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2937 PDiag << ft_parameter_mismatch << ArgPos + 1
2938 << ToFunction->getParamType(ArgPos)
2939 << FromFunction->getParamType(ArgPos);
2940 return;
2941 }
2942
2943 // Handle different return type.
2944 if (!Context.hasSameType(FromFunction->getReturnType(),
2945 ToFunction->getReturnType())) {
2946 PDiag << ft_return_type << ToFunction->getReturnType()
2947 << FromFunction->getReturnType();
2948 return;
2949 }
2950
2951 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2952 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2953 << FromFunction->getMethodQuals();
2954 return;
2955 }
2956
2957 // Handle exception specification differences on canonical type (in C++17
2958 // onwards).
2959 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2960 ->isNothrow() !=
2961 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2962 ->isNothrow()) {
2963 PDiag << ft_noexcept;
2964 return;
2965 }
2966
2967 // Unable to find a difference, so add no extra info.
2968 PDiag << ft_default;
2969}
2970
2971/// FunctionParamTypesAreEqual - This routine checks two function proto types
2972/// for equality of their parameter types. Caller has already checked that
2973/// they have same number of parameters. If the parameters are different,
2974/// ArgPos will have the parameter index of the first different parameter.
2975/// If `Reversed` is true, the parameters of `NewType` will be compared in
2976/// reverse order. That's useful if one of the functions is being used as a C++20
2977/// synthesized operator overload with a reversed parameter order.
2978bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2979 const FunctionProtoType *NewType,
2980 unsigned *ArgPos, bool Reversed) {
2981 assert(OldType->getNumParams() == NewType->getNumParams() &&(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 2983, __extension__ __PRETTY_FUNCTION__
))
2982 "Can't compare parameters of functions with different number of "(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 2983, __extension__ __PRETTY_FUNCTION__
))
2983 "parameters!")(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 2983, __extension__ __PRETTY_FUNCTION__
))
;
2984 for (size_t I = 0; I < OldType->getNumParams(); I++) {
2985 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2986 size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2987
2988 // Ignore address spaces in pointee type. This is to disallow overloading
2989 // on __ptr32/__ptr64 address spaces.
2990 QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2991 QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2992
2993 if (!Context.hasSameType(Old, New)) {
2994 if (ArgPos)
2995 *ArgPos = I;
2996 return false;
2997 }
2998 }
2999 return true;
3000}
3001
3002/// CheckPointerConversion - Check the pointer conversion from the
3003/// expression From to the type ToType. This routine checks for
3004/// ambiguous or inaccessible derived-to-base pointer
3005/// conversions for which IsPointerConversion has already returned
3006/// true. It returns true and produces a diagnostic if there was an
3007/// error, or returns false otherwise.
3008bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3009 CastKind &Kind,
3010 CXXCastPath& BasePath,
3011 bool IgnoreBaseAccess,
3012 bool Diagnose) {
3013 QualType FromType = From->getType();
3014 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3015
3016 Kind = CK_BitCast;
3017
3018 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3019 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3020 Expr::NPCK_ZeroExpression) {
3021 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3022 DiagRuntimeBehavior(From->getExprLoc(), From,
3023 PDiag(diag::warn_impcast_bool_to_null_pointer)
3024 << ToType << From->getSourceRange());
3025 else if (!isUnevaluatedContext())
3026 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3027 << ToType << From->getSourceRange();
3028 }
3029 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3030 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3031 QualType FromPointeeType = FromPtrType->getPointeeType(),
3032 ToPointeeType = ToPtrType->getPointeeType();
3033
3034 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3035 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3036 // We must have a derived-to-base conversion. Check an
3037 // ambiguous or inaccessible conversion.
3038 unsigned InaccessibleID = 0;
3039 unsigned AmbiguousID = 0;
3040 if (Diagnose) {
3041 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3042 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3043 }
3044 if (CheckDerivedToBaseConversion(
3045 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3046 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3047 &BasePath, IgnoreBaseAccess))
3048 return true;
3049
3050 // The conversion was successful.
3051 Kind = CK_DerivedToBase;
3052 }
3053
3054 if (Diagnose && !IsCStyleOrFunctionalCast &&
3055 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3056 assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3057, __extension__ __PRETTY_FUNCTION__
))
3057 "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3057, __extension__ __PRETTY_FUNCTION__
))
;
3058 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3059 << From->getSourceRange();
3060 }
3061 }
3062 } else if (const ObjCObjectPointerType *ToPtrType =
3063 ToType->getAs<ObjCObjectPointerType>()) {
3064 if (const ObjCObjectPointerType *FromPtrType =
3065 FromType->getAs<ObjCObjectPointerType>()) {
3066 // Objective-C++ conversions are always okay.
3067 // FIXME: We should have a different class of conversions for the
3068 // Objective-C++ implicit conversions.
3069 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3070 return false;
3071 } else if (FromType->isBlockPointerType()) {
3072 Kind = CK_BlockPointerToObjCPointerCast;
3073 } else {
3074 Kind = CK_CPointerToObjCPointerCast;
3075 }
3076 } else if (ToType->isBlockPointerType()) {
3077 if (!FromType->isBlockPointerType())
3078 Kind = CK_AnyPointerToBlockPointerCast;
3079 }
3080
3081 // We shouldn't fall into this case unless it's valid for other
3082 // reasons.
3083 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3084 Kind = CK_NullToPointer;
3085
3086 return false;
3087}
3088
3089/// IsMemberPointerConversion - Determines whether the conversion of the
3090/// expression From, which has the (possibly adjusted) type FromType, can be
3091/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3092/// If so, returns true and places the converted type (that might differ from
3093/// ToType in its cv-qualifiers at some level) into ConvertedType.
3094bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3095 QualType ToType,
3096 bool InOverloadResolution,
3097 QualType &ConvertedType) {
3098 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3099 if (!ToTypePtr)
3100 return false;
3101
3102 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3103 if (From->isNullPointerConstant(Context,
3104 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3105 : Expr::NPC_ValueDependentIsNull)) {
3106 ConvertedType = ToType;
3107 return true;
3108 }
3109
3110 // Otherwise, both types have to be member pointers.
3111 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3112 if (!FromTypePtr)
3113 return false;
3114
3115 // A pointer to member of B can be converted to a pointer to member of D,
3116 // where D is derived from B (C++ 4.11p2).
3117 QualType FromClass(FromTypePtr->getClass(), 0);
3118 QualType ToClass(ToTypePtr->getClass(), 0);
3119
3120 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3121 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3122 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3123 ToClass.getTypePtr());
3124 return true;
3125 }
3126
3127 return false;
3128}
3129
3130/// CheckMemberPointerConversion - Check the member pointer conversion from the
3131/// expression From to the type ToType. This routine checks for ambiguous or
3132/// virtual or inaccessible base-to-derived member pointer conversions
3133/// for which IsMemberPointerConversion has already returned true. It returns
3134/// true and produces a diagnostic if there was an error, or returns false
3135/// otherwise.
3136bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3137 CastKind &Kind,
3138 CXXCastPath &BasePath,
3139 bool IgnoreBaseAccess) {
3140 QualType FromType = From->getType();
3141 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3142 if (!FromPtrType) {
3143 // This must be a null pointer to member pointer conversion
3144 assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3146, __extension__ __PRETTY_FUNCTION__
))
3145 Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3146, __extension__ __PRETTY_FUNCTION__
))
3146 "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3146, __extension__ __PRETTY_FUNCTION__
))
;
3147 Kind = CK_NullToMemberPointer;
3148 return false;
3149 }
3150
3151 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3152 assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3153, __extension__ __PRETTY_FUNCTION__
))
3153 "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3153, __extension__ __PRETTY_FUNCTION__
))
;
3154
3155 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3156 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3157
3158 // FIXME: What about dependent types?
3159 assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3159, __extension__ __PRETTY_FUNCTION__
))
;
3160 assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3160, __extension__ __PRETTY_FUNCTION__
))
;
3161
3162 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3163 /*DetectVirtual=*/true);
3164 bool DerivationOkay =
3165 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3166 assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3167, __extension__ __PRETTY_FUNCTION__
))
3167 "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3167, __extension__ __PRETTY_FUNCTION__
))
;
3168 (void)DerivationOkay;
3169
3170 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3171 getUnqualifiedType())) {
3172 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3173 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3174 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3175 return true;
3176 }
3177
3178 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3179 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3180 << FromClass << ToClass << QualType(VBase, 0)
3181 << From->getSourceRange();
3182 return true;
3183 }
3184
3185 if (!IgnoreBaseAccess)
3186 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3187 Paths.front(),
3188 diag::err_downcast_from_inaccessible_base);
3189
3190 // Must be a base to derived member conversion.
3191 BuildBasePathArray(Paths, BasePath);
3192 Kind = CK_BaseToDerivedMemberPointer;
3193 return false;
3194}
3195
3196/// Determine whether the lifetime conversion between the two given
3197/// qualifiers sets is nontrivial.
3198static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3199 Qualifiers ToQuals) {
3200 // Converting anything to const __unsafe_unretained is trivial.
3201 if (ToQuals.hasConst() &&
3202 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3203 return false;
3204
3205 return true;
3206}
3207
3208/// Perform a single iteration of the loop for checking if a qualification
3209/// conversion is valid.
3210///
3211/// Specifically, check whether any change between the qualifiers of \p
3212/// FromType and \p ToType is permissible, given knowledge about whether every
3213/// outer layer is const-qualified.
3214static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3215 bool CStyle, bool IsTopLevel,
3216 bool &PreviousToQualsIncludeConst,
3217 bool &ObjCLifetimeConversion) {
3218 Qualifiers FromQuals = FromType.getQualifiers();
3219 Qualifiers ToQuals = ToType.getQualifiers();
3220
3221 // Ignore __unaligned qualifier.
3222 FromQuals.removeUnaligned();
3223
3224 // Objective-C ARC:
3225 // Check Objective-C lifetime conversions.
3226 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3227 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3228 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3229 ObjCLifetimeConversion = true;
3230 FromQuals.removeObjCLifetime();
3231 ToQuals.removeObjCLifetime();
3232 } else {
3233 // Qualification conversions cannot cast between different
3234 // Objective-C lifetime qualifiers.
3235 return false;
3236 }
3237 }
3238
3239 // Allow addition/removal of GC attributes but not changing GC attributes.
3240 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3241 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3242 FromQuals.removeObjCGCAttr();
3243 ToQuals.removeObjCGCAttr();
3244 }
3245
3246 // -- for every j > 0, if const is in cv 1,j then const is in cv
3247 // 2,j, and similarly for volatile.
3248 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3249 return false;
3250
3251 // If address spaces mismatch:
3252 // - in top level it is only valid to convert to addr space that is a
3253 // superset in all cases apart from C-style casts where we allow
3254 // conversions between overlapping address spaces.
3255 // - in non-top levels it is not a valid conversion.
3256 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3257 (!IsTopLevel ||
3258 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3259 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3260 return false;
3261
3262 // -- if the cv 1,j and cv 2,j are different, then const is in
3263 // every cv for 0 < k < j.
3264 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3265 !PreviousToQualsIncludeConst)
3266 return false;
3267
3268 // The following wording is from C++20, where the result of the conversion
3269 // is T3, not T2.
3270 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3271 // "array of unknown bound of"
3272 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3273 return false;
3274
3275 // -- if the resulting P3,i is different from P1,i [...], then const is
3276 // added to every cv 3_k for 0 < k < i.
3277 if (!CStyle && FromType->isConstantArrayType() &&
3278 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3279 return false;
3280
3281 // Keep track of whether all prior cv-qualifiers in the "to" type
3282 // include const.
3283 PreviousToQualsIncludeConst =
3284 PreviousToQualsIncludeConst && ToQuals.hasConst();
3285 return true;
3286}
3287
3288/// IsQualificationConversion - Determines whether the conversion from
3289/// an rvalue of type FromType to ToType is a qualification conversion
3290/// (C++ 4.4).
3291///
3292/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3293/// when the qualification conversion involves a change in the Objective-C
3294/// object lifetime.
3295bool
3296Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3297 bool CStyle, bool &ObjCLifetimeConversion) {
3298 FromType = Context.getCanonicalType(FromType);
3299 ToType = Context.getCanonicalType(ToType);
3300 ObjCLifetimeConversion = false;
3301
3302 // If FromType and ToType are the same type, this is not a
3303 // qualification conversion.
3304 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3305 return false;
3306
3307 // (C++ 4.4p4):
3308 // A conversion can add cv-qualifiers at levels other than the first
3309 // in multi-level pointers, subject to the following rules: [...]
3310 bool PreviousToQualsIncludeConst = true;
3311 bool UnwrappedAnyPointer = false;
3312 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3313 if (!isQualificationConversionStep(
3314 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3315 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3316 return false;
3317 UnwrappedAnyPointer = true;
3318 }
3319
3320 // We are left with FromType and ToType being the pointee types
3321 // after unwrapping the original FromType and ToType the same number
3322 // of times. If we unwrapped any pointers, and if FromType and
3323 // ToType have the same unqualified type (since we checked
3324 // qualifiers above), then this is a qualification conversion.
3325 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3326}
3327
3328/// - Determine whether this is a conversion from a scalar type to an
3329/// atomic type.
3330///
3331/// If successful, updates \c SCS's second and third steps in the conversion
3332/// sequence to finish the conversion.
3333static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3334 bool InOverloadResolution,
3335 StandardConversionSequence &SCS,
3336 bool CStyle) {
3337 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3338 if (!ToAtomic)
3339 return false;
3340
3341 StandardConversionSequence InnerSCS;
3342 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3343 InOverloadResolution, InnerSCS,
3344 CStyle, /*AllowObjCWritebackConversion=*/false))
3345 return false;
3346
3347 SCS.Second = InnerSCS.Second;
3348 SCS.setToType(1, InnerSCS.getToType(1));
3349 SCS.Third = InnerSCS.Third;
3350 SCS.QualificationIncludesObjCLifetime
3351 = InnerSCS.QualificationIncludesObjCLifetime;
3352 SCS.setToType(2, InnerSCS.getToType(2));
3353 return true;
3354}
3355
3356static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3357 CXXConstructorDecl *Constructor,
3358 QualType Type) {
3359 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3360 if (CtorType->getNumParams() > 0) {
3361 QualType FirstArg = CtorType->getParamType(0);
3362 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3363 return true;
3364 }
3365 return false;
3366}
3367
3368static OverloadingResult
3369IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3370 CXXRecordDecl *To,
3371 UserDefinedConversionSequence &User,
3372 OverloadCandidateSet &CandidateSet,
3373 bool AllowExplicit) {
3374 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3375 for (auto *D : S.LookupConstructors(To)) {
3376 auto Info = getConstructorInfo(D);
3377 if (!Info)
3378 continue;
3379
3380 bool Usable = !Info.Constructor->isInvalidDecl() &&
3381 S.isInitListConstructor(Info.Constructor);
3382 if (Usable) {
3383 bool SuppressUserConversions = false;
3384 if (Info.ConstructorTmpl)
3385 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3386 /*ExplicitArgs*/ nullptr, From,
3387 CandidateSet, SuppressUserConversions,
3388 /*PartialOverloading*/ false,
3389 AllowExplicit);
3390 else
3391 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3392 CandidateSet, SuppressUserConversions,
3393 /*PartialOverloading*/ false, AllowExplicit);
3394 }
3395 }
3396
3397 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3398
3399 OverloadCandidateSet::iterator Best;
3400 switch (auto Result =
3401 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3402 case OR_Deleted:
3403 case OR_Success: {
3404 // Record the standard conversion we used and the conversion function.
3405 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3406 QualType ThisType = Constructor->getThisType();
3407 // Initializer lists don't have conversions as such.
3408 User.Before.setAsIdentityConversion();
3409 User.HadMultipleCandidates = HadMultipleCandidates;
3410 User.ConversionFunction = Constructor;
3411 User.FoundConversionFunction = Best->FoundDecl;
3412 User.After.setAsIdentityConversion();
3413 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3414 User.After.setAllToTypes(ToType);
3415 return Result;
3416 }
3417
3418 case OR_No_Viable_Function:
3419 return OR_No_Viable_Function;
3420 case OR_Ambiguous:
3421 return OR_Ambiguous;
3422 }
3423
3424 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3424)
;
3425}
3426
3427/// Determines whether there is a user-defined conversion sequence
3428/// (C++ [over.ics.user]) that converts expression From to the type
3429/// ToType. If such a conversion exists, User will contain the
3430/// user-defined conversion sequence that performs such a conversion
3431/// and this routine will return true. Otherwise, this routine returns
3432/// false and User is unspecified.
3433///
3434/// \param AllowExplicit true if the conversion should consider C++0x
3435/// "explicit" conversion functions as well as non-explicit conversion
3436/// functions (C++0x [class.conv.fct]p2).
3437///
3438/// \param AllowObjCConversionOnExplicit true if the conversion should
3439/// allow an extra Objective-C pointer conversion on uses of explicit
3440/// constructors. Requires \c AllowExplicit to also be set.
3441static OverloadingResult
3442IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3443 UserDefinedConversionSequence &User,
3444 OverloadCandidateSet &CandidateSet,
3445 AllowedExplicit AllowExplicit,
3446 bool AllowObjCConversionOnExplicit) {
3447 assert(AllowExplicit != AllowedExplicit::None ||(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3448, __extension__ __PRETTY_FUNCTION__
))
3448 !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3448, __extension__ __PRETTY_FUNCTION__
))
;
3449 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3450
3451 // Whether we will only visit constructors.
3452 bool ConstructorsOnly = false;
3453
3454 // If the type we are conversion to is a class type, enumerate its
3455 // constructors.
3456 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3457 // C++ [over.match.ctor]p1:
3458 // When objects of class type are direct-initialized (8.5), or
3459 // copy-initialized from an expression of the same or a
3460 // derived class type (8.5), overload resolution selects the
3461 // constructor. [...] For copy-initialization, the candidate
3462 // functions are all the converting constructors (12.3.1) of
3463 // that class. The argument list is the expression-list within
3464 // the parentheses of the initializer.
3465 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3466 (From->getType()->getAs<RecordType>() &&
3467 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3468 ConstructorsOnly = true;
3469
3470 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3471 // We're not going to find any constructors.
3472 } else if (CXXRecordDecl *ToRecordDecl
3473 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3474
3475 Expr **Args = &From;
3476 unsigned NumArgs = 1;
3477 bool ListInitializing = false;
3478 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3479 // But first, see if there is an init-list-constructor that will work.
3480 OverloadingResult Result = IsInitializerListConstructorConversion(
3481 S, From, ToType, ToRecordDecl, User, CandidateSet,
3482 AllowExplicit == AllowedExplicit::All);
3483 if (Result != OR_No_Viable_Function)
3484 return Result;
3485 // Never mind.
3486 CandidateSet.clear(
3487 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3488
3489 // If we're list-initializing, we pass the individual elements as
3490 // arguments, not the entire list.
3491 Args = InitList->getInits();
3492 NumArgs = InitList->getNumInits();
3493 ListInitializing = true;
3494 }
3495
3496 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3497 auto Info = getConstructorInfo(D);
3498 if (!Info)
3499 continue;
3500
3501 bool Usable = !Info.Constructor->isInvalidDecl();
3502 if (!ListInitializing)
3503 Usable = Usable && Info.Constructor->isConvertingConstructor(
3504 /*AllowExplicit*/ true);
3505 if (Usable) {
3506 bool SuppressUserConversions = !ConstructorsOnly;
3507 // C++20 [over.best.ics.general]/4.5:
3508 // if the target is the first parameter of a constructor [of class
3509 // X] and the constructor [...] is a candidate by [...] the second
3510 // phase of [over.match.list] when the initializer list has exactly
3511 // one element that is itself an initializer list, [...] and the
3512 // conversion is to X or reference to cv X, user-defined conversion
3513 // sequences are not cnosidered.
3514 if (SuppressUserConversions && ListInitializing) {
3515 SuppressUserConversions =
3516 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3517 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3518 ToType);
3519 }
3520 if (Info.ConstructorTmpl)
3521 S.AddTemplateOverloadCandidate(
3522 Info.ConstructorTmpl, Info.FoundDecl,
3523 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3524 CandidateSet, SuppressUserConversions,
3525 /*PartialOverloading*/ false,
3526 AllowExplicit == AllowedExplicit::All);
3527 else
3528 // Allow one user-defined conversion when user specifies a
3529 // From->ToType conversion via an static cast (c-style, etc).
3530 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3531 llvm::makeArrayRef(Args, NumArgs),
3532 CandidateSet, SuppressUserConversions,
3533 /*PartialOverloading*/ false,
3534 AllowExplicit == AllowedExplicit::All);
3535 }
3536 }
3537 }
3538 }
3539
3540 // Enumerate conversion functions, if we're allowed to.
3541 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3542 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3543 // No conversion functions from incomplete types.
3544 } else if (const RecordType *FromRecordType =
3545 From->getType()->getAs<RecordType>()) {
3546 if (CXXRecordDecl *FromRecordDecl
3547 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3548 // Add all of the conversion functions as candidates.
3549 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3550 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3551 DeclAccessPair FoundDecl = I.getPair();
3552 NamedDecl *D = FoundDecl.getDecl();
3553 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3554 if (isa<UsingShadowDecl>(D))
3555 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3556
3557 CXXConversionDecl *Conv;
3558 FunctionTemplateDecl *ConvTemplate;
3559 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3560 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3561 else
3562 Conv = cast<CXXConversionDecl>(D);
3563
3564 if (ConvTemplate)
3565 S.AddTemplateConversionCandidate(
3566 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3567 CandidateSet, AllowObjCConversionOnExplicit,
3568 AllowExplicit != AllowedExplicit::None);
3569 else
3570 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3571 CandidateSet, AllowObjCConversionOnExplicit,
3572 AllowExplicit != AllowedExplicit::None);
3573 }
3574 }
3575 }
3576
3577 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3578
3579 OverloadCandidateSet::iterator Best;
3580 switch (auto Result =
3581 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3582 case OR_Success:
3583 case OR_Deleted:
3584 // Record the standard conversion we used and the conversion function.
3585 if (CXXConstructorDecl *Constructor
3586 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3587 // C++ [over.ics.user]p1:
3588 // If the user-defined conversion is specified by a
3589 // constructor (12.3.1), the initial standard conversion
3590 // sequence converts the source type to the type required by
3591 // the argument of the constructor.
3592 //
3593 QualType ThisType = Constructor->getThisType();
3594 if (isa<InitListExpr>(From)) {
3595 // Initializer lists don't have conversions as such.
3596 User.Before.setAsIdentityConversion();
3597 } else {
3598 if (Best->Conversions[0].isEllipsis())
3599 User.EllipsisConversion = true;
3600 else {
3601 User.Before = Best->Conversions[0].Standard;
3602 User.EllipsisConversion = false;
3603 }
3604 }
3605 User.HadMultipleCandidates = HadMultipleCandidates;
3606 User.ConversionFunction = Constructor;
3607 User.FoundConversionFunction = Best->FoundDecl;
3608 User.After.setAsIdentityConversion();
3609 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3610 User.After.setAllToTypes(ToType);
3611 return Result;
3612 }
3613 if (CXXConversionDecl *Conversion
3614 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3615 // C++ [over.ics.user]p1:
3616 //
3617 // [...] If the user-defined conversion is specified by a
3618 // conversion function (12.3.2), the initial standard
3619 // conversion sequence converts the source type to the
3620 // implicit object parameter of the conversion function.
3621 User.Before = Best->Conversions[0].Standard;
3622 User.HadMultipleCandidates = HadMultipleCandidates;
3623 User.ConversionFunction = Conversion;
3624 User.FoundConversionFunction = Best->FoundDecl;
3625 User.EllipsisConversion = false;
3626
3627 // C++ [over.ics.user]p2:
3628 // The second standard conversion sequence converts the
3629 // result of the user-defined conversion to the target type
3630 // for the sequence. Since an implicit conversion sequence
3631 // is an initialization, the special rules for
3632 // initialization by user-defined conversion apply when
3633 // selecting the best user-defined conversion for a
3634 // user-defined conversion sequence (see 13.3.3 and
3635 // 13.3.3.1).
3636 User.After = Best->FinalConversion;
3637 return Result;
3638 }
3639 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "clang/lib/Sema/SemaOverload.cpp", 3639)
;
3640
3641 case OR_No_Viable_Function:
3642 return OR_No_Viable_Function;
3643
3644 case OR_Ambiguous:
3645 return OR_Ambiguous;
3646 }
3647
3648 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3648)
;
3649}
3650
3651bool
3652Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3653 ImplicitConversionSequence ICS;
3654 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3655 OverloadCandidateSet::CSK_Normal);
3656 OverloadingResult OvResult =
3657 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3658 CandidateSet, AllowedExplicit::None, false);
3659
3660 if (!(OvResult == OR_Ambiguous ||
3661 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3662 return false;
3663
3664 auto Cands = CandidateSet.CompleteCandidates(
3665 *this,
3666 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3667 From);
3668 if (OvResult == OR_Ambiguous)
3669 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3670 << From->getType() << ToType << From->getSourceRange();
3671 else { // OR_No_Viable_Function && !CandidateSet.empty()
3672 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3673 diag::err_typecheck_nonviable_condition_incomplete,
3674 From->getType(), From->getSourceRange()))
3675 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3676 << false << From->getType() << From->getSourceRange() << ToType;
3677 }
3678
3679 CandidateSet.NoteCandidates(
3680 *this, From, Cands);
3681 return true;
3682}
3683
3684// Helper for compareConversionFunctions that gets the FunctionType that the
3685// conversion-operator return value 'points' to, or nullptr.
3686static const FunctionType *
3687getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3688 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3689 const PointerType *RetPtrTy =
3690 ConvFuncTy->getReturnType()->getAs<PointerType>();
3691
3692 if (!RetPtrTy)
3693 return nullptr;
3694
3695 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3696}
3697
3698/// Compare the user-defined conversion functions or constructors
3699/// of two user-defined conversion sequences to determine whether any ordering
3700/// is possible.
3701static ImplicitConversionSequence::CompareKind
3702compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3703 FunctionDecl *Function2) {
3704 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3705 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3706 if (!Conv1 || !Conv2)
3707 return ImplicitConversionSequence::Indistinguishable;
3708
3709 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3710 return ImplicitConversionSequence::Indistinguishable;
3711
3712 // Objective-C++:
3713 // If both conversion functions are implicitly-declared conversions from
3714 // a lambda closure type to a function pointer and a block pointer,
3715 // respectively, always prefer the conversion to a function pointer,
3716 // because the function pointer is more lightweight and is more likely
3717 // to keep code working.
3718 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3719 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3720 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3721 if (Block1 != Block2)
3722 return Block1 ? ImplicitConversionSequence::Worse
3723 : ImplicitConversionSequence::Better;
3724 }
3725
3726 // In order to support multiple calling conventions for the lambda conversion
3727 // operator (such as when the free and member function calling convention is
3728 // different), prefer the 'free' mechanism, followed by the calling-convention
3729 // of operator(). The latter is in place to support the MSVC-like solution of
3730 // defining ALL of the possible conversions in regards to calling-convention.
3731 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3732 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3733
3734 if (Conv1FuncRet && Conv2FuncRet &&
3735 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3736 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3737 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3738
3739 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3740 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3741
3742 CallingConv CallOpCC =
3743 CallOp->getType()->castAs<FunctionType>()->getCallConv();
3744 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3745 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3746 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3747 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3748
3749 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3750 for (CallingConv CC : PrefOrder) {
3751 if (Conv1CC == CC)
3752 return ImplicitConversionSequence::Better;
3753 if (Conv2CC == CC)
3754 return ImplicitConversionSequence::Worse;
3755 }
3756 }
3757
3758 return ImplicitConversionSequence::Indistinguishable;
3759}
3760
3761static bool hasDeprecatedStringLiteralToCharPtrConversion(
3762 const ImplicitConversionSequence &ICS) {
3763 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3764 (ICS.isUserDefined() &&
3765 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3766}
3767
3768/// CompareImplicitConversionSequences - Compare two implicit
3769/// conversion sequences to determine whether one is better than the
3770/// other or if they are indistinguishable (C++ 13.3.3.2).
3771static ImplicitConversionSequence::CompareKind
3772CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3773 const ImplicitConversionSequence& ICS1,
3774 const ImplicitConversionSequence& ICS2)
3775{
3776 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3777 // conversion sequences (as defined in 13.3.3.1)
3778 // -- a standard conversion sequence (13.3.3.1.1) is a better
3779 // conversion sequence than a user-defined conversion sequence or
3780 // an ellipsis conversion sequence, and
3781 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3782 // conversion sequence than an ellipsis conversion sequence
3783 // (13.3.3.1.3).
3784 //
3785 // C++0x [over.best.ics]p10:
3786 // For the purpose of ranking implicit conversion sequences as
3787 // described in 13.3.3.2, the ambiguous conversion sequence is
3788 // treated as a user-defined sequence that is indistinguishable
3789 // from any other user-defined conversion sequence.
3790
3791 // String literal to 'char *' conversion has been deprecated in C++03. It has
3792 // been removed from C++11. We still accept this conversion, if it happens at
3793 // the best viable function. Otherwise, this conversion is considered worse
3794 // than ellipsis conversion. Consider this as an extension; this is not in the
3795 // standard. For example:
3796 //
3797 // int &f(...); // #1
3798 // void f(char*); // #2
3799 // void g() { int &r = f("foo"); }
3800 //
3801 // In C++03, we pick #2 as the best viable function.
3802 // In C++11, we pick #1 as the best viable function, because ellipsis
3803 // conversion is better than string-literal to char* conversion (since there
3804 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3805 // convert arguments, #2 would be the best viable function in C++11.
3806 // If the best viable function has this conversion, a warning will be issued
3807 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3808
3809 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3810 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3811 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3812 // Ill-formedness must not differ
3813 ICS1.isBad() == ICS2.isBad())
3814 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3815 ? ImplicitConversionSequence::Worse
3816 : ImplicitConversionSequence::Better;
3817
3818 if (ICS1.getKindRank() < ICS2.getKindRank())
3819 return ImplicitConversionSequence::Better;
3820 if (ICS2.getKindRank() < ICS1.getKindRank())
3821 return ImplicitConversionSequence::Worse;
3822
3823 // The following checks require both conversion sequences to be of
3824 // the same kind.
3825 if (ICS1.getKind() != ICS2.getKind())
3826 return ImplicitConversionSequence::Indistinguishable;
3827
3828 ImplicitConversionSequence::CompareKind Result =
3829 ImplicitConversionSequence::Indistinguishable;
3830
3831 // Two implicit conversion sequences of the same form are
3832 // indistinguishable conversion sequences unless one of the
3833 // following rules apply: (C++ 13.3.3.2p3):
3834
3835 // List-initialization sequence L1 is a better conversion sequence than
3836 // list-initialization sequence L2 if:
3837 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3838 // if not that,
3839 // — L1 and L2 convert to arrays of the same element type, and either the
3840 // number of elements n_1 initialized by L1 is less than the number of
3841 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3842 // an array of unknown bound and L1 does not,
3843 // even if one of the other rules in this paragraph would otherwise apply.
3844 if (!ICS1.isBad()) {
3845 bool StdInit1 = false, StdInit2 = false;
3846 if (ICS1.hasInitializerListContainerType())
3847 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3848 nullptr);
3849 if (ICS2.hasInitializerListContainerType())
3850 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3851 nullptr);
3852 if (StdInit1 != StdInit2)
3853 return StdInit1 ? ImplicitConversionSequence::Better
3854 : ImplicitConversionSequence::Worse;
3855
3856 if (ICS1.hasInitializerListContainerType() &&
3857 ICS2.hasInitializerListContainerType())
3858 if (auto *CAT1 = S.Context.getAsConstantArrayType(
3859 ICS1.getInitializerListContainerType()))
3860 if (auto *CAT2 = S.Context.getAsConstantArrayType(
3861 ICS2.getInitializerListContainerType())) {
3862 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3863 CAT2->getElementType())) {
3864 // Both to arrays of the same element type
3865 if (CAT1->getSize() != CAT2->getSize())
3866 // Different sized, the smaller wins
3867 return CAT1->getSize().ult(CAT2->getSize())
3868 ? ImplicitConversionSequence::Better
3869 : ImplicitConversionSequence::Worse;
3870 if (ICS1.isInitializerListOfIncompleteArray() !=
3871 ICS2.isInitializerListOfIncompleteArray())
3872 // One is incomplete, it loses
3873 return ICS2.isInitializerListOfIncompleteArray()
3874 ? ImplicitConversionSequence::Better
3875 : ImplicitConversionSequence::Worse;
3876 }
3877 }
3878 }
3879
3880 if (ICS1.isStandard())
3881 // Standard conversion sequence S1 is a better conversion sequence than
3882 // standard conversion sequence S2 if [...]
3883 Result = CompareStandardConversionSequences(S, Loc,
3884 ICS1.Standard, ICS2.Standard);
3885 else if (ICS1.isUserDefined()) {
3886 // User-defined conversion sequence U1 is a better conversion
3887 // sequence than another user-defined conversion sequence U2 if
3888 // they contain the same user-defined conversion function or
3889 // constructor and if the second standard conversion sequence of
3890 // U1 is better than the second standard conversion sequence of
3891 // U2 (C++ 13.3.3.2p3).
3892 if (ICS1.UserDefined.ConversionFunction ==
3893 ICS2.UserDefined.ConversionFunction)
3894 Result = CompareStandardConversionSequences(S, Loc,
3895 ICS1.UserDefined.After,
3896 ICS2.UserDefined.After);
3897 else
3898 Result = compareConversionFunctions(S,
3899 ICS1.UserDefined.ConversionFunction,
3900 ICS2.UserDefined.ConversionFunction);
3901 }
3902
3903 return Result;
3904}
3905
3906// Per 13.3.3.2p3, compare the given standard conversion sequences to
3907// determine if one is a proper subset of the other.
3908static ImplicitConversionSequence::CompareKind
3909compareStandardConversionSubsets(ASTContext &Context,
3910 const StandardConversionSequence& SCS1,
3911 const StandardConversionSequence& SCS2) {
3912 ImplicitConversionSequence::CompareKind Result
3913 = ImplicitConversionSequence::Indistinguishable;
3914
3915 // the identity conversion sequence is considered to be a subsequence of
3916 // any non-identity conversion sequence
3917 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3918 return ImplicitConversionSequence::Better;
3919 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3920 return ImplicitConversionSequence::Worse;
3921
3922 if (SCS1.Second != SCS2.Second) {
3923 if (SCS1.Second == ICK_Identity)
3924 Result = ImplicitConversionSequence::Better;
3925 else if (SCS2.Second == ICK_Identity)
3926 Result = ImplicitConversionSequence::Worse;
3927 else
3928 return ImplicitConversionSequence::Indistinguishable;
3929 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3930 return ImplicitConversionSequence::Indistinguishable;
3931
3932 if (SCS1.Third == SCS2.Third) {
3933 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3934 : ImplicitConversionSequence::Indistinguishable;
3935 }
3936
3937 if (SCS1.Third == ICK_Identity)
3938 return Result == ImplicitConversionSequence::Worse
3939 ? ImplicitConversionSequence::Indistinguishable
3940 : ImplicitConversionSequence::Better;
3941
3942 if (SCS2.Third == ICK_Identity)
3943 return Result == ImplicitConversionSequence::Better
3944 ? ImplicitConversionSequence::Indistinguishable
3945 : ImplicitConversionSequence::Worse;
3946
3947 return ImplicitConversionSequence::Indistinguishable;
3948}
3949
3950/// Determine whether one of the given reference bindings is better
3951/// than the other based on what kind of bindings they are.
3952static bool
3953isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3954 const StandardConversionSequence &SCS2) {
3955 // C++0x [over.ics.rank]p3b4:
3956 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3957 // implicit object parameter of a non-static member function declared
3958 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3959 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3960 // lvalue reference to a function lvalue and S2 binds an rvalue
3961 // reference*.
3962 //
3963 // FIXME: Rvalue references. We're going rogue with the above edits,
3964 // because the semantics in the current C++0x working paper (N3225 at the
3965 // time of this writing) break the standard definition of std::forward
3966 // and std::reference_wrapper when dealing with references to functions.
3967 // Proposed wording changes submitted to CWG for consideration.
3968 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3969 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3970 return false;
3971
3972 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3973 SCS2.IsLvalueReference) ||
3974 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3975 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3976}
3977
3978enum class FixedEnumPromotion {
3979 None,
3980 ToUnderlyingType,
3981 ToPromotedUnderlyingType
3982};
3983
3984/// Returns kind of fixed enum promotion the \a SCS uses.
3985static FixedEnumPromotion
3986getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3987
3988 if (SCS.Second != ICK_Integral_Promotion)
3989 return FixedEnumPromotion::None;
3990
3991 QualType FromType = SCS.getFromType();
3992 if (!FromType->isEnumeralType())
3993 return FixedEnumPromotion::None;
3994
3995 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3996 if (!Enum->isFixed())
3997 return FixedEnumPromotion::None;
3998
3999 QualType UnderlyingType = Enum->getIntegerType();
4000 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4001 return FixedEnumPromotion::ToUnderlyingType;
4002
4003 return FixedEnumPromotion::ToPromotedUnderlyingType;
4004}
4005
4006/// CompareStandardConversionSequences - Compare two standard
4007/// conversion sequences to determine whether one is better than the
4008/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4009static ImplicitConversionSequence::CompareKind
4010CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4011 const StandardConversionSequence& SCS1,
4012 const StandardConversionSequence& SCS2)
4013{
4014 // Standard conversion sequence S1 is a better conversion sequence
4015 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4016
4017 // -- S1 is a proper subsequence of S2 (comparing the conversion
4018 // sequences in the canonical form defined by 13.3.3.1.1,
4019 // excluding any Lvalue Transformation; the identity conversion
4020 // sequence is considered to be a subsequence of any
4021 // non-identity conversion sequence) or, if not that,
4022 if (ImplicitConversionSequence::CompareKind CK
4023 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4024 return CK;
4025
4026 // -- the rank of S1 is better than the rank of S2 (by the rules
4027 // defined below), or, if not that,
4028 ImplicitConversionRank Rank1 = SCS1.getRank();
4029 ImplicitConversionRank Rank2 = SCS2.getRank();
4030 if (Rank1 < Rank2)
4031 return ImplicitConversionSequence::Better;
4032 else if (Rank2 < Rank1)
4033 return ImplicitConversionSequence::Worse;
4034
4035 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4036 // are indistinguishable unless one of the following rules
4037 // applies:
4038
4039 // A conversion that is not a conversion of a pointer, or
4040 // pointer to member, to bool is better than another conversion
4041 // that is such a conversion.
4042 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4043 return SCS2.isPointerConversionToBool()
4044 ? ImplicitConversionSequence::Better
4045 : ImplicitConversionSequence::Worse;
4046
4047 // C++14 [over.ics.rank]p4b2:
4048 // This is retroactively applied to C++11 by CWG 1601.
4049 //
4050 // A conversion that promotes an enumeration whose underlying type is fixed
4051 // to its underlying type is better than one that promotes to the promoted
4052 // underlying type, if the two are different.
4053 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4054 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4055 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4056 FEP1 != FEP2)
4057 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4058 ? ImplicitConversionSequence::Better
4059 : ImplicitConversionSequence::Worse;
4060
4061 // C++ [over.ics.rank]p4b2:
4062 //
4063 // If class B is derived directly or indirectly from class A,
4064 // conversion of B* to A* is better than conversion of B* to
4065 // void*, and conversion of A* to void* is better than conversion
4066 // of B* to void*.
4067 bool SCS1ConvertsToVoid
4068 = SCS1.isPointerConversionToVoidPointer(S.Context);
4069 bool SCS2ConvertsToVoid
4070 = SCS2.isPointerConversionToVoidPointer(S.Context);
4071 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4072 // Exactly one of the conversion sequences is a conversion to
4073 // a void pointer; it's the worse conversion.
4074 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4075 : ImplicitConversionSequence::Worse;
4076 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4077 // Neither conversion sequence converts to a void pointer; compare
4078 // their derived-to-base conversions.
4079 if (ImplicitConversionSequence::CompareKind DerivedCK
4080 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4081 return DerivedCK;
4082 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4083 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4084 // Both conversion sequences are conversions to void
4085 // pointers. Compare the source types to determine if there's an
4086 // inheritance relationship in their sources.
4087 QualType FromType1 = SCS1.getFromType();
4088 QualType FromType2 = SCS2.getFromType();
4089
4090 // Adjust the types we're converting from via the array-to-pointer
4091 // conversion, if we need to.
4092 if (SCS1.First == ICK_Array_To_Pointer)
4093 FromType1 = S.Context.getArrayDecayedType(FromType1);
4094 if (SCS2.First == ICK_Array_To_Pointer)
4095 FromType2 = S.Context.getArrayDecayedType(FromType2);
4096
4097 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4098 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4099
4100 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4101 return ImplicitConversionSequence::Better;
4102 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4103 return ImplicitConversionSequence::Worse;
4104
4105 // Objective-C++: If one interface is more specific than the
4106 // other, it is the better one.
4107 const ObjCObjectPointerType* FromObjCPtr1
4108 = FromType1->getAs<ObjCObjectPointerType>();
4109 const ObjCObjectPointerType* FromObjCPtr2
4110 = FromType2->getAs<ObjCObjectPointerType>();
4111 if (FromObjCPtr1 && FromObjCPtr2) {
4112 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4113 FromObjCPtr2);
4114 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4115 FromObjCPtr1);
4116 if (AssignLeft != AssignRight) {
4117 return AssignLeft? ImplicitConversionSequence::Better
4118 : ImplicitConversionSequence::Worse;
4119 }
4120 }
4121 }
4122
4123 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4124 // Check for a better reference binding based on the kind of bindings.
4125 if (isBetterReferenceBindingKind(SCS1, SCS2))
4126 return ImplicitConversionSequence::Better;
4127 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4128 return ImplicitConversionSequence::Worse;
4129 }
4130
4131 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4132 // bullet 3).
4133 if (ImplicitConversionSequence::CompareKind QualCK
4134 = CompareQualificationConversions(S, SCS1, SCS2))
4135 return QualCK;
4136
4137 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4138 // C++ [over.ics.rank]p3b4:
4139 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4140 // which the references refer are the same type except for
4141 // top-level cv-qualifiers, and the type to which the reference
4142 // initialized by S2 refers is more cv-qualified than the type
4143 // to which the reference initialized by S1 refers.
4144 QualType T1 = SCS1.getToType(2);
4145 QualType T2 = SCS2.getToType(2);
4146 T1 = S.Context.getCanonicalType(T1);
4147 T2 = S.Context.getCanonicalType(T2);
4148 Qualifiers T1Quals, T2Quals;
4149 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4150 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4151 if (UnqualT1 == UnqualT2) {
4152 // Objective-C++ ARC: If the references refer to objects with different
4153 // lifetimes, prefer bindings that don't change lifetime.
4154 if (SCS1.ObjCLifetimeConversionBinding !=
4155 SCS2.ObjCLifetimeConversionBinding) {
4156 return SCS1.ObjCLifetimeConversionBinding
4157 ? ImplicitConversionSequence::Worse
4158 : ImplicitConversionSequence::Better;
4159 }
4160
4161 // If the type is an array type, promote the element qualifiers to the
4162 // type for comparison.
4163 if (isa<ArrayType>(T1) && T1Quals)
4164 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4165 if (isa<ArrayType>(T2) && T2Quals)
4166 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4167 if (T2.isMoreQualifiedThan(T1))
4168 return ImplicitConversionSequence::Better;
4169 if (T1.isMoreQualifiedThan(T2))
4170 return ImplicitConversionSequence::Worse;
4171 }
4172 }
4173
4174 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4175 // floating-to-integral conversion if the integral conversion
4176 // is between types of the same size.
4177 // For example:
4178 // void f(float);
4179 // void f(int);
4180 // int main {
4181 // long a;
4182 // f(a);
4183 // }
4184 // Here, MSVC will call f(int) instead of generating a compile error
4185 // as clang will do in standard mode.
4186 if (S.getLangOpts().MSVCCompat &&
4187 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4188 SCS1.Second == ICK_Integral_Conversion &&
4189 SCS2.Second == ICK_Floating_Integral &&
4190 S.Context.getTypeSize(SCS1.getFromType()) ==
4191 S.Context.getTypeSize(SCS1.getToType(2)))
4192 return ImplicitConversionSequence::Better;
4193
4194 // Prefer a compatible vector conversion over a lax vector conversion
4195 // For example:
4196 //
4197 // typedef float __v4sf __attribute__((__vector_size__(16)));
4198 // void f(vector float);
4199 // void f(vector signed int);
4200 // int main() {
4201 // __v4sf a;
4202 // f(a);
4203 // }
4204 // Here, we'd like to choose f(vector float) and not
4205 // report an ambiguous call error
4206 if (SCS1.Second == ICK_Vector_Conversion &&
4207 SCS2.Second == ICK_Vector_Conversion) {
4208 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4209 SCS1.getFromType(), SCS1.getToType(2));
4210 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4211 SCS2.getFromType(), SCS2.getToType(2));
4212
4213 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4214 return SCS1IsCompatibleVectorConversion
4215 ? ImplicitConversionSequence::Better
4216 : ImplicitConversionSequence::Worse;
4217 }
4218
4219 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4220 SCS2.Second == ICK_SVE_Vector_Conversion) {
4221 bool SCS1IsCompatibleSVEVectorConversion =
4222 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4223 bool SCS2IsCompatibleSVEVectorConversion =
4224 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4225
4226 if (SCS1IsCompatibleSVEVectorConversion !=
4227 SCS2IsCompatibleSVEVectorConversion)
4228 return SCS1IsCompatibleSVEVectorConversion
4229 ? ImplicitConversionSequence::Better
4230 : ImplicitConversionSequence::Worse;
4231 }
4232
4233 return ImplicitConversionSequence::Indistinguishable;
4234}
4235
4236/// CompareQualificationConversions - Compares two standard conversion
4237/// sequences to determine whether they can be ranked based on their
4238/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4239static ImplicitConversionSequence::CompareKind
4240CompareQualificationConversions(Sema &S,
4241 const StandardConversionSequence& SCS1,
4242 const StandardConversionSequence& SCS2) {
4243 // C++ [over.ics.rank]p3:
4244 // -- S1 and S2 differ only in their qualification conversion and
4245 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4246 // [C++98]
4247 // [...] and the cv-qualification signature of type T1 is a proper subset
4248 // of the cv-qualification signature of type T2, and S1 is not the
4249 // deprecated string literal array-to-pointer conversion (4.2).
4250 // [C++2a]
4251 // [...] where T1 can be converted to T2 by a qualification conversion.
4252 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4253 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4254 return ImplicitConversionSequence::Indistinguishable;
4255
4256 // FIXME: the example in the standard doesn't use a qualification
4257 // conversion (!)
4258 QualType T1 = SCS1.getToType(2);
4259 QualType T2 = SCS2.getToType(2);
4260 T1 = S.Context.getCanonicalType(T1);
4261 T2 = S.Context.getCanonicalType(T2);
4262 assert(!T1->isReferenceType() && !T2->isReferenceType())(static_cast <bool> (!T1->isReferenceType() &&
!T2->isReferenceType()) ? void (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "clang/lib/Sema/SemaOverload.cpp", 4262, __extension__ __PRETTY_FUNCTION__
))
;
4263 Qualifiers T1Quals, T2Quals;
4264 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4265 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4266
4267 // If the types are the same, we won't learn anything by unwrapping
4268 // them.
4269 if (UnqualT1 == UnqualT2)
4270 return ImplicitConversionSequence::Indistinguishable;
4271
4272 // Don't ever prefer a standard conversion sequence that uses the deprecated
4273 // string literal array to pointer conversion.
4274 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4275 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4276
4277 // Objective-C++ ARC:
4278 // Prefer qualification conversions not involving a change in lifetime
4279 // to qualification conversions that do change lifetime.
4280 if (SCS1.QualificationIncludesObjCLifetime &&
4281 !SCS2.QualificationIncludesObjCLifetime)
4282 CanPick1 = false;
4283 if (SCS2.QualificationIncludesObjCLifetime &&
4284 !SCS1.QualificationIncludesObjCLifetime)
4285 CanPick2 = false;
4286
4287 bool ObjCLifetimeConversion;
4288 if (CanPick1 &&
4289 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4290 CanPick1 = false;
4291 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4292 // directions, so we can't short-cut this second check in general.
4293 if (CanPick2 &&
4294 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4295 CanPick2 = false;
4296
4297 if (CanPick1 != CanPick2)
4298 return CanPick1 ? ImplicitConversionSequence::Better
4299 : ImplicitConversionSequence::Worse;
4300 return ImplicitConversionSequence::Indistinguishable;
4301}
4302
4303/// CompareDerivedToBaseConversions - Compares two standard conversion
4304/// sequences to determine whether they can be ranked based on their
4305/// various kinds of derived-to-base conversions (C++
4306/// [over.ics.rank]p4b3). As part of these checks, we also look at
4307/// conversions between Objective-C interface types.
4308static ImplicitConversionSequence::CompareKind
4309CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4310 const StandardConversionSequence& SCS1,
4311 const StandardConversionSequence& SCS2) {
4312 QualType FromType1 = SCS1.getFromType();
4313 QualType ToType1 = SCS1.getToType(1);
4314 QualType FromType2 = SCS2.getFromType();
4315 QualType ToType2 = SCS2.getToType(1);
4316
4317 // Adjust the types we're converting from via the array-to-pointer
4318 // conversion, if we need to.
4319 if (SCS1.First == ICK_Array_To_Pointer)
4320 FromType1 = S.Context.getArrayDecayedType(FromType1);
4321 if (SCS2.First == ICK_Array_To_Pointer)
4322 FromType2 = S.Context.getArrayDecayedType(FromType2);
4323
4324 // Canonicalize all of the types.
4325 FromType1 = S.Context.getCanonicalType(FromType1);
4326 ToType1 = S.Context.getCanonicalType(ToType1);
4327 FromType2 = S.Context.getCanonicalType(FromType2);
4328 ToType2 = S.Context.getCanonicalType(ToType2);
4329
4330 // C++ [over.ics.rank]p4b3:
4331 //
4332 // If class B is derived directly or indirectly from class A and
4333 // class C is derived directly or indirectly from B,
4334 //
4335 // Compare based on pointer conversions.
4336 if (SCS1.Second == ICK_Pointer_Conversion &&
4337 SCS2.Second == ICK_Pointer_Conversion &&
4338 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4339 FromType1->isPointerType() && FromType2->isPointerType() &&
4340 ToType1->isPointerType() && ToType2->isPointerType()) {
4341 QualType FromPointee1 =
4342 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4343 QualType ToPointee1 =
4344 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4345 QualType FromPointee2 =
4346 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4347 QualType ToPointee2 =
4348 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4349
4350 // -- conversion of C* to B* is better than conversion of C* to A*,
4351 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4352 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4353 return ImplicitConversionSequence::Better;
4354 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4355 return ImplicitConversionSequence::Worse;
4356 }
4357
4358 // -- conversion of B* to A* is better than conversion of C* to A*,
4359 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4360 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4361 return ImplicitConversionSequence::Better;
4362 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4363 return ImplicitConversionSequence::Worse;
4364 }
4365 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4366 SCS2.Second == ICK_Pointer_Conversion) {
4367 const ObjCObjectPointerType *FromPtr1
4368 = FromType1->getAs<ObjCObjectPointerType>();
4369 const ObjCObjectPointerType *FromPtr2
4370 = FromType2->getAs<ObjCObjectPointerType>();
4371 const ObjCObjectPointerType *ToPtr1
4372 = ToType1->getAs<ObjCObjectPointerType>();
4373 const ObjCObjectPointerType *ToPtr2
4374 = ToType2->getAs<ObjCObjectPointerType>();
4375
4376 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4377 // Apply the same conversion ranking rules for Objective-C pointer types
4378 // that we do for C++ pointers to class types. However, we employ the
4379 // Objective-C pseudo-subtyping relationship used for assignment of
4380 // Objective-C pointer types.
4381 bool FromAssignLeft
4382 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4383 bool FromAssignRight
4384 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4385 bool ToAssignLeft
4386 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4387 bool ToAssignRight
4388 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4389
4390 // A conversion to an a non-id object pointer type or qualified 'id'
4391 // type is better than a conversion to 'id'.
4392 if (ToPtr1->isObjCIdType() &&
4393 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4394 return ImplicitConversionSequence::Worse;
4395 if (ToPtr2->isObjCIdType() &&
4396 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4397 return ImplicitConversionSequence::Better;
4398
4399 // A conversion to a non-id object pointer type is better than a
4400 // conversion to a qualified 'id' type
4401 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4402 return ImplicitConversionSequence::Worse;
4403 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4404 return ImplicitConversionSequence::Better;
4405
4406 // A conversion to an a non-Class object pointer type or qualified 'Class'
4407 // type is better than a conversion to 'Class'.
4408 if (ToPtr1->isObjCClassType() &&
4409 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4410 return ImplicitConversionSequence::Worse;
4411 if (ToPtr2->isObjCClassType() &&
4412 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4413 return ImplicitConversionSequence::Better;
4414
4415 // A conversion to a non-Class object pointer type is better than a
4416 // conversion to a qualified 'Class' type.
4417 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4418 return ImplicitConversionSequence::Worse;
4419 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4420 return ImplicitConversionSequence::Better;
4421
4422 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4423 if (S.Context.hasSameType(FromType1, FromType2) &&
4424 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4425 (ToAssignLeft != ToAssignRight)) {
4426 if (FromPtr1->isSpecialized()) {
4427 // "conversion of B<A> * to B * is better than conversion of B * to
4428 // C *.
4429 bool IsFirstSame =
4430 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4431 bool IsSecondSame =
4432 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4433 if (IsFirstSame) {
4434 if (!IsSecondSame)
4435 return ImplicitConversionSequence::Better;
4436 } else if (IsSecondSame)
4437 return ImplicitConversionSequence::Worse;
4438 }
4439 return ToAssignLeft? ImplicitConversionSequence::Worse
4440 : ImplicitConversionSequence::Better;
4441 }
4442
4443 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4444 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4445 (FromAssignLeft != FromAssignRight))
4446 return FromAssignLeft? ImplicitConversionSequence::Better
4447 : ImplicitConversionSequence::Worse;
4448 }
4449 }
4450
4451 // Ranking of member-pointer types.
4452 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4453 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4454 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4455 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4456 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4457 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4458 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4459 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4460 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4461 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4462 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4463 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4464 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4465 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4466 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4467 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4468 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4469 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4470 return ImplicitConversionSequence::Worse;
4471 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4472 return ImplicitConversionSequence::Better;
4473 }
4474 // conversion of B::* to C::* is better than conversion of A::* to C::*
4475 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4476 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4477 return ImplicitConversionSequence::Better;
4478 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4479 return ImplicitConversionSequence::Worse;
4480 }
4481 }
4482
4483 if (SCS1.Second == ICK_Derived_To_Base) {
4484 // -- conversion of C to B is better than conversion of C to A,
4485 // -- binding of an expression of type C to a reference of type
4486 // B& is better than binding an expression of type C to a
4487 // reference of type A&,
4488 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4489 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4490 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4491 return ImplicitConversionSequence::Better;
4492 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4493 return ImplicitConversionSequence::Worse;
4494 }
4495
4496 // -- conversion of B to A is better than conversion of C to A.
4497 // -- binding of an expression of type B to a reference of type
4498 // A& is better than binding an expression of type C to a
4499 // reference of type A&,
4500 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4501 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4502 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4503 return ImplicitConversionSequence::Better;
4504 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4505 return ImplicitConversionSequence::Worse;
4506 }
4507 }
4508
4509 return ImplicitConversionSequence::Indistinguishable;
4510}
4511
4512/// Determine whether the given type is valid, e.g., it is not an invalid
4513/// C++ class.
4514static bool isTypeValid(QualType T) {
4515 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4516 return !Record->isInvalidDecl();
4517
4518 return true;
4519}
4520
4521static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4522 if (!T.getQualifiers().hasUnaligned())
4523 return T;
4524
4525 Qualifiers Q;
4526 T = Ctx.getUnqualifiedArrayType(T, Q);
4527 Q.removeUnaligned();
4528 return Ctx.getQualifiedType(T, Q);
4529}
4530
4531/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4532/// determine whether they are reference-compatible,
4533/// reference-related, or incompatible, for use in C++ initialization by
4534/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4535/// type, and the first type (T1) is the pointee type of the reference
4536/// type being initialized.
4537Sema::ReferenceCompareResult
4538Sema::CompareReferenceRelationship(SourceLocation Loc,
4539 QualType OrigT1, QualType OrigT2,
4540 ReferenceConversions *ConvOut) {
4541 assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4542, __extension__ __PRETTY_FUNCTION__
))
4542 "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4542, __extension__ __PRETTY_FUNCTION__
))
;
4543 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() &&
"T2 cannot be a reference type") ? void (0) : __assert_fail (
"!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4543, __extension__ __PRETTY_FUNCTION__
))
;
4544
4545 QualType T1 = Context.getCanonicalType(OrigT1);
4546 QualType T2 = Context.getCanonicalType(OrigT2);
4547 Qualifiers T1Quals, T2Quals;
4548 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4549 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4550
4551 ReferenceConversions ConvTmp;
4552 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4553 Conv = ReferenceConversions();
4554
4555 // C++2a [dcl.init.ref]p4:
4556 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4557 // reference-related to "cv2 T2" if T1 is similar to T2, or
4558 // T1 is a base class of T2.
4559 // "cv1 T1" is reference-compatible with "cv2 T2" if
4560 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4561 // "pointer to cv1 T1" via a standard conversion sequence.
4562
4563 // Check for standard conversions we can apply to pointers: derived-to-base
4564 // conversions, ObjC pointer conversions, and function pointer conversions.
4565 // (Qualification conversions are checked last.)
4566 QualType ConvertedT2;
4567 if (UnqualT1 == UnqualT2) {
4568 // Nothing to do.
4569 } else if (isCompleteType(Loc, OrigT2) &&
4570 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4571 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4572 Conv |= ReferenceConversions::DerivedToBase;
4573 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4574 UnqualT2->isObjCObjectOrInterfaceType() &&
4575 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4576 Conv |= ReferenceConversions::ObjC;
4577 else if (UnqualT2->isFunctionType() &&
4578 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4579 Conv |= ReferenceConversions::Function;
4580 // No need to check qualifiers; function types don't have them.
4581 return Ref_Compatible;
4582 }
4583 bool ConvertedReferent = Conv != 0;
4584
4585 // We can have a qualification conversion. Compute whether the types are
4586 // similar at the same time.
4587 bool PreviousToQualsIncludeConst = true;
4588 bool TopLevel = true;
4589 do {
4590 if (T1 == T2)
4591 break;
4592
4593 // We will need a qualification conversion.
4594 Conv |= ReferenceConversions::Qualification;
4595
4596 // Track whether we performed a qualification conversion anywhere other
4597 // than the top level. This matters for ranking reference bindings in
4598 // overload resolution.
4599 if (!TopLevel)
4600 Conv |= ReferenceConversions::NestedQualification;
4601
4602 // MS compiler ignores __unaligned qualifier for references; do the same.
4603 T1 = withoutUnaligned(Context, T1);
4604 T2 = withoutUnaligned(Context, T2);
4605
4606 // If we find a qualifier mismatch, the types are not reference-compatible,
4607 // but are still be reference-related if they're similar.
4608 bool ObjCLifetimeConversion = false;
4609 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4610 PreviousToQualsIncludeConst,
4611 ObjCLifetimeConversion))
4612 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4613 ? Ref_Related
4614 : Ref_Incompatible;
4615
4616 // FIXME: Should we track this for any level other than the first?
4617 if (ObjCLifetimeConversion)
4618 Conv |= ReferenceConversions::ObjCLifetime;
4619
4620 TopLevel = false;
4621 } while (Context.UnwrapSimilarTypes(T1, T2));
4622
4623 // At this point, if the types are reference-related, we must either have the
4624 // same inner type (ignoring qualifiers), or must have already worked out how
4625 // to convert the referent.
4626 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4627 ? Ref_Compatible
4628 : Ref_Incompatible;
4629}
4630
4631/// Look for a user-defined conversion to a value reference-compatible
4632/// with DeclType. Return true if something definite is found.
4633static bool
4634FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4635 QualType DeclType, SourceLocation DeclLoc,
4636 Expr *Init, QualType T2, bool AllowRvalues,
4637 bool AllowExplicit) {
4638 assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types."
) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "clang/lib/Sema/SemaOverload.cpp", 4638, __extension__ __PRETTY_FUNCTION__
))
;
4639 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4640
4641 OverloadCandidateSet CandidateSet(
4642 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4643 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4644 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4645 NamedDecl *D = *I;
4646 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4647 if (isa<UsingShadowDecl>(D))
4648 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4649
4650 FunctionTemplateDecl *ConvTemplate
4651 = dyn_cast<FunctionTemplateDecl>(D);
4652 CXXConversionDecl *Conv;
4653 if (ConvTemplate)
4654 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4655 else
4656 Conv = cast<CXXConversionDecl>(D);
4657
4658 if (AllowRvalues) {
4659 // If we are initializing an rvalue reference, don't permit conversion
4660 // functions that return lvalues.
4661 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4662 const ReferenceType *RefType
4663 = Conv->getConversionType()->getAs<LValueReferenceType>();
4664 if (RefType && !RefType->getPointeeType()->isFunctionType())
4665 continue;
4666 }
4667
4668 if (!ConvTemplate &&
4669 S.CompareReferenceRelationship(
4670 DeclLoc,
4671 Conv->getConversionType()
4672 .getNonReferenceType()
4673 .getUnqualifiedType(),
4674 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4675 Sema::Ref_Incompatible)
4676 continue;
4677 } else {
4678 // If the conversion function doesn't return a reference type,
4679 // it can't be considered for this conversion. An rvalue reference
4680 // is only acceptable if its referencee is a function type.
4681
4682 const ReferenceType *RefType =
4683 Conv->getConversionType()->getAs<ReferenceType>();
4684 if (!RefType ||
4685 (!RefType->isLValueReferenceType() &&
4686 !RefType->getPointeeType()->isFunctionType()))
4687 continue;
4688 }
4689
4690 if (ConvTemplate)
4691 S.AddTemplateConversionCandidate(
4692 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4693 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4694 else
4695 S.AddConversionCandidate(
4696 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4697 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4698 }
4699
4700 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4701
4702 OverloadCandidateSet::iterator Best;
4703 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4704 case OR_Success:
4705 // C++ [over.ics.ref]p1:
4706 //
4707 // [...] If the parameter binds directly to the result of
4708 // applying a conversion function to the argument
4709 // expression, the implicit conversion sequence is a
4710 // user-defined conversion sequence (13.3.3.1.2), with the
4711 // second standard conversion sequence either an identity
4712 // conversion or, if the conversion function returns an
4713 // entity of a type that is a derived class of the parameter
4714 // type, a derived-to-base Conversion.
4715 if (!Best->FinalConversion.DirectBinding)
4716 return false;
4717
4718 ICS.setUserDefined();
4719 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4720 ICS.UserDefined.After = Best->FinalConversion;
4721 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4722 ICS.UserDefined.ConversionFunction = Best->Function;
4723 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4724 ICS.UserDefined.EllipsisConversion = false;
4725 assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4727, __extension__ __PRETTY_FUNCTION__
))
4726 ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4727, __extension__ __PRETTY_FUNCTION__
))
4727 "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4727, __extension__ __PRETTY_FUNCTION__
))
;
4728 return true;
4729
4730 case OR_Ambiguous:
4731 ICS.setAmbiguous();
4732 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4733 Cand != CandidateSet.end(); ++Cand)
4734 if (Cand->Best)
4735 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4736 return true;
4737
4738 case OR_No_Viable_Function:
4739 case OR_Deleted:
4740 // There was no suitable conversion, or we found a deleted
4741 // conversion; continue with other checks.
4742 return false;
4743 }
4744
4745 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 4745)
;
4746}
4747
4748/// Compute an implicit conversion sequence for reference
4749/// initialization.
4750static ImplicitConversionSequence
4751TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4752 SourceLocation DeclLoc,
4753 bool SuppressUserConversions,
4754 bool AllowExplicit) {
4755 assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() &&
"Reference init needs a reference") ? void (0) : __assert_fail
("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "clang/lib/Sema/SemaOverload.cpp", 4755, __extension__ __PRETTY_FUNCTION__
))
;
4756
4757 // Most paths end in a failed conversion.
4758 ImplicitConversionSequence ICS;
4759 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4760
4761 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4762 QualType T2 = Init->getType();
4763
4764 // If the initializer is the address of an overloaded function, try
4765 // to resolve the overloaded function. If all goes well, T2 is the
4766 // type of the resulting function.
4767 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4768 DeclAccessPair Found;
4769 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4770 false, Found))
4771 T2 = Fn->getType();
4772 }
4773
4774 // Compute some basic properties of the types and the initializer.
4775 bool isRValRef = DeclType->isRValueReferenceType();
4776 Expr::Classification InitCategory = Init->Classify(S.Context);
4777
4778 Sema::ReferenceConversions RefConv;
4779 Sema::ReferenceCompareResult RefRelationship =
4780 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4781
4782 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4783 ICS.setStandard();
4784 ICS.Standard.First = ICK_Identity;
4785 // FIXME: A reference binding can be a function conversion too. We should
4786 // consider that when ordering reference-to-function bindings.
4787 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4788 ? ICK_Derived_To_Base
4789 : (RefConv & Sema::ReferenceConversions::ObjC)
4790 ? ICK_Compatible_Conversion
4791 : ICK_Identity;
4792 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4793 // a reference binding that performs a non-top-level qualification
4794 // conversion as a qualification conversion, not as an identity conversion.
4795 ICS.Standard.Third = (RefConv &
4796 Sema::ReferenceConversions::NestedQualification)
4797 ? ICK_Qualification
4798 : ICK_Identity;
4799 ICS.Standard.setFromType(T2);
4800 ICS.Standard.setToType(0, T2);
4801 ICS.Standard.setToType(1, T1);
4802 ICS.Standard.setToType(2, T1);
4803 ICS.Standard.ReferenceBinding = true;
4804 ICS.Standard.DirectBinding = BindsDirectly;
4805 ICS.Standard.IsLvalueReference = !isRValRef;
4806 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4807 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4808 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4809 ICS.Standard.ObjCLifetimeConversionBinding =
4810 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4811 ICS.Standard.CopyConstructor = nullptr;
4812 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4813 };
4814
4815 // C++0x [dcl.init.ref]p5:
4816 // A reference to type "cv1 T1" is initialized by an expression
4817 // of type "cv2 T2" as follows:
4818
4819 // -- If reference is an lvalue reference and the initializer expression
4820 if (!isRValRef) {
4821 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4822 // reference-compatible with "cv2 T2," or
4823 //
4824 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4825 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4826 // C++ [over.ics.ref]p1:
4827 // When a parameter of reference type binds directly (8.5.3)
4828 // to an argument expression, the implicit conversion sequence
4829 // is the identity conversion, unless the argument expression
4830 // has a type that is a derived class of the parameter type,
4831 // in which case the implicit conversion sequence is a
4832 // derived-to-base Conversion (13.3.3.1).
4833 SetAsReferenceBinding(/*BindsDirectly=*/true);
4834
4835 // Nothing more to do: the inaccessibility/ambiguity check for
4836 // derived-to-base conversions is suppressed when we're
4837 // computing the implicit conversion sequence (C++
4838 // [over.best.ics]p2).
4839 return ICS;
4840 }
4841
4842 // -- has a class type (i.e., T2 is a class type), where T1 is
4843 // not reference-related to T2, and can be implicitly
4844 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4845 // is reference-compatible with "cv3 T3" 92) (this
4846 // conversion is selected by enumerating the applicable
4847 // conversion functions (13.3.1.6) and choosing the best
4848 // one through overload resolution (13.3)),
4849 if (!SuppressUserConversions && T2->isRecordType() &&
4850 S.isCompleteType(DeclLoc, T2) &&
4851 RefRelationship == Sema::Ref_Incompatible) {
4852 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4853 Init, T2, /*AllowRvalues=*/false,
4854 AllowExplicit))
4855 return ICS;
4856 }
4857 }
4858
4859 // -- Otherwise, the reference shall be an lvalue reference to a
4860 // non-volatile const type (i.e., cv1 shall be const), or the reference
4861 // shall be an rvalue reference.
4862 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4863 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4864 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4865 return ICS;
4866 }
4867
4868 // -- If the initializer expression
4869 //
4870 // -- is an xvalue, class prvalue, array prvalue or function
4871 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4872 if (RefRelationship == Sema::Ref_Compatible &&
4873 (InitCategory.isXValue() ||
4874 (InitCategory.isPRValue() &&
4875 (T2->isRecordType() || T2->isArrayType())) ||
4876 (InitCategory.isLValue() && T2->isFunctionType()))) {
4877 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4878 // binding unless we're binding to a class prvalue.
4879 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4880 // allow the use of rvalue references in C++98/03 for the benefit of
4881 // standard library implementors; therefore, we need the xvalue check here.
4882 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4883 !(InitCategory.isPRValue() || T2->isRecordType()));
4884 return ICS;
4885 }
4886
4887 // -- has a class type (i.e., T2 is a class type), where T1 is not
4888 // reference-related to T2, and can be implicitly converted to
4889 // an xvalue, class prvalue, or function lvalue of type
4890 // "cv3 T3", where "cv1 T1" is reference-compatible with
4891 // "cv3 T3",
4892 //
4893 // then the reference is bound to the value of the initializer
4894 // expression in the first case and to the result of the conversion
4895 // in the second case (or, in either case, to an appropriate base
4896 // class subobject).
4897 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4898 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4899 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4900 Init, T2, /*AllowRvalues=*/true,
4901 AllowExplicit)) {
4902 // In the second case, if the reference is an rvalue reference
4903 // and the second standard conversion sequence of the
4904 // user-defined conversion sequence includes an lvalue-to-rvalue
4905 // conversion, the program is ill-formed.
4906 if (ICS.isUserDefined() && isRValRef &&
4907 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4908 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4909
4910 return ICS;
4911 }
4912
4913 // A temporary of function type cannot be created; don't even try.
4914 if (T1->isFunctionType())
4915 return ICS;
4916
4917 // -- Otherwise, a temporary of type "cv1 T1" is created and
4918 // initialized from the initializer expression using the
4919 // rules for a non-reference copy initialization (8.5). The
4920 // reference is then bound to the temporary. If T1 is
4921 // reference-related to T2, cv1 must be the same
4922 // cv-qualification as, or greater cv-qualification than,
4923 // cv2; otherwise, the program is ill-formed.
4924 if (RefRelationship == Sema::Ref_Related) {
4925 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4926 // we would be reference-compatible or reference-compatible with
4927 // added qualification. But that wasn't the case, so the reference
4928 // initialization fails.
4929 //
4930 // Note that we only want to check address spaces and cvr-qualifiers here.
4931 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4932 Qualifiers T1Quals = T1.getQualifiers();
4933 Qualifiers T2Quals = T2.getQualifiers();
4934 T1Quals.removeObjCGCAttr();
4935 T1Quals.removeObjCLifetime();
4936 T2Quals.removeObjCGCAttr();
4937 T2Quals.removeObjCLifetime();
4938 // MS compiler ignores __unaligned qualifier for references; do the same.
4939 T1Quals.removeUnaligned();
4940 T2Quals.removeUnaligned();
4941 if (!T1Quals.compatiblyIncludes(T2Quals))
4942 return ICS;
4943 }
4944
4945 // If at least one of the types is a class type, the types are not
4946 // related, and we aren't allowed any user conversions, the
4947 // reference binding fails. This case is important for breaking
4948 // recursion, since TryImplicitConversion below will attempt to
4949 // create a temporary through the use of a copy constructor.
4950 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4951 (T1->isRecordType() || T2->isRecordType()))
4952 return ICS;
4953
4954 // If T1 is reference-related to T2 and the reference is an rvalue
4955 // reference, the initializer expression shall not be an lvalue.
4956 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4957 Init->Classify(S.Context).isLValue()) {
4958 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4959 return ICS;
4960 }
4961
4962 // C++ [over.ics.ref]p2:
4963 // When a parameter of reference type is not bound directly to
4964 // an argument expression, the conversion sequence is the one
4965 // required to convert the argument expression to the
4966 // underlying type of the reference according to
4967 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4968 // to copy-initializing a temporary of the underlying type with
4969 // the argument expression. Any difference in top-level
4970 // cv-qualification is subsumed by the initialization itself
4971 // and does not constitute a conversion.
4972 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4973 AllowedExplicit::None,
4974 /*InOverloadResolution=*/false,
4975 /*CStyle=*/false,
4976 /*AllowObjCWritebackConversion=*/false,
4977 /*AllowObjCConversionOnExplicit=*/false);
4978
4979 // Of course, that's still a reference binding.
4980 if (ICS.isStandard()) {
4981 ICS.Standard.ReferenceBinding = true;
4982 ICS.Standard.IsLvalueReference = !isRValRef;
4983 ICS.Standard.BindsToFunctionLvalue = false;
4984 ICS.Standard.BindsToRvalue = true;
4985 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4986 ICS.Standard.ObjCLifetimeConversionBinding = false;
4987 } else if (ICS.isUserDefined()) {
4988 const ReferenceType *LValRefType =
4989 ICS.UserDefined.ConversionFunction->getReturnType()
4990 ->getAs<LValueReferenceType>();
4991
4992 // C++ [over.ics.ref]p3:
4993 // Except for an implicit object parameter, for which see 13.3.1, a
4994 // standard conversion sequence cannot be formed if it requires [...]
4995 // binding an rvalue reference to an lvalue other than a function
4996 // lvalue.
4997 // Note that the function case is not possible here.
4998 if (isRValRef && LValRefType) {
4999 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5000 return ICS;
5001 }
5002
5003 ICS.UserDefined.After.ReferenceBinding = true;
5004 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5005 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5006 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5007 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5008 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5009 }
5010
5011 return ICS;
5012}
5013
5014static ImplicitConversionSequence
5015TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5016 bool SuppressUserConversions,
5017 bool InOverloadResolution,
5018 bool AllowObjCWritebackConversion,
5019 bool AllowExplicit = false);
5020
5021/// TryListConversion - Try to copy-initialize a value of type ToType from the
5022/// initializer list From.
5023static ImplicitConversionSequence
5024TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5025 bool SuppressUserConversions,
5026 bool InOverloadResolution,
5027 bool AllowObjCWritebackConversion) {
5028 // C++11 [over.ics.list]p1:
5029 // When an argument is an initializer list, it is not an expression and
5030 // special rules apply for converting it to a parameter type.
5031
5032 ImplicitConversionSequence Result;
5033 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5034
5035 // We need a complete type for what follows. With one C++20 exception,
5036 // incomplete types can never be initialized from init lists.
5037 QualType InitTy = ToType;
5038 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5039 if (AT && S.getLangOpts().CPlusPlus20)
5040 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5041 // C++20 allows list initialization of an incomplete array type.
5042 InitTy = IAT->getElementType();
5043 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5044 return Result;
5045
5046 // Per DR1467:
5047 // If the parameter type is a class X and the initializer list has a single
5048 // element of type cv U, where U is X or a class derived from X, the
5049 // implicit conversion sequence is the one required to convert the element
5050 // to the parameter type.
5051 //
5052 // Otherwise, if the parameter type is a character array [... ]
5053 // and the initializer list has a single element that is an
5054 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5055 // implicit conversion sequence is the identity conversion.
5056 if (From->getNumInits() == 1) {
5057 if (ToType->isRecordType()) {
5058 QualType InitType = From->getInit(0)->getType();
5059 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5060 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5061 return TryCopyInitialization(S, From->getInit(0), ToType,
5062 SuppressUserConversions,
5063 InOverloadResolution,
5064 AllowObjCWritebackConversion);
5065 }
5066
5067 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5068 InitializedEntity Entity =
5069 InitializedEntity::InitializeParameter(S.Context, ToType,
5070 /*Consumed=*/false);
5071 if (S.CanPerformCopyInitialization(Entity, From)) {
5072 Result.setStandard();
5073 Result.Standard.setAsIdentityConversion();
5074 Result.Standard.setFromType(ToType);
5075 Result.Standard.setAllToTypes(ToType);
5076 return Result;
5077 }
5078 }
5079 }
5080
5081 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5082 // C++11 [over.ics.list]p2:
5083 // If the parameter type is std::initializer_list<X> or "array of X" and
5084 // all the elements can be implicitly converted to X, the implicit
5085 // conversion sequence is the worst conversion necessary to convert an
5086 // element of the list to X.
5087 //
5088 // C++14 [over.ics.list]p3:
5089 // Otherwise, if the parameter type is "array of N X", if the initializer
5090 // list has exactly N elements or if it has fewer than N elements and X is
5091 // default-constructible, and if all the elements of the initializer list
5092 // can be implicitly converted to X, the implicit conversion sequence is
5093 // the worst conversion necessary to convert an element of the list to X.
5094 if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5095 unsigned e = From->getNumInits();
5096 ImplicitConversionSequence DfltElt;
5097 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5098 QualType());
5099 QualType ContTy = ToType;
5100 bool IsUnbounded = false;
5101 if (AT) {
5102 InitTy = AT->getElementType();
5103 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5104 if (CT->getSize().ult(e)) {
5105 // Too many inits, fatally bad
5106 Result.setBad(BadConversionSequence::too_many_initializers, From,
5107 ToType);
5108 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5109 return Result;
5110 }
5111 if (CT->getSize().ugt(e)) {
5112 // Need an init from empty {}, is there one?
5113 InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5114 From->getEndLoc());
5115 EmptyList.setType(S.Context.VoidTy);
5116 DfltElt = TryListConversion(
5117 S, &EmptyList, InitTy, SuppressUserConversions,
5118 InOverloadResolution, AllowObjCWritebackConversion);
5119 if (DfltElt.isBad()) {
5120 // No {} init, fatally bad
5121 Result.setBad(BadConversionSequence::too_few_initializers, From,
5122 ToType);
5123 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5124 return Result;
5125 }
5126 }
5127 } else {
5128 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array")(static_cast <bool> (isa<IncompleteArrayType>(AT)
&& "Expected incomplete array") ? void (0) : __assert_fail
("isa<IncompleteArrayType>(AT) && \"Expected incomplete array\""
, "clang/lib/Sema/SemaOverload.cpp", 5128, __extension__ __PRETTY_FUNCTION__
))
;
5129 IsUnbounded = true;
5130 if (!e) {
5131 // Cannot convert to zero-sized.
5132 Result.setBad(BadConversionSequence::too_few_initializers, From,
5133 ToType);
5134 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5135 return Result;
5136 }
5137 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5138 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5139 ArrayType::Normal, 0);
5140 }
5141 }
5142
5143 Result.setStandard();
5144 Result.Standard.setAsIdentityConversion();
5145 Result.Standard.setFromType(InitTy);
5146 Result.Standard.setAllToTypes(InitTy);
5147 for (unsigned i = 0; i < e; ++i) {
5148 Expr *Init = From->getInit(i);
5149 ImplicitConversionSequence ICS = TryCopyInitialization(
5150 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5151 AllowObjCWritebackConversion);
5152
5153 // Keep the worse conversion seen so far.
5154 // FIXME: Sequences are not totally ordered, so 'worse' can be
5155 // ambiguous. CWG has been informed.
5156 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5157 Result) ==
5158 ImplicitConversionSequence::Worse) {
5159 Result = ICS;
5160 // Bail as soon as we find something unconvertible.
5161 if (Result.isBad()) {
5162 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5163 return Result;
5164 }
5165 }
5166 }
5167
5168 // If we needed any implicit {} initialization, compare that now.
5169 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5170 // has been informed that this might not be the best thing.
5171 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5172 S, From->getEndLoc(), DfltElt, Result) ==
5173 ImplicitConversionSequence::Worse)
5174 Result = DfltElt;
5175 // Record the type being initialized so that we may compare sequences
5176 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5177 return Result;
5178 }
5179
5180 // C++14 [over.ics.list]p4:
5181 // C++11 [over.ics.list]p3:
5182 // Otherwise, if the parameter is a non-aggregate class X and overload
5183 // resolution chooses a single best constructor [...] the implicit
5184 // conversion sequence is a user-defined conversion sequence. If multiple
5185 // constructors are viable but none is better than the others, the
5186 // implicit conversion sequence is a user-defined conversion sequence.
5187 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5188 // This function can deal with initializer lists.
5189 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5190 AllowedExplicit::None,
5191 InOverloadResolution, /*CStyle=*/false,
5192 AllowObjCWritebackConversion,
5193 /*AllowObjCConversionOnExplicit=*/false);
5194 }
5195
5196 // C++14 [over.ics.list]p5:
5197 // C++11 [over.ics.list]p4:
5198 // Otherwise, if the parameter has an aggregate type which can be
5199 // initialized from the initializer list [...] the implicit conversion
5200 // sequence is a user-defined conversion sequence.
5201 if (ToType->isAggregateType()) {
5202 // Type is an aggregate, argument is an init list. At this point it comes
5203 // down to checking whether the initialization works.
5204 // FIXME: Find out whether this parameter is consumed or not.
5205 InitializedEntity Entity =
5206 InitializedEntity::InitializeParameter(S.Context, ToType,
5207 /*Consumed=*/false);
5208 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5209 From)) {
5210 Result.setUserDefined();
5211 Result.UserDefined.Before.setAsIdentityConversion();
5212 // Initializer lists don't have a type.
5213 Result.UserDefined.Before.setFromType(QualType());
5214 Result.UserDefined.Before.setAllToTypes(QualType());
5215
5216 Result.UserDefined.After.setAsIdentityConversion();
5217 Result.UserDefined.After.setFromType(ToType);
5218 Result.UserDefined.After.setAllToTypes(ToType);
5219 Result.UserDefined.ConversionFunction = nullptr;
5220 }
5221 return Result;
5222 }
5223
5224 // C++14 [over.ics.list]p6:
5225 // C++11 [over.ics.list]p5:
5226 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5227 if (ToType->isReferenceType()) {
5228 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5229 // mention initializer lists in any way. So we go by what list-
5230 // initialization would do and try to extrapolate from that.
5231
5232 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5233
5234 // If the initializer list has a single element that is reference-related
5235 // to the parameter type, we initialize the reference from that.
5236 if (From->getNumInits() == 1) {
5237 Expr *Init = From->getInit(0);
5238
5239 QualType T2 = Init->getType();
5240
5241 // If the initializer is the address of an overloaded function, try
5242 // to resolve the overloaded function. If all goes well, T2 is the
5243 // type of the resulting function.
5244 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5245 DeclAccessPair Found;
5246 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5247 Init, ToType, false, Found))
5248 T2 = Fn->getType();
5249 }
5250
5251 // Compute some basic properties of the types and the initializer.
5252 Sema::ReferenceCompareResult RefRelationship =
5253 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5254
5255 if (RefRelationship >= Sema::Ref_Related) {
5256 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5257 SuppressUserConversions,
5258 /*AllowExplicit=*/false);
5259 }
5260 }
5261
5262 // Otherwise, we bind the reference to a temporary created from the
5263 // initializer list.
5264 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5265 InOverloadResolution,
5266 AllowObjCWritebackConversion);
5267 if (Result.isFailure())
5268 return Result;
5269 assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5270, __extension__ __PRETTY_FUNCTION__
))
5270 "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5270, __extension__ __PRETTY_FUNCTION__
))
;
5271
5272 // Can we even bind to a temporary?
5273 if (ToType->isRValueReferenceType() ||
5274 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5275 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5276 Result.UserDefined.After;
5277 SCS.ReferenceBinding = true;
5278 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5279 SCS.BindsToRvalue = true;
5280 SCS.BindsToFunctionLvalue = false;
5281 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5282 SCS.ObjCLifetimeConversionBinding = false;
5283 } else
5284 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5285 From, ToType);
5286 return Result;
5287 }
5288
5289 // C++14 [over.ics.list]p7:
5290 // C++11 [over.ics.list]p6:
5291 // Otherwise, if the parameter type is not a class:
5292 if (!ToType->isRecordType()) {
5293 // - if the initializer list has one element that is not itself an
5294 // initializer list, the implicit conversion sequence is the one
5295 // required to convert the element to the parameter type.
5296 unsigned NumInits = From->getNumInits();
5297 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5298 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5299 SuppressUserConversions,
5300 InOverloadResolution,
5301 AllowObjCWritebackConversion);
5302 // - if the initializer list has no elements, the implicit conversion
5303 // sequence is the identity conversion.
5304 else if (NumInits == 0) {
5305 Result.setStandard();
5306 Result.Standard.setAsIdentityConversion();
5307 Result.Standard.setFromType(ToType);
5308 Result.Standard.setAllToTypes(ToType);
5309 }
5310 return Result;
5311 }
5312
5313 // C++14 [over.ics.list]p8:
5314 // C++11 [over.ics.list]p7:
5315 // In all cases other than those enumerated above, no conversion is possible
5316 return Result;
5317}
5318
5319/// TryCopyInitialization - Try to copy-initialize a value of type
5320/// ToType from the expression From. Return the implicit conversion
5321/// sequence required to pass this argument, which may be a bad
5322/// conversion sequence (meaning that the argument cannot be passed to
5323/// a parameter of this type). If @p SuppressUserConversions, then we
5324/// do not permit any user-defined conversion sequences.
5325static ImplicitConversionSequence
5326TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5327 bool SuppressUserConversions,
5328 bool InOverloadResolution,
5329 bool AllowObjCWritebackConversion,
5330 bool AllowExplicit) {
5331 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5332 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5333 InOverloadResolution,AllowObjCWritebackConversion);
5334
5335 if (ToType->isReferenceType())
5336 return TryReferenceInit(S, From, ToType,
5337 /*FIXME:*/ From->getBeginLoc(),
5338 SuppressUserConversions, AllowExplicit);
5339
5340 return TryImplicitConversion(S, From, ToType,
5341 SuppressUserConversions,
5342 AllowedExplicit::None,
5343 InOverloadResolution,
5344 /*CStyle=*/false,
5345 AllowObjCWritebackConversion,
5346 /*AllowObjCConversionOnExplicit=*/false);
5347}
5348
5349static bool TryCopyInitialization(const CanQualType FromQTy,
5350 const CanQualType ToQTy,
5351 Sema &S,
5352 SourceLocation Loc,
5353 ExprValueKind FromVK) {
5354 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5355 ImplicitConversionSequence ICS =
5356 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5357
5358 return !ICS.isBad();
5359}
5360
5361/// TryObjectArgumentInitialization - Try to initialize the object
5362/// parameter of the given member function (@c Method) from the
5363/// expression @p From.
5364static ImplicitConversionSequence
5365TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5366 Expr::Classification FromClassification,
5367 CXXMethodDecl *Method,
5368 CXXRecordDecl *ActingContext) {
5369 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5370 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5371 // const volatile object.
5372 Qualifiers Quals = Method->getMethodQualifiers();
5373 if (isa<CXXDestructorDecl>(Method)) {
5374 Quals.addConst();
5375 Quals.addVolatile();
5376 }
5377
5378 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5379
5380 // Set up the conversion sequence as a "bad" conversion, to allow us
5381 // to exit early.
5382 ImplicitConversionSequence ICS;
5383
5384 // We need to have an object of class type.
5385 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5386 FromType = PT->getPointeeType();
5387
5388 // When we had a pointer, it's implicitly dereferenced, so we
5389 // better have an lvalue.
5390 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "clang/lib/Sema/SemaOverload.cpp"
, 5390, __extension__ __PRETTY_FUNCTION__))
;
5391 }
5392
5393 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "clang/lib/Sema/SemaOverload.cpp"
, 5393, __extension__ __PRETTY_FUNCTION__))
;
5394
5395 // C++0x [over.match.funcs]p4:
5396 // For non-static member functions, the type of the implicit object
5397 // parameter is
5398 //
5399 // - "lvalue reference to cv X" for functions declared without a
5400 // ref-qualifier or with the & ref-qualifier
5401 // - "rvalue reference to cv X" for functions declared with the &&
5402 // ref-qualifier
5403 //
5404 // where X is the class of which the function is a member and cv is the
5405 // cv-qualification on the member function declaration.
5406 //
5407 // However, when finding an implicit conversion sequence for the argument, we
5408 // are not allowed to perform user-defined conversions
5409 // (C++ [over.match.funcs]p5). We perform a simplified version of
5410 // reference binding here, that allows class rvalues to bind to
5411 // non-constant references.
5412
5413 // First check the qualifiers.
5414 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5415 if (ImplicitParamType.getCVRQualifiers()
5416 != FromTypeCanon.getLocalCVRQualifiers() &&
5417 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5418 ICS.setBad(BadConversionSequence::bad_qualifiers,
5419 FromType, ImplicitParamType);
5420 return ICS;
5421 }
5422
5423 if (FromTypeCanon.hasAddressSpace()) {
5424 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5425 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5426 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5427 ICS.setBad(BadConversionSequence::bad_qualifiers,
5428 FromType, ImplicitParamType);
5429 return ICS;
5430 }
5431 }
5432
5433 // Check that we have either the same type or a derived type. It
5434 // affects the conversion rank.
5435 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5436 ImplicitConversionKind SecondKind;
5437 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5438 SecondKind = ICK_Identity;
5439 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5440 SecondKind = ICK_Derived_To_Base;
5441 else {
5442 ICS.setBad(BadConversionSequence::unrelated_class,
5443 FromType, ImplicitParamType);
5444 return ICS;
5445 }
5446
5447 // Check the ref-qualifier.
5448 switch (Method->getRefQualifier()) {
5449 case RQ_None:
5450 // Do nothing; we don't care about lvalueness or rvalueness.
5451 break;
5452
5453 case RQ_LValue:
5454 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5455 // non-const lvalue reference cannot bind to an rvalue
5456 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5457 ImplicitParamType);
5458 return ICS;
5459 }
5460 break;
5461
5462 case RQ_RValue:
5463 if (!FromClassification.isRValue()) {
5464 // rvalue reference cannot bind to an lvalue
5465 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5466 ImplicitParamType);
5467 return ICS;
5468 }
5469 break;
5470 }
5471
5472 // Success. Mark this as a reference binding.
5473 ICS.setStandard();
5474 ICS.Standard.setAsIdentityConversion();
5475 ICS.Standard.Second = SecondKind;
5476 ICS.Standard.setFromType(FromType);
5477 ICS.Standard.setAllToTypes(ImplicitParamType);
5478 ICS.Standard.ReferenceBinding = true;
5479 ICS.Standard.DirectBinding = true;
5480 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5481 ICS.Standard.BindsToFunctionLvalue = false;
5482 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5483 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5484 = (Method->getRefQualifier() == RQ_None);
5485 return ICS;
5486}
5487
5488/// PerformObjectArgumentInitialization - Perform initialization of
5489/// the implicit object parameter for the given Method with the given
5490/// expression.
5491ExprResult
5492Sema::PerformObjectArgumentInitialization(Expr *From,
5493 NestedNameSpecifier *Qualifier,
5494 NamedDecl *FoundDecl,
5495 CXXMethodDecl *Method) {
5496 QualType FromRecordType, DestType;
5497 QualType ImplicitParamRecordType =
5498 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5499
5500 Expr::Classification FromClassification;
5501 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5502 FromRecordType = PT->getPointeeType();
5503 DestType = Method->getThisType();
5504 FromClassification = Expr::Classification::makeSimpleLValue();
5505 } else {
5506 FromRecordType = From->getType();
5507 DestType = ImplicitParamRecordType;
5508 FromClassification = From->Classify(Context);
5509
5510 // When performing member access on a prvalue, materialize a temporary.
5511 if (From->isPRValue()) {
5512 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5513 Method->getRefQualifier() !=
5514 RefQualifierKind::RQ_RValue);
5515 }
5516 }
5517
5518 // Note that we always use the true parent context when performing
5519 // the actual argument initialization.
5520 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5521 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5522 Method->getParent());
5523 if (ICS.isBad()) {
5524 switch (ICS.Bad.Kind) {
5525 case BadConversionSequence::bad_qualifiers: {
5526 Qualifiers FromQs = FromRecordType.getQualifiers();
5527 Qualifiers ToQs = DestType.getQualifiers();
5528 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5529 if (CVR) {
5530 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5531 << Method->getDeclName() << FromRecordType << (CVR - 1)
5532 << From->getSourceRange();
5533 Diag(Method->getLocation(), diag::note_previous_decl)
5534 << Method->getDeclName();
5535 return ExprError();
5536 }
5537 break;
5538 }
5539
5540 case BadConversionSequence::lvalue_ref_to_rvalue:
5541 case BadConversionSequence::rvalue_ref_to_lvalue: {
5542 bool IsRValueQualified =
5543 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5544 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5545 << Method->getDeclName() << FromClassification.isRValue()
5546 << IsRValueQualified;
5547 Diag(Method->getLocation(), diag::note_previous_decl)
5548 << Method->getDeclName();
5549 return ExprError();
5550 }
5551
5552 case BadConversionSequence::no_conversion:
5553 case BadConversionSequence::unrelated_class:
5554 break;
5555
5556 case BadConversionSequence::too_few_initializers:
5557 case BadConversionSequence::too_many_initializers:
5558 llvm_unreachable("Lists are not objects")::llvm::llvm_unreachable_internal("Lists are not objects", "clang/lib/Sema/SemaOverload.cpp"
, 5558)
;
5559 }
5560
5561 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5562 << ImplicitParamRecordType << FromRecordType
5563 << From->getSourceRange();
5564 }
5565
5566 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5567 ExprResult FromRes =
5568 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5569 if (FromRes.isInvalid())
5570 return ExprError();
5571 From = FromRes.get();
5572 }
5573
5574 if (!Context.hasSameType(From->getType(), DestType)) {
5575 CastKind CK;
5576 QualType PteeTy = DestType->getPointeeType();
5577 LangAS DestAS =
5578 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5579 if (FromRecordType.getAddressSpace() != DestAS)
5580 CK = CK_AddressSpaceConversion;
5581 else
5582 CK = CK_NoOp;
5583 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5584 }
5585 return From;
5586}
5587
5588/// TryContextuallyConvertToBool - Attempt to contextually convert the
5589/// expression From to bool (C++0x [conv]p3).
5590static ImplicitConversionSequence
5591TryContextuallyConvertToBool(Sema &S, Expr *From) {
5592 // C++ [dcl.init]/17.8:
5593 // - Otherwise, if the initialization is direct-initialization, the source
5594 // type is std::nullptr_t, and the destination type is bool, the initial
5595 // value of the object being initialized is false.
5596 if (From->getType()->isNullPtrType())
5597 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5598 S.Context.BoolTy,
5599 From->isGLValue());
5600
5601 // All other direct-initialization of bool is equivalent to an implicit
5602 // conversion to bool in which explicit conversions are permitted.
5603 return TryImplicitConversion(S, From, S.Context.BoolTy,
5604 /*SuppressUserConversions=*/false,
5605 AllowedExplicit::Conversions,
5606 /*InOverloadResolution=*/false,
5607 /*CStyle=*/false,
5608 /*AllowObjCWritebackConversion=*/false,
5609 /*AllowObjCConversionOnExplicit=*/false);
5610}
5611
5612/// PerformContextuallyConvertToBool - Perform a contextual conversion
5613/// of the expression From to bool (C++0x [conv]p3).
5614ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5615 if (checkPlaceholderForOverload(*this, From))
5616 return ExprError();
5617
5618 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5619 if (!ICS.isBad())
5620 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5621
5622 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5623 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5624 << From->getType() << From->getSourceRange();
5625 return ExprError();
5626}
5627
5628/// Check that the specified conversion is permitted in a converted constant
5629/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5630/// is acceptable.
5631static bool CheckConvertedConstantConversions(Sema &S,
5632 StandardConversionSequence &SCS) {
5633 // Since we know that the target type is an integral or unscoped enumeration
5634 // type, most conversion kinds are impossible. All possible First and Third
5635 // conversions are fine.
5636 switch (SCS.Second) {
5637 case ICK_Identity:
5638 case ICK_Integral_Promotion:
5639 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5640 case ICK_Zero_Queue_Conversion:
5641 return true;
5642
5643 case ICK_Boolean_Conversion:
5644 // Conversion from an integral or unscoped enumeration type to bool is
5645 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5646 // conversion, so we allow it in a converted constant expression.
5647 //
5648 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5649 // a lot of popular code. We should at least add a warning for this
5650 // (non-conforming) extension.
5651 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5652 SCS.getToType(2)->isBooleanType();
5653
5654 case ICK_Pointer_Conversion:
5655 case ICK_Pointer_Member:
5656 // C++1z: null pointer conversions and null member pointer conversions are
5657 // only permitted if the source type is std::nullptr_t.
5658 return SCS.getFromType()->isNullPtrType();
5659
5660 case ICK_Floating_Promotion:
5661 case ICK_Complex_Promotion:
5662 case ICK_Floating_Conversion:
5663 case ICK_Complex_Conversion:
5664 case ICK_Floating_Integral:
5665 case ICK_Compatible_Conversion:
5666 case ICK_Derived_To_Base:
5667 case ICK_Vector_Conversion:
5668 case ICK_SVE_Vector_Conversion:
5669 case ICK_Vector_Splat:
5670 case ICK_Complex_Real:
5671 case ICK_Block_Pointer_Conversion:
5672 case ICK_TransparentUnionConversion:
5673 case ICK_Writeback_Conversion:
5674 case ICK_Zero_Event_Conversion:
5675 case ICK_C_Only_Conversion:
5676 case ICK_Incompatible_Pointer_Conversion:
5677 return false;
5678
5679 case ICK_Lvalue_To_Rvalue:
5680 case ICK_Array_To_Pointer:
5681 case ICK_Function_To_Pointer:
5682 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5682)
;
5683
5684 case ICK_Function_Conversion:
5685 case ICK_Qualification:
5686 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5686)
;
5687
5688 case ICK_Num_Conversion_Kinds:
5689 break;
5690 }
5691
5692 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "clang/lib/Sema/SemaOverload.cpp"
, 5692)
;
5693}
5694
5695/// CheckConvertedConstantExpression - Check that the expression From is a
5696/// converted constant expression of type T, perform the conversion and produce
5697/// the converted expression, per C++11 [expr.const]p3.
5698static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5699 QualType T, APValue &Value,
5700 Sema::CCEKind CCE,
5701 bool RequireInt,
5702 NamedDecl *Dest) {
5703 assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5704, __extension__ __PRETTY_FUNCTION__
))
5704 "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5704, __extension__ __PRETTY_FUNCTION__
))
;
5705
5706 if (checkPlaceholderForOverload(S, From))
5707 return ExprError();
5708
5709 // C++1z [expr.const]p3:
5710 // A converted constant expression of type T is an expression,
5711 // implicitly converted to type T, where the converted
5712 // expression is a constant expression and the implicit conversion
5713 // sequence contains only [... list of conversions ...].
5714 ImplicitConversionSequence ICS =
5715 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5716 ? TryContextuallyConvertToBool(S, From)
5717 : TryCopyInitialization(S, From, T,
5718 /*SuppressUserConversions=*/false,
5719 /*InOverloadResolution=*/false,
5720 /*AllowObjCWritebackConversion=*/false,
5721 /*AllowExplicit=*/false);
5722 StandardConversionSequence *SCS = nullptr;
5723 switch (ICS.getKind()) {
5724 case ImplicitConversionSequence::StandardConversion:
5725 SCS = &ICS.Standard;
5726 break;
5727 case ImplicitConversionSequence::UserDefinedConversion:
5728 if (T->isRecordType())
5729 SCS = &ICS.UserDefined.Before;
5730 else
5731 SCS = &ICS.UserDefined.After;
5732 break;
5733 case ImplicitConversionSequence::AmbiguousConversion:
5734 case ImplicitConversionSequence::BadConversion:
5735 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5736 return S.Diag(From->getBeginLoc(),
5737 diag::err_typecheck_converted_constant_expression)
5738 << From->getType() << From->getSourceRange() << T;
5739 return ExprError();
5740
5741 case ImplicitConversionSequence::EllipsisConversion:
5742 case ImplicitConversionSequence::StaticObjectArgumentConversion:
5743 llvm_unreachable("bad conversion in converted constant expression")::llvm::llvm_unreachable_internal("bad conversion in converted constant expression"
, "clang/lib/Sema/SemaOverload.cpp", 5743)
;
5744 }
5745
5746 // Check that we would only use permitted conversions.
5747 if (!CheckConvertedConstantConversions(S, *SCS)) {
5748 return S.Diag(From->getBeginLoc(),
5749 diag::err_typecheck_converted_constant_expression_disallowed)
5750 << From->getType() << From->getSourceRange() << T;
5751 }
5752 // [...] and where the reference binding (if any) binds directly.
5753 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5754 return S.Diag(From->getBeginLoc(),
5755 diag::err_typecheck_converted_constant_expression_indirect)
5756 << From->getType() << From->getSourceRange() << T;
5757 }
5758
5759 // Usually we can simply apply the ImplicitConversionSequence we formed
5760 // earlier, but that's not guaranteed to work when initializing an object of
5761 // class type.
5762 ExprResult Result;
5763 if (T->isRecordType()) {
5764 assert(CCE == Sema::CCEK_TemplateArg &&(static_cast <bool> (CCE == Sema::CCEK_TemplateArg &&
"unexpected class type converted constant expr") ? void (0) :
__assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "clang/lib/Sema/SemaOverload.cpp", 5765, __extension__ __PRETTY_FUNCTION__
))
5765 "unexpected class type converted constant expr")(static_cast <bool> (CCE == Sema::CCEK_TemplateArg &&
"unexpected class type converted constant expr") ? void (0) :
__assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "clang/lib/Sema/SemaOverload.cpp", 5765, __extension__ __PRETTY_FUNCTION__
))
;
5766 Result = S.PerformCopyInitialization(
5767 InitializedEntity::InitializeTemplateParameter(
5768 T, cast<NonTypeTemplateParmDecl>(Dest)),
5769 SourceLocation(), From);
5770 } else {
5771 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5772 }
5773 if (Result.isInvalid())
5774 return Result;
5775
5776 // C++2a [intro.execution]p5:
5777 // A full-expression is [...] a constant-expression [...]
5778 Result =
5779 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5780 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5781 if (Result.isInvalid())
5782 return Result;
5783
5784 // Check for a narrowing implicit conversion.
5785 bool ReturnPreNarrowingValue = false;
5786 APValue PreNarrowingValue;
5787 QualType PreNarrowingType;
5788 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5789 PreNarrowingType)) {
5790 case NK_Dependent_Narrowing:
5791 // Implicit conversion to a narrower type, but the expression is
5792 // value-dependent so we can't tell whether it's actually narrowing.
5793 case NK_Variable_Narrowing:
5794 // Implicit conversion to a narrower type, and the value is not a constant
5795 // expression. We'll diagnose this in a moment.
5796 case NK_Not_Narrowing:
5797 break;
5798
5799 case NK_Constant_Narrowing:
5800 if (CCE == Sema::CCEK_ArrayBound &&
5801 PreNarrowingType->isIntegralOrEnumerationType() &&
5802 PreNarrowingValue.isInt()) {
5803 // Don't diagnose array bound narrowing here; we produce more precise
5804 // errors by allowing the un-narrowed value through.
5805 ReturnPreNarrowingValue = true;
5806 break;
5807 }
5808 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5809 << CCE << /*Constant*/ 1
5810 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5811 break;
5812
5813 case NK_Type_Narrowing:
5814 // FIXME: It would be better to diagnose that the expression is not a
5815 // constant expression.
5816 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5817 << CCE << /*Constant*/ 0 << From->getType() << T;
5818 break;
5819 }
5820
5821 if (Result.get()->isValueDependent()) {
5822 Value = APValue();
5823 return Result;
5824 }
5825
5826 // Check the expression is a constant expression.
5827 SmallVector<PartialDiagnosticAt, 8> Notes;
5828 Expr::EvalResult Eval;
5829 Eval.Diag = &Notes;
5830
5831 ConstantExprKind Kind;
5832 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5833 Kind = ConstantExprKind::ClassTemplateArgument;
5834 else if (CCE == Sema::CCEK_TemplateArg)
5835 Kind = ConstantExprKind::NonClassTemplateArgument;
5836 else
5837 Kind = ConstantExprKind::Normal;
5838
5839 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5840 (RequireInt && !Eval.Val.isInt())) {
5841 // The expression can't be folded, so we can't keep it at this position in
5842 // the AST.
5843 Result = ExprError();
5844 } else {
5845 Value = Eval.Val;
5846
5847 if (Notes.empty()) {
5848 // It's a constant expression.
5849 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5850 if (ReturnPreNarrowingValue)
5851 Value = std::move(PreNarrowingValue);
5852 return E;
5853 }
5854 }
5855
5856 // It's not a constant expression. Produce an appropriate diagnostic.
5857 if (Notes.size() == 1 &&
5858 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5859 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5860 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5861 diag::note_constexpr_invalid_template_arg) {
5862 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5863 for (unsigned I = 0; I < Notes.size(); ++I)
5864 S.Diag(Notes[I].first, Notes[I].second);
5865 } else {
5866 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5867 << CCE << From->getSourceRange();
5868 for (unsigned I = 0; I < Notes.size(); ++I)
5869 S.Diag(Notes[I].first, Notes[I].second);
5870 }
5871 return ExprError();
5872}
5873
5874ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5875 APValue &Value, CCEKind CCE,
5876 NamedDecl *Dest) {
5877 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5878 Dest);
5879}
5880
5881ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5882 llvm::APSInt &Value,
5883 CCEKind CCE) {
5884 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")(static_cast <bool> (T->isIntegralOrEnumerationType(
) && "unexpected converted const type") ? void (0) : __assert_fail
("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "clang/lib/Sema/SemaOverload.cpp", 5884, __extension__ __PRETTY_FUNCTION__
))
;
5885
5886 APValue V;
5887 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5888 /*Dest=*/nullptr);
5889 if (!R.isInvalid() && !R.get()->isValueDependent())
5890 Value = V.getInt();
5891 return R;
5892}
5893
5894
5895/// dropPointerConversions - If the given standard conversion sequence
5896/// involves any pointer conversions, remove them. This may change
5897/// the result type of the conversion sequence.
5898static void dropPointerConversion(StandardConversionSequence &SCS) {
5899 if (SCS.Second == ICK_Pointer_Conversion) {
5900 SCS.Second = ICK_Identity;
5901 SCS.Third = ICK_Identity;
5902 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5903 }
5904}
5905
5906/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5907/// convert the expression From to an Objective-C pointer type.
5908static ImplicitConversionSequence
5909TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5910 // Do an implicit conversion to 'id'.
5911 QualType Ty = S.Context.getObjCIdType();
5912 ImplicitConversionSequence ICS
5913 = TryImplicitConversion(S, From, Ty,
5914 // FIXME: Are these flags correct?
5915 /*SuppressUserConversions=*/false,
5916 AllowedExplicit::Conversions,
5917 /*InOverloadResolution=*/false,
5918 /*CStyle=*/false,
5919 /*AllowObjCWritebackConversion=*/false,
5920 /*AllowObjCConversionOnExplicit=*/true);
5921
5922 // Strip off any final conversions to 'id'.
5923 switch (ICS.getKind()) {
5924 case ImplicitConversionSequence::BadConversion:
5925 case ImplicitConversionSequence::AmbiguousConversion:
5926 case ImplicitConversionSequence::EllipsisConversion:
5927 case ImplicitConversionSequence::StaticObjectArgumentConversion:
5928 break;
5929
5930 case ImplicitConversionSequence::UserDefinedConversion:
5931 dropPointerConversion(ICS.UserDefined.After);
5932 break;
5933
5934 case ImplicitConversionSequence::StandardConversion:
5935 dropPointerConversion(ICS.Standard);
5936 break;
5937 }
5938
5939 return ICS;
5940}
5941
5942/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5943/// conversion of the expression From to an Objective-C pointer type.
5944/// Returns a valid but null ExprResult if no conversion sequence exists.
5945ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5946 if (checkPlaceholderForOverload(*this, From))
5947 return ExprError();
5948
5949 QualType Ty = Context.getObjCIdType();
5950 ImplicitConversionSequence ICS =
5951 TryContextuallyConvertToObjCPointer(*this, From);
5952 if (!ICS.isBad())
5953 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5954 return ExprResult();
5955}
5956
5957/// Determine whether the provided type is an integral type, or an enumeration
5958/// type of a permitted flavor.
5959bool Sema::ICEConvertDiagnoser::match(QualType T) {
5960 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5961 : T->isIntegralOrUnscopedEnumerationType();
5962}
5963
5964static ExprResult
5965diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5966 Sema::ContextualImplicitConverter &Converter,
5967 QualType T, UnresolvedSetImpl &ViableConversions) {
5968
5969 if (Converter.Suppress)
5970 return ExprError();
5971
5972 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5973 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5974 CXXConversionDecl *Conv =
5975 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5976 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5977 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5978 }
5979 return From;
5980}
5981
5982static bool
5983diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5984 Sema::ContextualImplicitConverter &Converter,
5985 QualType T, bool HadMultipleCandidates,
5986 UnresolvedSetImpl &ExplicitConversions) {
5987 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5988 DeclAccessPair Found = ExplicitConversions[0];
5989 CXXConversionDecl *Conversion =
5990 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5991
5992 // The user probably meant to invoke the given explicit
5993 // conversion; use it.
5994 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5995 std::string TypeStr;
5996 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5997
5998 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5999 << FixItHint::CreateInsertion(From->getBeginLoc(),
6000 "static_cast<" + TypeStr + ">(")
6001 << FixItHint::CreateInsertion(
6002 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6003 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6004
6005 // If we aren't in a SFINAE context, build a call to the
6006 // explicit conversion function.
6007 if (SemaRef.isSFINAEContext())
6008 return true;
6009
6010 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6011 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6012 HadMultipleCandidates);
6013 if (Result.isInvalid())
6014 return true;
6015 // Record usage of conversion in an implicit cast.
6016 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6017 CK_UserDefinedConversion, Result.get(),
6018 nullptr, Result.get()->getValueKind(),
6019 SemaRef.CurFPFeatureOverrides());
6020 }
6021 return false;
6022}
6023
6024static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6025 Sema::ContextualImplicitConverter &Converter,
6026 QualType T, bool HadMultipleCandidates,
6027 DeclAccessPair &Found) {
6028 CXXConversionDecl *Conversion =
6029 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6030 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6031
6032 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6033 if (!Converter.SuppressConversion) {
6034 if (SemaRef.isSFINAEContext())
6035 return true;
6036
6037 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6038 << From->getSourceRange();
6039 }
6040
6041 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6042 HadMultipleCandidates);
6043 if (Result.isInvalid())
6044 return true;
6045 // Record usage of conversion in an implicit cast.
6046 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6047 CK_UserDefinedConversion, Result.get(),
6048 nullptr, Result.get()->getValueKind(),
6049 SemaRef.CurFPFeatureOverrides());
6050 return false;
6051}
6052
6053static ExprResult finishContextualImplicitConversion(
6054 Sema &SemaRef, SourceLocation Loc, Expr *From,
6055 Sema::ContextualImplicitConverter &Converter) {
6056 if (!Converter.match(From->getType()) && !Converter.Suppress)
6057 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6058 << From->getSourceRange();
6059
6060 return SemaRef.DefaultLvalueConversion(From);
6061}
6062
6063static void
6064collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6065 UnresolvedSetImpl &ViableConversions,
6066 OverloadCandidateSet &CandidateSet) {
6067 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6068 DeclAccessPair FoundDecl = ViableConversions[I];
6069 NamedDecl *D = FoundDecl.getDecl();
6070 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6071 if (isa<UsingShadowDecl>(D))
6072 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6073
6074 CXXConversionDecl *Conv;
6075 FunctionTemplateDecl *ConvTemplate;
6076 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6077 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6078 else
6079 Conv = cast<CXXConversionDecl>(D);
6080
6081 if (ConvTemplate)
6082 SemaRef.AddTemplateConversionCandidate(
6083 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6084 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6085 else
6086 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6087 ToType, CandidateSet,
6088 /*AllowObjCConversionOnExplicit=*/false,
6089 /*AllowExplicit*/ true);
6090 }
6091}
6092
6093/// Attempt to convert the given expression to a type which is accepted
6094/// by the given converter.
6095///
6096/// This routine will attempt to convert an expression of class type to a
6097/// type accepted by the specified converter. In C++11 and before, the class
6098/// must have a single non-explicit conversion function converting to a matching
6099/// type. In C++1y, there can be multiple such conversion functions, but only
6100/// one target type.
6101///
6102/// \param Loc The source location of the construct that requires the
6103/// conversion.
6104///
6105/// \param From The expression we're converting from.
6106///
6107/// \param Converter Used to control and diagnose the conversion process.
6108///
6109/// \returns The expression, converted to an integral or enumeration type if
6110/// successful.
6111ExprResult Sema::PerformContextualImplicitConversion(
6112 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6113 // We can't perform any more checking for type-dependent expressions.
6114 if (From->isTypeDependent())
6115 return From;
6116
6117 // Process placeholders immediately.
6118 if (From->hasPlaceholderType()) {
6119 ExprResult result = CheckPlaceholderExpr(From);
6120 if (result.isInvalid())
6121 return result;
6122 From = result.get();
6123 }
6124
6125 // If the expression already has a matching type, we're golden.
6126 QualType T = From->getType();
6127 if (Converter.match(T))
6128 return DefaultLvalueConversion(From);
6129
6130 // FIXME: Check for missing '()' if T is a function type?
6131
6132 // We can only perform contextual implicit conversions on objects of class
6133 // type.
6134 const RecordType *RecordTy = T->getAs<RecordType>();
6135 if (!RecordTy || !getLangOpts().CPlusPlus) {
6136 if (!Converter.Suppress)
6137 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6138 return From;
6139 }
6140
6141 // We must have a complete class type.
6142 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6143 ContextualImplicitConverter &Converter;
6144 Expr *From;
6145
6146 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6147 : Converter(Converter), From(From) {}
6148
6149 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6150 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6151 }
6152 } IncompleteDiagnoser(Converter, From);
6153
6154 if (Converter.Suppress ? !isCompleteType(Loc, T)
6155 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6156 return From;
6157
6158 // Look for a conversion to an integral or enumeration type.
6159 UnresolvedSet<4>
6160 ViableConversions; // These are *potentially* viable in C++1y.
6161 UnresolvedSet<4> ExplicitConversions;
6162 const auto &Conversions =
6163 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6164
6165 bool HadMultipleCandidates =
6166 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6167
6168 // To check that there is only one target type, in C++1y:
6169 QualType ToType;
6170 bool HasUniqueTargetType = true;
6171
6172 // Collect explicit or viable (potentially in C++1y) conversions.
6173 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6174 NamedDecl *D = (*I)->getUnderlyingDecl();
6175 CXXConversionDecl *Conversion;
6176 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6177 if (ConvTemplate) {
6178 if (getLangOpts().CPlusPlus14)
6179 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6180 else
6181 continue; // C++11 does not consider conversion operator templates(?).
6182 } else
6183 Conversion = cast<CXXConversionDecl>(D);
6184
6185 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "clang/lib/Sema/SemaOverload.cpp", 6187, __extension__ __PRETTY_FUNCTION__
))
6186 "Conversion operator templates are considered potentially "(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "clang/lib/Sema/SemaOverload.cpp", 6187, __extension__ __PRETTY_FUNCTION__
))
6187 "viable in C++1y")(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "clang/lib/Sema/SemaOverload.cpp", 6187, __extension__ __PRETTY_FUNCTION__
))
;
6188
6189 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6190 if (Converter.match(CurToType) || ConvTemplate) {
6191
6192 if (Conversion->isExplicit()) {
6193 // FIXME: For C++1y, do we need this restriction?
6194 // cf. diagnoseNoViableConversion()
6195 if (!ConvTemplate)
6196 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6197 } else {
6198 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6199 if (ToType.isNull())
6200 ToType = CurToType.getUnqualifiedType();
6201 else if (HasUniqueTargetType &&
6202 (CurToType.getUnqualifiedType() != ToType))
6203 HasUniqueTargetType = false;
6204 }
6205 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6206 }
6207 }
6208 }
6209
6210 if (getLangOpts().CPlusPlus14) {
6211 // C++1y [conv]p6:
6212 // ... An expression e of class type E appearing in such a context
6213 // is said to be contextually implicitly converted to a specified
6214 // type T and is well-formed if and only if e can be implicitly
6215 // converted to a type T that is determined as follows: E is searched
6216 // for conversion functions whose return type is cv T or reference to
6217 // cv T such that T is allowed by the context. There shall be
6218 // exactly one such T.
6219
6220 // If no unique T is found:
6221 if (ToType.isNull()) {
6222 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6223 HadMultipleCandidates,
6224 ExplicitConversions))
6225 return ExprError();
6226 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6227 }
6228
6229 // If more than one unique Ts are found:
6230 if (!HasUniqueTargetType)
6231 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6232 ViableConversions);
6233
6234 // If one unique T is found:
6235 // First, build a candidate set from the previously recorded
6236 // potentially viable conversions.
6237 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6238 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6239 CandidateSet);
6240
6241 // Then, perform overload resolution over the candidate set.
6242 OverloadCandidateSet::iterator Best;
6243 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6244 case OR_Success: {
6245 // Apply this conversion.
6246 DeclAccessPair Found =
6247 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6248 if (recordConversion(*this, Loc, From, Converter, T,
6249 HadMultipleCandidates, Found))
6250 return ExprError();
6251 break;
6252 }
6253 case OR_Ambiguous:
6254 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6255 ViableConversions);
6256 case OR_No_Viable_Function:
6257 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6258 HadMultipleCandidates,
6259 ExplicitConversions))
6260 return ExprError();
6261 [[fallthrough]];
6262 case OR_Deleted:
6263 // We'll complain below about a non-integral condition type.
6264 break;
6265 }
6266 } else {
6267 switch (ViableConversions.size()) {
6268 case 0: {
6269 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6270 HadMultipleCandidates,
6271 ExplicitConversions))
6272 return ExprError();
6273
6274 // We'll complain below about a non-integral condition type.
6275 break;
6276 }
6277 case 1: {
6278 // Apply this conversion.
6279 DeclAccessPair Found = ViableConversions[0];
6280 if (recordConversion(*this, Loc, From, Converter, T,
6281 HadMultipleCandidates, Found))
6282 return ExprError();
6283 break;
6284 }
6285 default:
6286 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6287 ViableConversions);
6288 }
6289 }
6290
6291 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6292}
6293
6294/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6295/// an acceptable non-member overloaded operator for a call whose
6296/// arguments have types T1 (and, if non-empty, T2). This routine
6297/// implements the check in C++ [over.match.oper]p3b2 concerning
6298/// enumeration types.
6299static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6300 FunctionDecl *Fn,
6301 ArrayRef<Expr *> Args) {
6302 QualType T1 = Args[0]->getType();
6303 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6304
6305 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6306 return true;
6307
6308 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6309 return true;
6310
6311 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6312 if (Proto->getNumParams() < 1)
6313 return false;
6314
6315 if (T1->isEnumeralType()) {
6316 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6317 if (Context.hasSameUnqualifiedType(T1, ArgType))
6318 return true;
6319 }
6320
6321 if (Proto->getNumParams() < 2)
6322 return false;
6323
6324 if (!T2.isNull() && T2->isEnumeralType()) {
6325 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6326 if (Context.hasSameUnqualifiedType(T2, ArgType))
6327 return true;
6328 }
6329
6330 return false;
6331}
6332
6333/// AddOverloadCandidate - Adds the given function to the set of
6334/// candidate functions, using the given function call arguments. If
6335/// @p SuppressUserConversions, then don't allow user-defined
6336/// conversions via constructors or conversion operators.
6337///
6338/// \param PartialOverloading true if we are performing "partial" overloading
6339/// based on an incomplete set of function arguments. This feature is used by
6340/// code completion.
6341void Sema::AddOverloadCandidate(
6342 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6343 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6344 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6345 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6346 OverloadCandidateParamOrder PO) {
6347 const FunctionProtoType *Proto
6348 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6349 assert(Proto && "Functions without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Functions without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "clang/lib/Sema/SemaOverload.cpp", 6349, __extension__ __PRETTY_FUNCTION__
))
;
6350 assert(!Function->getDescribedFunctionTemplate() &&(static_cast <bool> (!Function->getDescribedFunctionTemplate
() && "Use AddTemplateOverloadCandidate for function templates"
) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "clang/lib/Sema/SemaOverload.cpp", 6351, __extension__ __PRETTY_FUNCTION__
))
6351 "Use AddTemplateOverloadCandidate for function templates")(static_cast <bool> (!Function->getDescribedFunctionTemplate
() && "Use AddTemplateOverloadCandidate for function templates"
) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "clang/lib/Sema/SemaOverload.cpp", 6351, __extension__ __PRETTY_FUNCTION__
))
;
6352
6353 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6354 if (!isa<CXXConstructorDecl>(Method)) {
6355 // If we get here, it's because we're calling a member function
6356 // that is named without a member access expression (e.g.,
6357 // "this->f") that was either written explicitly or created
6358 // implicitly. This can happen with a qualified call to a member
6359 // function, e.g., X::f(). We use an empty type for the implied
6360 // object argument (C++ [over.call.func]p3), and the acting context
6361 // is irrelevant.
6362 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6363 Expr::Classification::makeSimpleLValue(), Args,
6364 CandidateSet, SuppressUserConversions,
6365 PartialOverloading, EarlyConversions, PO);
6366 return;
6367 }
6368 // We treat a constructor like a non-member function, since its object
6369 // argument doesn't participate in overload resolution.
6370 }
6371
6372 if (!CandidateSet.isNewCandidate(Function, PO))
6373 return;
6374
6375 // C++11 [class.copy]p11: [DR1402]
6376 // A defaulted move constructor that is defined as deleted is ignored by
6377 // overload resolution.
6378 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6379 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6380 Constructor->isMoveConstructor())
6381 return;
6382
6383 // Overload resolution is always an unevaluated context.
6384 EnterExpressionEvaluationContext Unevaluated(
6385 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6386
6387 // C++ [over.match.oper]p3:
6388 // if no operand has a class type, only those non-member functions in the
6389 // lookup set that have a first parameter of type T1 or "reference to
6390 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6391 // is a right operand) a second parameter of type T2 or "reference to
6392 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6393 // candidate functions.
6394 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6395 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6396 return;
6397
6398 // Add this candidate
6399 OverloadCandidate &Candidate =
6400 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6401 Candidate.FoundDecl = FoundDecl;
6402 Candidate.Function = Function;
6403 Candidate.Viable = true;
6404 Candidate.RewriteKind =
6405 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6406 Candidate.IsSurrogate = false;
6407 Candidate.IsADLCandidate = IsADLCandidate;
6408 Candidate.IgnoreObjectArgument = false;
6409 Candidate.ExplicitCallArguments = Args.size();
6410
6411 // Explicit functions are not actually candidates at all if we're not
6412 // allowing them in this context, but keep them around so we can point
6413 // to them in diagnostics.
6414 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6415 Candidate.Viable = false;
6416 Candidate.FailureKind = ovl_fail_explicit;
6417 return;
6418 }
6419
6420 // Functions with internal linkage are only viable in the same module unit.
6421 if (auto *MF = Function->getOwningModule()) {
6422 if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() &&
6423 !isModuleUnitOfCurrentTU(MF)) {
6424 /// FIXME: Currently, the semantics of linkage in clang is slightly
6425 /// different from the semantics in C++ spec. In C++ spec, only names
6426 /// have linkage. So that all entities of the same should share one
6427 /// linkage. But in clang, different entities of the same could have
6428 /// different linkage.
6429 NamedDecl *ND = Function;
6430 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6431 ND = SpecInfo->getTemplate();
6432
6433 if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
6434 Candidate.Viable = false;
6435 Candidate.FailureKind = ovl_fail_module_mismatched;
6436 return;
6437 }
6438 }
6439 }
6440
6441 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6442 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6443 Candidate.Viable = false;
6444 Candidate.FailureKind = ovl_non_default_multiversion_function;
6445 return;
6446 }
6447
6448 if (Constructor) {
6449 // C++ [class.copy]p3:
6450 // A member function template is never instantiated to perform the copy
6451 // of a class object to an object of its class type.
6452 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6453 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6454 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6455 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6456 ClassType))) {
6457 Candidate.Viable = false;
6458 Candidate.FailureKind = ovl_fail_illegal_constructor;
6459 return;
6460 }
6461
6462 // C++ [over.match.funcs]p8: (proposed DR resolution)
6463 // A constructor inherited from class type C that has a first parameter
6464 // of type "reference to P" (including such a constructor instantiated
6465 // from a template) is excluded from the set of candidate functions when
6466 // constructing an object of type cv D if the argument list has exactly
6467 // one argument and D is reference-related to P and P is reference-related
6468 // to C.
6469 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6470 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6471 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6472 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6473 QualType C = Context.getRecordType(Constructor->getParent());
6474 QualType D = Context.getRecordType(Shadow->getParent());
6475 SourceLocation Loc = Args.front()->getExprLoc();
6476 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6477 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6478 Candidate.Viable = false;
6479 Candidate.FailureKind = ovl_fail_inhctor_slice;
6480 return;
6481 }
6482 }
6483
6484 // Check that the constructor is capable of constructing an object in the
6485 // destination address space.
6486 if (!Qualifiers::isAddressSpaceSupersetOf(
6487 Constructor->getMethodQualifiers().getAddressSpace(),
6488 CandidateSet.getDestAS())) {
6489 Candidate.Viable = false;
6490 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6491 }
6492 }
6493
6494 unsigned NumParams = Proto->getNumParams();
6495
6496 // (C++ 13.3.2p2): A candidate function having fewer than m
6497 // parameters is viable only if it has an ellipsis in its parameter
6498 // list (8.3.5).
6499 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6500 !Proto->isVariadic() &&
6501 shouldEnforceArgLimit(PartialOverloading, Function)) {
6502 Candidate.Viable = false;
6503 Candidate.FailureKind = ovl_fail_too_many_arguments;
6504 return;
6505 }
6506
6507 // (C++ 13.3.2p2): A candidate function having more than m parameters
6508 // is viable only if the (m+1)st parameter has a default argument
6509 // (8.3.6). For the purposes of overload resolution, the
6510 // parameter list is truncated on the right, so that there are
6511 // exactly m parameters.
6512 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6513 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6514 // Not enough arguments.
6515 Candidate.Viable = false;
6516 Candidate.FailureKind = ovl_fail_too_few_arguments;
6517 return;
6518 }
6519
6520 // (CUDA B.1): Check for invalid calls between targets.
6521 if (getLangOpts().CUDA)
6522 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6523 // Skip the check for callers that are implicit members, because in this
6524 // case we may not yet know what the member's target is; the target is
6525 // inferred for the member automatically, based on the bases and fields of
6526 // the class.
6527 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6528 Candidate.Viable = false;
6529 Candidate.FailureKind = ovl_fail_bad_target;
6530 return;
6531 }
6532
6533 if (Function->getTrailingRequiresClause()) {
6534 ConstraintSatisfaction Satisfaction;
6535 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
6536 /*ForOverloadResolution*/ true) ||
6537 !Satisfaction.IsSatisfied) {
6538 Candidate.Viable = false;
6539 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6540 return;
6541 }
6542 }
6543
6544 // Determine the implicit conversion sequences for each of the
6545 // arguments.
6546 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6547 unsigned ConvIdx =
6548 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6549 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6550 // We already formed a conversion sequence for this parameter during
6551 // template argument deduction.
6552 } else if (ArgIdx < NumParams) {
6553 // (C++ 13.3.2p3): for F to be a viable function, there shall
6554 // exist for each argument an implicit conversion sequence
6555 // (13.3.3.1) that converts that argument to the corresponding
6556 // parameter of F.
6557 QualType ParamType = Proto->getParamType(ArgIdx);
6558 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6559 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6560 /*InOverloadResolution=*/true,
6561 /*AllowObjCWritebackConversion=*/
6562 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6563 if (Candidate.Conversions[ConvIdx].isBad()) {
6564 Candidate.Viable = false;
6565 Candidate.FailureKind = ovl_fail_bad_conversion;
6566 return;
6567 }
6568 } else {
6569 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6570 // argument for which there is no corresponding parameter is
6571 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6572 Candidate.Conversions[ConvIdx].setEllipsis();
6573 }
6574 }
6575
6576 if (EnableIfAttr *FailedAttr =
6577 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6578 Candidate.Viable = false;
6579 Candidate.FailureKind = ovl_fail_enable_if;
6580 Candidate.DeductionFailure.Data = FailedAttr;
6581 return;
6582 }
6583}
6584
6585ObjCMethodDecl *
6586Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6587 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6588 if (Methods.size() <= 1)
6589 return nullptr;
6590
6591 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6592 bool Match = true;
6593 ObjCMethodDecl *Method = Methods[b];
6594 unsigned NumNamedArgs = Sel.getNumArgs();
6595 // Method might have more arguments than selector indicates. This is due
6596 // to addition of c-style arguments in method.
6597 if (Method->param_size() > NumNamedArgs)
6598 NumNamedArgs = Method->param_size();
6599 if (Args.size() < NumNamedArgs)
6600 continue;
6601
6602 for (unsigned i = 0; i < NumNamedArgs; i++) {
6603 // We can't do any type-checking on a type-dependent argument.
6604 if (Args[i]->isTypeDependent()) {
6605 Match = false;
6606 break;
6607 }
6608
6609 ParmVarDecl *param = Method->parameters()[i];
6610 Expr *argExpr = Args[i];
6611 assert(argExpr && "SelectBestMethod(): missing expression")(static_cast <bool> (argExpr && "SelectBestMethod(): missing expression"
) ? void (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "clang/lib/Sema/SemaOverload.cpp", 6611, __extension__ __PRETTY_FUNCTION__
))
;
6612
6613 // Strip the unbridged-cast placeholder expression off unless it's
6614 // a consumed argument.
6615 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6616 !param->hasAttr<CFConsumedAttr>())
6617 argExpr = stripARCUnbridgedCast(argExpr);
6618
6619 // If the parameter is __unknown_anytype, move on to the next method.
6620 if (param->getType() == Context.UnknownAnyTy) {
6621 Match = false;
6622 break;
6623 }
6624
6625 ImplicitConversionSequence ConversionState
6626 = TryCopyInitialization(*this, argExpr, param->getType(),
6627 /*SuppressUserConversions*/false,
6628 /*InOverloadResolution=*/true,
6629 /*AllowObjCWritebackConversion=*/
6630 getLangOpts().ObjCAutoRefCount,
6631 /*AllowExplicit*/false);
6632 // This function looks for a reasonably-exact match, so we consider
6633 // incompatible pointer conversions to be a failure here.
6634 if (ConversionState.isBad() ||
6635 (ConversionState.isStandard() &&
6636 ConversionState.Standard.Second ==
6637 ICK_Incompatible_Pointer_Conversion)) {
6638 Match = false;
6639 break;
6640 }
6641 }
6642 // Promote additional arguments to variadic methods.
6643 if (Match && Method->isVariadic()) {
6644 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6645 if (Args[i]->isTypeDependent()) {
6646 Match = false;
6647 break;
6648 }
6649 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6650 nullptr);
6651 if (Arg.isInvalid()) {
6652 Match = false;
6653 break;
6654 }
6655 }
6656 } else {
6657 // Check for extra arguments to non-variadic methods.
6658 if (Args.size() != NumNamedArgs)
6659 Match = false;
6660 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6661 // Special case when selectors have no argument. In this case, select
6662 // one with the most general result type of 'id'.
6663 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6664 QualType ReturnT = Methods[b]->getReturnType();
6665 if (ReturnT->isObjCIdType())
6666 return Methods[b];
6667 }
6668 }
6669 }
6670
6671 if (Match)
6672 return Method;
6673 }
6674 return nullptr;
6675}
6676
6677static bool convertArgsForAvailabilityChecks(
6678 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6679 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6680 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6681 if (ThisArg) {
6682 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6683 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "clang/lib/Sema/SemaOverload.cpp", 6684, __extension__ __PRETTY_FUNCTION__
))
6684 "Shouldn't have `this` for ctors!")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "clang/lib/Sema/SemaOverload.cpp", 6684, __extension__ __PRETTY_FUNCTION__
))
;
6685 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")(static_cast <bool> (!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? void (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "clang/lib/Sema/SemaOverload.cpp", 6685, __extension__ __PRETTY_FUNCTION__
))
;
6686 ExprResult R = S.PerformObjectArgumentInitialization(
6687 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6688 if (R.isInvalid())
6689 return false;
6690 ConvertedThis = R.get();
6691 } else {
6692 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6693 (void)MD;
6694 assert((MissingImplicitThis || MD->isStatic() ||(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "clang/lib/Sema/SemaOverload.cpp", 6696, __extension__ __PRETTY_FUNCTION__
))
6695 isa<CXXConstructorDecl>(MD)) &&(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "clang/lib/Sema/SemaOverload.cpp", 6696, __extension__ __PRETTY_FUNCTION__
))
6696 "Expected `this` for non-ctor instance methods")(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "clang/lib/Sema/SemaOverload.cpp", 6696, __extension__ __PRETTY_FUNCTION__
))
;
6697 }
6698 ConvertedThis = nullptr;
6699 }
6700
6701 // Ignore any variadic arguments. Converting them is pointless, since the
6702 // user can't refer to them in the function condition.
6703 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6704
6705 // Convert the arguments.
6706 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6707 ExprResult R;
6708 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6709 S.Context, Function->getParamDecl(I)),
6710 SourceLocation(), Args[I]);
6711
6712 if (R.isInvalid())
6713 return false;
6714
6715 ConvertedArgs.push_back(R.get());
6716 }
6717
6718 if (Trap.hasErrorOccurred())
6719 return false;
6720
6721 // Push default arguments if needed.
6722 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6723 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6724 ParmVarDecl *P = Function->getParamDecl(i);
6725 if (!P->hasDefaultArg())
6726 return false;
6727 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6728 if (R.isInvalid())
6729 return false;
6730 ConvertedArgs.push_back(R.get());
6731 }
6732
6733 if (Trap.hasErrorOccurred())
6734 return false;
6735 }
6736 return true;
6737}
6738
6739EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6740 SourceLocation CallLoc,
6741 ArrayRef<Expr *> Args,
6742 bool MissingImplicitThis) {
6743 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6744 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6745 return nullptr;
6746
6747 SFINAETrap Trap(*this);
6748 SmallVector<Expr *, 16> ConvertedArgs;
6749 // FIXME: We should look into making enable_if late-parsed.
6750 Expr *DiscardedThis;
6751 if (!convertArgsForAvailabilityChecks(
6752 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6753 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6754 return *EnableIfAttrs.begin();
6755
6756 for (auto *EIA : EnableIfAttrs) {
6757 APValue Result;
6758 // FIXME: This doesn't consider value-dependent cases, because doing so is
6759 // very difficult. Ideally, we should handle them more gracefully.
6760 if (EIA->getCond()->isValueDependent() ||
6761 !EIA->getCond()->EvaluateWithSubstitution(
6762 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6763 return EIA;
6764
6765 if (!Result.isInt() || !Result.getInt().getBoolValue())
6766 return EIA;
6767 }
6768 return nullptr;
6769}
6770
6771template <typename CheckFn>
6772static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6773 bool ArgDependent, SourceLocation Loc,
6774 CheckFn &&IsSuccessful) {
6775 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6776 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6777 if (ArgDependent == DIA->getArgDependent())
6778 Attrs.push_back(DIA);
6779 }
6780
6781 // Common case: No diagnose_if attributes, so we can quit early.
6782 if (Attrs.empty())
6783 return false;
6784
6785 auto WarningBegin = std::stable_partition(
6786 Attrs.begin(), Attrs.end(),
6787 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6788
6789 // Note that diagnose_if attributes are late-parsed, so they appear in the
6790 // correct order (unlike enable_if attributes).
6791 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6792 IsSuccessful);
6793 if (ErrAttr != WarningBegin) {
6794 const DiagnoseIfAttr *DIA = *ErrAttr;
6795 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6796 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6797 << DIA->getParent() << DIA->getCond()->getSourceRange();
6798 return true;
6799 }
6800
6801 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6802 if (IsSuccessful(DIA)) {
6803 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6804 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6805 << DIA->getParent() << DIA->getCond()->getSourceRange();
6806 }
6807
6808 return false;
6809}
6810
6811bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6812 const Expr *ThisArg,
6813 ArrayRef<const Expr *> Args,
6814 SourceLocation Loc) {
6815 return diagnoseDiagnoseIfAttrsWith(
6816 *this, Function, /*ArgDependent=*/true, Loc,
6817 [&](const DiagnoseIfAttr *DIA) {
6818 APValue Result;
6819 // It's sane to use the same Args for any redecl of this function, since
6820 // EvaluateWithSubstitution only cares about the position of each
6821 // argument in the arg list, not the ParmVarDecl* it maps to.
6822 if (!DIA->getCond()->EvaluateWithSubstitution(
6823 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6824 return false;
6825 return Result.isInt() && Result.getInt().getBoolValue();
6826 });
6827}
6828
6829bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6830 SourceLocation Loc) {
6831 return diagnoseDiagnoseIfAttrsWith(
6832 *this, ND, /*ArgDependent=*/false, Loc,
6833 [&](const DiagnoseIfAttr *DIA) {
6834 bool Result;
6835 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6836 Result;
6837 });
6838}
6839
6840/// Add all of the function declarations in the given function set to
6841/// the overload candidate set.
6842void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6843 ArrayRef<Expr *> Args,
6844 OverloadCandidateSet &CandidateSet,
6845 TemplateArgumentListInfo *ExplicitTemplateArgs,
6846 bool SuppressUserConversions,
6847 bool PartialOverloading,
6848 bool FirstArgumentIsBase) {
6849 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6850 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6851 ArrayRef<Expr *> FunctionArgs = Args;
6852
6853 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6854 FunctionDecl *FD =
6855 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6856
6857 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6858 QualType ObjectType;
6859 Expr::Classification ObjectClassification;
6860 if (Args.size() > 0) {
6861 if (Expr *E = Args[0]) {
6862 // Use the explicit base to restrict the lookup:
6863 ObjectType = E->getType();
6864 // Pointers in the object arguments are implicitly dereferenced, so we
6865 // always classify them as l-values.
6866 if (!ObjectType.isNull() && ObjectType->isPointerType())
6867 ObjectClassification = Expr::Classification::makeSimpleLValue();
6868 else
6869 ObjectClassification = E->Classify(Context);
6870 } // .. else there is an implicit base.
6871 FunctionArgs = Args.slice(1);
6872 }
6873 if (FunTmpl) {
6874 AddMethodTemplateCandidate(
6875 FunTmpl, F.getPair(),
6876 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6877 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6878 FunctionArgs, CandidateSet, SuppressUserConversions,
6879 PartialOverloading);
6880 } else {
6881 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6882 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6883 ObjectClassification, FunctionArgs, CandidateSet,
6884 SuppressUserConversions, PartialOverloading);
6885 }
6886 } else {
6887 // This branch handles both standalone functions and static methods.
6888
6889 // Slice the first argument (which is the base) when we access
6890 // static method as non-static.
6891 if (Args.size() > 0 &&
6892 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6893 !isa<CXXConstructorDecl>(FD)))) {
6894 assert(cast<CXXMethodDecl>(FD)->isStatic())(static_cast <bool> (cast<CXXMethodDecl>(FD)->
isStatic()) ? void (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "clang/lib/Sema/SemaOverload.cpp", 6894, __extension__ __PRETTY_FUNCTION__
))
;
6895 FunctionArgs = Args.slice(1);
6896 }
6897 if (FunTmpl) {
6898 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6899 ExplicitTemplateArgs, FunctionArgs,
6900 CandidateSet, SuppressUserConversions,
6901 PartialOverloading);
6902 } else {
6903 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6904 SuppressUserConversions, PartialOverloading);
6905 }
6906 }
6907 }
6908}
6909
6910/// AddMethodCandidate - Adds a named decl (which is some kind of
6911/// method) as a method candidate to the given overload set.
6912void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6913 Expr::Classification ObjectClassification,
6914 ArrayRef<Expr *> Args,
6915 OverloadCandidateSet &CandidateSet,
6916 bool SuppressUserConversions,
6917 OverloadCandidateParamOrder PO) {
6918 NamedDecl *Decl = FoundDecl.getDecl();
6919 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6920
6921 if (isa<UsingShadowDecl>(Decl))
6922 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6923
6924 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6925 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "clang/lib/Sema/SemaOverload.cpp", 6926, __extension__ __PRETTY_FUNCTION__
))
6926 "Expected a member function template")(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "clang/lib/Sema/SemaOverload.cpp", 6926, __extension__ __PRETTY_FUNCTION__
))
;
6927 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6928 /*ExplicitArgs*/ nullptr, ObjectType,
6929 ObjectClassification, Args, CandidateSet,
6930 SuppressUserConversions, false, PO);
6931 } else {
6932 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6933 ObjectType, ObjectClassification, Args, CandidateSet,
6934 SuppressUserConversions, false, None, PO);
6935 }
6936}
6937
6938/// AddMethodCandidate - Adds the given C++ member function to the set
6939/// of candidate functions, using the given function call arguments
6940/// and the object argument (@c Object). For example, in a call
6941/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6942/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6943/// allow user-defined conversions via constructors or conversion
6944/// operators.
6945void
6946Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6947 CXXRecordDecl *ActingContext, QualType ObjectType,
6948 Expr::Classification ObjectClassification,
6949 ArrayRef<Expr *> Args,
6950 OverloadCandidateSet &CandidateSet,
6951 bool SuppressUserConversions,
6952 bool PartialOverloading,
6953 ConversionSequenceList EarlyConversions,
6954 OverloadCandidateParamOrder PO) {
6955 const FunctionProtoType *Proto
6956 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6957 assert(Proto && "Methods without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Methods without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "clang/lib/Sema/SemaOverload.cpp", 6957, __extension__ __PRETTY_FUNCTION__
))
;
6958 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "clang/lib/Sema/SemaOverload.cpp", 6959, __extension__ __PRETTY_FUNCTION__
))
6959 "Use AddOverloadCandidate for constructors")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "clang/lib/Sema/SemaOverload.cpp", 6959, __extension__ __PRETTY_FUNCTION__
))
;
6960
6961 if (!CandidateSet.isNewCandidate(Method, PO))
6962 return;
6963
6964 // C++11 [class.copy]p23: [DR1402]
6965 // A defaulted move assignment operator that is defined as deleted is
6966 // ignored by overload resolution.
6967 if (Method->isDefaulted() && Method->isDeleted() &&
6968 Method->isMoveAssignmentOperator())
6969 return;
6970
6971 // Overload resolution is always an unevaluated context.
6972 EnterExpressionEvaluationContext Unevaluated(
6973 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6974
6975 // Add this candidate
6976 OverloadCandidate &Candidate =
6977 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6978 Candidate.FoundDecl = FoundDecl;
6979 Candidate.Function = Method;
6980 Candidate.RewriteKind =
6981 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6982 Candidate.IsSurrogate = false;
6983 Candidate.IgnoreObjectArgument = false;
6984 Candidate.ExplicitCallArguments = Args.size();
6985
6986 unsigned NumParams = Proto->getNumParams();
6987
6988 // (C++ 13.3.2p2): A candidate function having fewer than m
6989 // parameters is viable only if it has an ellipsis in its parameter
6990 // list (8.3.5).
6991 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6992 !Proto->isVariadic() &&
6993 shouldEnforceArgLimit(PartialOverloading, Method)) {
6994 Candidate.Viable = false;
6995 Candidate.FailureKind = ovl_fail_too_many_arguments;
6996 return;
6997 }
6998
6999 // (C++ 13.3.2p2): A candidate function having more than m parameters
7000 // is viable only if the (m+1)st parameter has a default argument
7001 // (8.3.6). For the purposes of overload resolution, the
7002 // parameter list is truncated on the right, so that there are
7003 // exactly m parameters.
7004 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
7005 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7006 // Not enough arguments.
7007 Candidate.Viable = false;
7008 Candidate.FailureKind = ovl_fail_too_few_arguments;
7009 return;
7010 }
7011
7012 Candidate.Viable = true;
7013
7014 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7015 if (ObjectType.isNull())
7016 Candidate.IgnoreObjectArgument = true;
7017 else if (Method->isStatic()) {
7018 // [over.best.ics.general]p8
7019 // When the parameter is the implicit object parameter of a static member
7020 // function, the implicit conversion sequence is a standard conversion
7021 // sequence that is neither better nor worse than any other standard
7022 // conversion sequence.
7023 //
7024 // This is a rule that was introduced in C++23 to support static lambdas. We
7025 // apply it retroactively because we want to support static lambdas as an
7026 // extension and it doesn't hurt previous code.
7027 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7028 } else {
7029 // Determine the implicit conversion sequence for the object
7030 // parameter.
7031 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7032 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7033 Method, ActingContext);
7034 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7035 Candidate.Viable = false;
7036 Candidate.FailureKind = ovl_fail_bad_conversion;
7037 return;
7038 }
7039 }
7040
7041 // (CUDA B.1): Check for invalid calls between targets.
7042 if (getLangOpts().CUDA)
7043 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
7044 if (!IsAllowedCUDACall(Caller, Method)) {
7045 Candidate.Viable = false;
7046 Candidate.FailureKind = ovl_fail_bad_target;
7047 return;
7048 }
7049
7050 if (Method->getTrailingRequiresClause()) {
7051 ConstraintSatisfaction Satisfaction;
7052 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7053 /*ForOverloadResolution*/ true) ||
7054 !Satisfaction.IsSatisfied) {
7055 Candidate.Viable = false;
7056 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7057 return;
7058 }
7059 }
7060
7061 // Determine the implicit conversion sequences for each of the
7062 // arguments.
7063 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7064 unsigned ConvIdx =
7065 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7066 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7067 // We already formed a conversion sequence for this parameter during
7068 // template argument deduction.
7069 } else if (ArgIdx < NumParams) {
7070 // (C++ 13.3.2p3): for F to be a viable function, there shall
7071 // exist for each argument an implicit conversion sequence
7072 // (13.3.3.1) that converts that argument to the corresponding
7073 // parameter of F.
7074 QualType ParamType = Proto->getParamType(ArgIdx);
7075 Candidate.Conversions[ConvIdx]
7076 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7077 SuppressUserConversions,
7078 /*InOverloadResolution=*/true,
7079 /*AllowObjCWritebackConversion=*/
7080 getLangOpts().ObjCAutoRefCount);
7081 if (Candidate.Conversions[ConvIdx].isBad()) {
7082 Candidate.Viable = false;
7083 Candidate.FailureKind = ovl_fail_bad_conversion;
7084 return;
7085 }
7086 } else {
7087 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7088 // argument for which there is no corresponding parameter is
7089 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7090 Candidate.Conversions[ConvIdx].setEllipsis();
7091 }
7092 }
7093
7094 if (EnableIfAttr *FailedAttr =
7095 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7096 Candidate.Viable = false;
7097 Candidate.FailureKind = ovl_fail_enable_if;
7098 Candidate.DeductionFailure.Data = FailedAttr;
7099 return;
7100 }
7101
7102 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7103 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7104 Candidate.Viable = false;
7105 Candidate.FailureKind = ovl_non_default_multiversion_function;
7106 }
7107}
7108
7109/// Add a C++ member function template as a candidate to the candidate
7110/// set, using template argument deduction to produce an appropriate member
7111/// function template specialization.
7112void Sema::AddMethodTemplateCandidate(
7113 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7114 CXXRecordDecl *ActingContext,
7115 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7116 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7117 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7118 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7119 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7120 return;
7121
7122 // C++ [over.match.funcs]p7:
7123 // In each case where a candidate is a function template, candidate
7124 // function template specializations are generated using template argument
7125 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7126 // candidate functions in the usual way.113) A given name can refer to one
7127 // or more function templates and also to a set of overloaded non-template
7128 // functions. In such a case, the candidate functions generated from each
7129 // function template are combined with the set of non-template candidate
7130 // functions.
7131 TemplateDeductionInfo Info(CandidateSet.getLocation());
7132 FunctionDecl *Specialization = nullptr;
7133 ConversionSequenceList Conversions;
7134 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7135 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7136 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7137 return CheckNonDependentConversions(
7138 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7139 SuppressUserConversions, ActingContext, ObjectType,
7140 ObjectClassification, PO);
7141 })) {
7142 OverloadCandidate &Candidate =
7143 CandidateSet.addCandidate(Conversions.size(), Conversions);
7144 Candidate.FoundDecl = FoundDecl;
7145 Candidate.Function = MethodTmpl->getTemplatedDecl();
7146 Candidate.Viable = false;
7147 Candidate.RewriteKind =
7148 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7149 Candidate.IsSurrogate = false;
7150 Candidate.IgnoreObjectArgument =
7151 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7152 ObjectType.isNull();
7153 Candidate.ExplicitCallArguments = Args.size();
7154 if (Result == TDK_NonDependentConversionFailure)
7155 Candidate.FailureKind = ovl_fail_bad_conversion;
7156 else {
7157 Candidate.FailureKind = ovl_fail_bad_deduction;
7158 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7159 Info);
7160 }
7161 return;
7162 }
7163
7164 // Add the function template specialization produced by template argument
7165 // deduction as a candidate.
7166 assert(Specialization && "Missing member function template specialization?")(static_cast <bool> (Specialization && "Missing member function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "clang/lib/Sema/SemaOverload.cpp", 7166, __extension__ __PRETTY_FUNCTION__
))
;
7167 assert(isa<CXXMethodDecl>(Specialization) &&(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "clang/lib/Sema/SemaOverload.cpp", 7168, __extension__ __PRETTY_FUNCTION__
))
7168 "Specialization is not a member function?")(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "clang/lib/Sema/SemaOverload.cpp", 7168, __extension__ __PRETTY_FUNCTION__
))
;
7169 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7170 ActingContext, ObjectType, ObjectClassification, Args,
7171 CandidateSet, SuppressUserConversions, PartialOverloading,
7172 Conversions, PO);
7173}
7174
7175/// Determine whether a given function template has a simple explicit specifier
7176/// or a non-value-dependent explicit-specification that evaluates to true.
7177static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7178 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7179}
7180
7181/// Add a C++ function template specialization as a candidate
7182/// in the candidate set, using template argument deduction to produce
7183/// an appropriate function template specialization.
7184void Sema::AddTemplateOverloadCandidate(
7185 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7186 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7187 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7188 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7189 OverloadCandidateParamOrder PO) {
7190 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7191 return;
7192
7193 // If the function template has a non-dependent explicit specification,
7194 // exclude it now if appropriate; we are not permitted to perform deduction
7195 // and substitution in this case.
7196 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7197 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7198 Candidate.FoundDecl = FoundDecl;
7199 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7200 Candidate.Viable = false;
7201 Candidate.FailureKind = ovl_fail_explicit;
7202 return;
7203 }
7204
7205 // C++ [over.match.funcs]p7:
7206 // In each case where a candidate is a function template, candidate
7207 // function template specializations are generated using template argument
7208 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7209 // candidate functions in the usual way.113) A given name can refer to one
7210 // or more function templates and also to a set of overloaded non-template
7211 // functions. In such a case, the candidate functions generated from each
7212 // function template are combined with the set of non-template candidate
7213 // functions.
7214 TemplateDeductionInfo Info(CandidateSet.getLocation());
7215 FunctionDecl *Specialization = nullptr;
7216 ConversionSequenceList Conversions;
7217 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7218 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7219 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7220 return CheckNonDependentConversions(
7221 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7222 SuppressUserConversions, nullptr, QualType(), {}, PO);
7223 })) {
7224 OverloadCandidate &Candidate =
7225 CandidateSet.addCandidate(Conversions.size(), Conversions);
7226 Candidate.FoundDecl = FoundDecl;
7227 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7228 Candidate.Viable = false;
7229 Candidate.RewriteKind =
7230 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7231 Candidate.IsSurrogate = false;
7232 Candidate.IsADLCandidate = IsADLCandidate;
7233 // Ignore the object argument if there is one, since we don't have an object
7234 // type.
7235 Candidate.IgnoreObjectArgument =
7236 isa<CXXMethodDecl>(Candidate.Function) &&
7237 !isa<CXXConstructorDecl>(Candidate.Function);
7238 Candidate.ExplicitCallArguments = Args.size();
7239 if (Result == TDK_NonDependentConversionFailure)
7240 Candidate.FailureKind = ovl_fail_bad_conversion;
7241 else {
7242 Candidate.FailureKind = ovl_fail_bad_deduction;
7243 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7244 Info);
7245 }
7246 return;
7247 }
7248
7249 // Add the function template specialization produced by template argument
7250 // deduction as a candidate.
7251 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "clang/lib/Sema/SemaOverload.cpp", 7251, __extension__ __PRETTY_FUNCTION__
))
;
7252 AddOverloadCandidate(
7253 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7254 PartialOverloading, AllowExplicit,
7255 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7256}
7257
7258/// Check that implicit conversion sequences can be formed for each argument
7259/// whose corresponding parameter has a non-dependent type, per DR1391's
7260/// [temp.deduct.call]p10.
7261bool Sema::CheckNonDependentConversions(
7262 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7263 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7264 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7265 CXXRecordDecl *ActingContext, QualType ObjectType,
7266 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7267 // FIXME: The cases in which we allow explicit conversions for constructor
7268 // arguments never consider calling a constructor template. It's not clear
7269 // that is correct.
7270 const bool AllowExplicit = false;
7271
7272 auto *FD = FunctionTemplate->getTemplatedDecl();
7273 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7274 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7275 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7276
7277 Conversions =
7278 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7279
7280 // Overload resolution is always an unevaluated context.
7281 EnterExpressionEvaluationContext Unevaluated(
7282 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7283
7284 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7285 // require that, but this check should never result in a hard error, and
7286 // overload resolution is permitted to sidestep instantiations.
7287 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7288 !ObjectType.isNull()) {
7289 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7290 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7291 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7292 Method, ActingContext);
7293 if (Conversions[ConvIdx].isBad())
7294 return true;
7295 }
7296
7297 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7298 ++I) {
7299 QualType ParamType = ParamTypes[I];
7300 if (!ParamType->isDependentType()) {
7301 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7302 ? 0
7303 : (ThisConversions + I);
7304 Conversions[ConvIdx]
7305 = TryCopyInitialization(*this, Args[I], ParamType,
7306 SuppressUserConversions,
7307 /*InOverloadResolution=*/true,
7308 /*AllowObjCWritebackConversion=*/
7309 getLangOpts().ObjCAutoRefCount,
7310 AllowExplicit);
7311 if (Conversions[ConvIdx].isBad())
7312 return true;
7313 }
7314 }
7315
7316 return false;
7317}
7318
7319/// Determine whether this is an allowable conversion from the result
7320/// of an explicit conversion operator to the expected type, per C++
7321/// [over.match.conv]p1 and [over.match.ref]p1.
7322///
7323/// \param ConvType The return type of the conversion function.
7324///
7325/// \param ToType The type we are converting to.
7326///
7327/// \param AllowObjCPointerConversion Allow a conversion from one
7328/// Objective-C pointer to another.
7329///
7330/// \returns true if the conversion is allowable, false otherwise.
7331static bool isAllowableExplicitConversion(Sema &S,
7332 QualType ConvType, QualType ToType,
7333 bool AllowObjCPointerConversion) {
7334 QualType ToNonRefType = ToType.getNonReferenceType();
7335
7336 // Easy case: the types are the same.
7337 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7338 return true;
7339
7340 // Allow qualification conversions.
7341 bool ObjCLifetimeConversion;
7342 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7343 ObjCLifetimeConversion))
7344 return true;
7345
7346 // If we're not allowed to consider Objective-C pointer conversions,
7347 // we're done.
7348 if (!AllowObjCPointerConversion)
7349 return false;
7350
7351 // Is this an Objective-C pointer conversion?
7352 bool IncompatibleObjC = false;
7353 QualType ConvertedType;
7354 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7355 IncompatibleObjC);
7356}
7357
7358/// AddConversionCandidate - Add a C++ conversion function as a
7359/// candidate in the candidate set (C++ [over.match.conv],
7360/// C++ [over.match.copy]). From is the expression we're converting from,
7361/// and ToType is the type that we're eventually trying to convert to
7362/// (which may or may not be the same type as the type that the
7363/// conversion function produces).
7364void Sema::AddConversionCandidate(
7365 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7366 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7367 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7368 bool AllowExplicit, bool AllowResultConversion) {
7369 assert(!Conversion->getDescribedFunctionTemplate() &&(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "clang/lib/Sema/SemaOverload.cpp", 7370, __extension__ __PRETTY_FUNCTION__
))
7370 "Conversion function templates use AddTemplateConversionCandidate")(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "clang/lib/Sema/SemaOverload.cpp", 7370, __extension__ __PRETTY_FUNCTION__
))
;
7371 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7372 if (!CandidateSet.isNewCandidate(Conversion))
7373 return;
7374
7375 // If the conversion function has an undeduced return type, trigger its
7376 // deduction now.
7377 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7378 if (DeduceReturnType(Conversion, From->getExprLoc()))
7379 return;
7380 ConvType = Conversion->getConversionType().getNonReferenceType();
7381 }
7382
7383 // If we don't allow any conversion of the result type, ignore conversion
7384 // functions that don't convert to exactly (possibly cv-qualified) T.
7385 if (!AllowResultConversion &&
7386 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7387 return;
7388
7389 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7390 // operator is only a candidate if its return type is the target type or
7391 // can be converted to the target type with a qualification conversion.
7392 //
7393 // FIXME: Include such functions in the candidate list and explain why we
7394 // can't select them.
7395 if (Conversion->isExplicit() &&
7396 !isAllowableExplicitConversion(*this, ConvType, ToType,
7397 AllowObjCConversionOnExplicit))
7398 return;
7399
7400 // Overload resolution is always an unevaluated context.
7401 EnterExpressionEvaluationContext Unevaluated(
7402 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7403
7404 // Add this candidate
7405 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7406 Candidate.FoundDecl = FoundDecl;
7407 Candidate.Function = Conversion;
7408 Candidate.IsSurrogate = false;
7409 Candidate.IgnoreObjectArgument = false;
7410 Candidate.FinalConversion.setAsIdentityConversion();
7411 Candidate.FinalConversion.setFromType(ConvType);
7412 Candidate.FinalConversion.setAllToTypes(ToType);
7413 Candidate.Viable = true;
7414 Candidate.ExplicitCallArguments = 1;
7415
7416 // Explicit functions are not actually candidates at all if we're not
7417 // allowing them in this context, but keep them around so we can point
7418 // to them in diagnostics.
7419 if (!AllowExplicit && Conversion->isExplicit()) {
7420 Candidate.Viable = false;
7421 Candidate.FailureKind = ovl_fail_explicit;
7422 return;
7423 }
7424
7425 // C++ [over.match.funcs]p4:
7426 // For conversion functions, the function is considered to be a member of
7427 // the class of the implicit implied object argument for the purpose of
7428 // defining the type of the implicit object parameter.
7429 //
7430 // Determine the implicit conversion sequence for the implicit
7431 // object parameter.
7432 QualType ImplicitParamType = From->getType();
7433 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7434 ImplicitParamType = FromPtrType->getPointeeType();
7435 CXXRecordDecl *ConversionContext
7436 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7437
7438 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7439 *this, CandidateSet.getLocation(), From->getType(),
7440 From->Classify(Context), Conversion, ConversionContext);
7441
7442 if (Candidate.Conversions[0].isBad()) {
7443 Candidate.Viable = false;
7444 Candidate.FailureKind = ovl_fail_bad_conversion;
7445 return;
7446 }
7447
7448 if (Conversion->getTrailingRequiresClause()) {
7449 ConstraintSatisfaction Satisfaction;
7450 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7451 !Satisfaction.IsSatisfied) {
7452 Candidate.Viable = false;
7453 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7454 return;
7455 }
7456 }
7457
7458 // We won't go through a user-defined type conversion function to convert a
7459 // derived to base as such conversions are given Conversion Rank. They only
7460 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7461 QualType FromCanon
7462 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7463 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7464 if (FromCanon == ToCanon ||
7465 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7466 Candidate.Viable = false;
7467 Candidate.FailureKind = ovl_fail_trivial_conversion;
7468 return;
7469 }
7470
7471 // To determine what the conversion from the result of calling the
7472 // conversion function to the type we're eventually trying to
7473 // convert to (ToType), we need to synthesize a call to the
7474 // conversion function and attempt copy initialization from it. This
7475 // makes sure that we get the right semantics with respect to
7476 // lvalues/rvalues and the type. Fortunately, we can allocate this
7477 // call on the stack and we don't need its arguments to be
7478 // well-formed.
7479 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7480 VK_LValue, From->getBeginLoc());
7481 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7482 Context.getPointerType(Conversion->getType()),
7483 CK_FunctionToPointerDecay, &ConversionRef,
7484 VK_PRValue, FPOptionsOverride());
7485
7486 QualType ConversionType = Conversion->getConversionType();
7487 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7488 Candidate.Viable = false;
7489 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7490 return;
7491 }
7492
7493 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7494
7495 // Note that it is safe to allocate CallExpr on the stack here because
7496 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7497 // allocator).
7498 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7499
7500 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7501 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7502 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7503
7504 ImplicitConversionSequence ICS =
7505 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7506 /*SuppressUserConversions=*/true,
7507 /*InOverloadResolution=*/false,
7508 /*AllowObjCWritebackConversion=*/false);
7509
7510 switch (ICS.getKind()) {
7511 case ImplicitConversionSequence::StandardConversion:
7512 Candidate.FinalConversion = ICS.Standard;
7513
7514 // C++ [over.ics.user]p3:
7515 // If the user-defined conversion is specified by a specialization of a
7516 // conversion function template, the second standard conversion sequence
7517 // shall have exact match rank.
7518 if (Conversion->getPrimaryTemplate() &&
7519 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7520 Candidate.Viable = false;
7521 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7522 return;
7523 }
7524
7525 // C++0x [dcl.init.ref]p5:
7526 // In the second case, if the reference is an rvalue reference and
7527 // the second standard conversion sequence of the user-defined
7528 // conversion sequence includes an lvalue-to-rvalue conversion, the
7529 // program is ill-formed.
7530 if (ToType->isRValueReferenceType() &&
7531 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7532 Candidate.Viable = false;
7533 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7534 return;
7535 }
7536 break;
7537
7538 case ImplicitConversionSequence::BadConversion:
7539 Candidate.Viable = false;
7540 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7541 return;
7542
7543 default:
7544 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "clang/lib/Sema/SemaOverload.cpp", 7545)
7545 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "clang/lib/Sema/SemaOverload.cpp", 7545)
;
7546 }
7547
7548 if (EnableIfAttr *FailedAttr =
7549 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7550 Candidate.Viable = false;
7551 Candidate.FailureKind = ovl_fail_enable_if;
7552 Candidate.DeductionFailure.Data = FailedAttr;
7553 return;
7554 }
7555
7556 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7557 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7558 Candidate.Viable = false;
7559 Candidate.FailureKind = ovl_non_default_multiversion_function;
7560 }
7561}
7562
7563/// Adds a conversion function template specialization
7564/// candidate to the overload set, using template argument deduction
7565/// to deduce the template arguments of the conversion function
7566/// template from the type that we are converting to (C++
7567/// [temp.deduct.conv]).
7568void Sema::AddTemplateConversionCandidate(
7569 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7570 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7571 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7572 bool AllowExplicit, bool AllowResultConversion) {
7573 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "clang/lib/Sema/SemaOverload.cpp", 7574, __extension__ __PRETTY_FUNCTION__
))
7574 "Only conversion function templates permitted here")(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "clang/lib/Sema/SemaOverload.cpp", 7574, __extension__ __PRETTY_FUNCTION__
))
;
7575
7576 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7577 return;
7578
7579 // If the function template has a non-dependent explicit specification,
7580 // exclude it now if appropriate; we are not permitted to perform deduction
7581 // and substitution in this case.
7582 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7583 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7584 Candidate.FoundDecl = FoundDecl;
7585 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7586 Candidate.Viable = false;
7587 Candidate.FailureKind = ovl_fail_explicit;
7588 return;
7589 }
7590
7591 TemplateDeductionInfo Info(CandidateSet.getLocation());
7592 CXXConversionDecl *Specialization = nullptr;
7593 if (TemplateDeductionResult Result
7594 = DeduceTemplateArguments(FunctionTemplate, ToType,
7595 Specialization, Info)) {
7596 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7597 Candidate.FoundDecl = FoundDecl;
7598 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7599 Candidate.Viable = false;
7600 Candidate.FailureKind = ovl_fail_bad_deduction;
7601 Candidate.IsSurrogate = false;
7602 Candidate.IgnoreObjectArgument = false;
7603 Candidate.ExplicitCallArguments = 1;
7604 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7605 Info);
7606 return;
7607 }
7608
7609 // Add the conversion function template specialization produced by
7610 // template argument deduction as a candidate.
7611 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "clang/lib/Sema/SemaOverload.cpp", 7611, __extension__ __PRETTY_FUNCTION__
))
;
7612 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7613 CandidateSet, AllowObjCConversionOnExplicit,
7614 AllowExplicit, AllowResultConversion);
7615}
7616
7617/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7618/// converts the given @c Object to a function pointer via the
7619/// conversion function @c Conversion, and then attempts to call it
7620/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7621/// the type of function that we'll eventually be calling.
7622void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7623 DeclAccessPair FoundDecl,
7624 CXXRecordDecl *ActingContext,
7625 const FunctionProtoType *Proto,
7626 Expr *Object,
7627 ArrayRef<Expr *> Args,
7628 OverloadCandidateSet& CandidateSet) {
7629 if (!CandidateSet.isNewCandidate(Conversion))
7630 return;
7631
7632 // Overload resolution is always an unevaluated context.
7633 EnterExpressionEvaluationContext Unevaluated(
7634 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7635
7636 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7637 Candidate.FoundDecl = FoundDecl;
7638 Candidate.Function = nullptr;
7639 Candidate.Surrogate = Conversion;
7640 Candidate.Viable = true;
7641 Candidate.IsSurrogate = true;
7642 Candidate.IgnoreObjectArgument = false;
7643 Candidate.ExplicitCallArguments = Args.size();
7644
7645 // Determine the implicit conversion sequence for the implicit
7646 // object parameter.
7647 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7648 *this, CandidateSet.getLocation(), Object->getType(),
7649 Object->Classify(Context), Conversion, ActingContext);
7650 if (ObjectInit.isBad()) {
7651 Candidate.Viable = false;
7652 Candidate.FailureKind = ovl_fail_bad_conversion;
7653 Candidate.Conversions[0] = ObjectInit;
7654 return;
7655 }
7656
7657 // The first conversion is actually a user-defined conversion whose
7658 // first conversion is ObjectInit's standard conversion (which is
7659 // effectively a reference binding). Record it as such.
7660 Candidate.Conversions[0].setUserDefined();
7661 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7662 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7663 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7664 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7665 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7666 Candidate.Conversions[0].UserDefined.After
7667 = Candidate.Conversions[0].UserDefined.Before;
7668 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7669
7670 // Find the
7671 unsigned NumParams = Proto->getNumParams();
7672
7673 // (C++ 13.3.2p2): A candidate function having fewer than m
7674 // parameters is viable only if it has an ellipsis in its parameter
7675 // list (8.3.5).
7676 if (Args.size() > NumParams && !Proto->isVariadic()) {
7677 Candidate.Viable = false;
7678 Candidate.FailureKind = ovl_fail_too_many_arguments;
7679 return;
7680 }
7681
7682 // Function types don't have any default arguments, so just check if
7683 // we have enough arguments.
7684 if (Args.size() < NumParams) {
7685 // Not enough arguments.
7686 Candidate.Viable = false;
7687 Candidate.FailureKind = ovl_fail_too_few_arguments;
7688 return;
7689 }
7690
7691 // Determine the implicit conversion sequences for each of the
7692 // arguments.
7693 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7694 if (ArgIdx < NumParams) {
7695 // (C++ 13.3.2p3): for F to be a viable function, there shall
7696 // exist for each argument an implicit conversion sequence
7697 // (13.3.3.1) that converts that argument to the corresponding
7698 // parameter of F.
7699 QualType ParamType = Proto->getParamType(ArgIdx);
7700 Candidate.Conversions[ArgIdx + 1]
7701 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7702 /*SuppressUserConversions=*/false,
7703 /*InOverloadResolution=*/false,
7704 /*AllowObjCWritebackConversion=*/
7705 getLangOpts().ObjCAutoRefCount);
7706 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7707 Candidate.Viable = false;
7708 Candidate.FailureKind = ovl_fail_bad_conversion;
7709 return;
7710 }
7711 } else {
7712 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7713 // argument for which there is no corresponding parameter is
7714 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7715 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7716 }
7717 }
7718
7719 if (EnableIfAttr *FailedAttr =
7720 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7721 Candidate.Viable = false;
7722 Candidate.FailureKind = ovl_fail_enable_if;
7723 Candidate.DeductionFailure.Data = FailedAttr;
7724 return;
7725 }
7726}
7727
7728/// Add all of the non-member operator function declarations in the given
7729/// function set to the overload candidate set.
7730void Sema::AddNonMemberOperatorCandidates(
7731 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7732 OverloadCandidateSet &CandidateSet,
7733 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7734 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7735 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7736 ArrayRef<Expr *> FunctionArgs = Args;
7737
7738 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7739 FunctionDecl *FD =
7740 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7741
7742 // Don't consider rewritten functions if we're not rewriting.
7743 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7744 continue;
7745
7746 assert(!isa<CXXMethodDecl>(FD) &&(static_cast <bool> (!isa<CXXMethodDecl>(FD) &&
"unqualified operator lookup found a member function") ? void
(0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "clang/lib/Sema/SemaOverload.cpp", 7747, __extension__ __PRETTY_FUNCTION__
))
7747 "unqualified operator lookup found a member function")(static_cast <bool> (!isa<CXXMethodDecl>(FD) &&
"unqualified operator lookup found a member function") ? void
(0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "clang/lib/Sema/SemaOverload.cpp", 7747, __extension__ __PRETTY_FUNCTION__
))
;
7748
7749 if (FunTmpl) {
7750 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7751 FunctionArgs, CandidateSet);
7752 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7753 AddTemplateOverloadCandidate(
7754 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7755 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7756 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7757 } else {
7758 if (ExplicitTemplateArgs)
7759 continue;
7760 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7761 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7762 AddOverloadCandidate(FD, F.getPair(),
7763 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7764 false, false, true, false, ADLCallKind::NotADL,
7765 None, OverloadCandidateParamOrder::Reversed);
7766 }
7767 }
7768}
7769
7770/// Add overload candidates for overloaded operators that are
7771/// member functions.
7772///
7773/// Add the overloaded operator candidates that are member functions
7774/// for the operator Op that was used in an operator expression such
7775/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7776/// CandidateSet will store the added overload candidates. (C++
7777/// [over.match.oper]).
7778void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7779 SourceLocation OpLoc,
7780 ArrayRef<Expr *> Args,
7781 OverloadCandidateSet &CandidateSet,
7782 OverloadCandidateParamOrder PO) {
7783 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7784
7785 // C++ [over.match.oper]p3:
7786 // For a unary operator @ with an operand of a type whose
7787 // cv-unqualified version is T1, and for a binary operator @ with
7788 // a left operand of a type whose cv-unqualified version is T1 and
7789 // a right operand of a type whose cv-unqualified version is T2,
7790 // three sets of candidate functions, designated member
7791 // candidates, non-member candidates and built-in candidates, are
7792 // constructed as follows:
7793 QualType T1 = Args[0]->getType();
7794
7795 // -- If T1 is a complete class type or a class currently being
7796 // defined, the set of member candidates is the result of the
7797 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7798 // the set of member candidates is empty.
7799 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7800 // Complete the type if it can be completed.
7801 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7802 return;
7803 // If the type is neither complete nor being defined, bail out now.
7804 if (!T1Rec->getDecl()->getDefinition())
7805 return;
7806
7807 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7808 LookupQualifiedName(Operators, T1Rec->getDecl());
7809 Operators.suppressDiagnostics();
7810
7811 for (LookupResult::iterator Oper = Operators.begin(),
7812 OperEnd = Operators.end();
7813 Oper != OperEnd;
7814 ++Oper)
7815 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7816 Args[0]->Classify(Context), Args.slice(1),
7817 CandidateSet, /*SuppressUserConversion=*/false, PO);
7818 }
7819}
7820
7821/// AddBuiltinCandidate - Add a candidate for a built-in
7822/// operator. ResultTy and ParamTys are the result and parameter types
7823/// of the built-in candidate, respectively. Args and NumArgs are the
7824/// arguments being passed to the candidate. IsAssignmentOperator
7825/// should be true when this built-in candidate is an assignment
7826/// operator. NumContextualBoolArguments is the number of arguments
7827/// (at the beginning of the argument list) that will be contextually
7828/// converted to bool.
7829void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7830 OverloadCandidateSet& CandidateSet,
7831 bool IsAssignmentOperator,
7832 unsigned NumContextualBoolArguments) {
7833 // Overload resolution is always an unevaluated context.
7834 EnterExpressionEvaluationContext Unevaluated(
7835 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7836
7837 // Add this candidate
7838 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7839 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7840 Candidate.Function = nullptr;
7841 Candidate.IsSurrogate = false;
7842 Candidate.IgnoreObjectArgument = false;
7843 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7844
7845 // Determine the implicit conversion sequences for each of the
7846 // arguments.
7847 Candidate.Viable = true;
7848 Candidate.ExplicitCallArguments = Args.size();
7849 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7850 // C++ [over.match.oper]p4:
7851 // For the built-in assignment operators, conversions of the
7852 // left operand are restricted as follows:
7853 // -- no temporaries are introduced to hold the left operand, and
7854 // -- no user-defined conversions are applied to the left
7855 // operand to achieve a type match with the left-most
7856 // parameter of a built-in candidate.
7857 //
7858 // We block these conversions by turning off user-defined
7859 // conversions, since that is the only way that initialization of
7860 // a reference to a non-class type can occur from something that
7861 // is not of the same type.
7862 if (ArgIdx < NumContextualBoolArguments) {
7863 assert(ParamTys[ArgIdx] == Context.BoolTy &&(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "clang/lib/Sema/SemaOverload.cpp", 7864, __extension__ __PRETTY_FUNCTION__
))
7864 "Contextual conversion to bool requires bool type")(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "clang/lib/Sema/SemaOverload.cpp", 7864, __extension__ __PRETTY_FUNCTION__
))
;
7865 Candidate.Conversions[ArgIdx]
7866 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7867 } else {
7868 Candidate.Conversions[ArgIdx]
7869 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7870 ArgIdx == 0 && IsAssignmentOperator,
7871 /*InOverloadResolution=*/false,
7872 /*AllowObjCWritebackConversion=*/
7873 getLangOpts().ObjCAutoRefCount);
7874 }
7875 if (Candidate.Conversions[ArgIdx].isBad()) {
7876 Candidate.Viable = false;
7877 Candidate.FailureKind = ovl_fail_bad_conversion;
7878 break;
7879 }
7880 }
7881}
7882
7883namespace {
7884
7885/// BuiltinCandidateTypeSet - A set of types that will be used for the
7886/// candidate operator functions for built-in operators (C++
7887/// [over.built]). The types are separated into pointer types and
7888/// enumeration types.
7889class BuiltinCandidateTypeSet {
7890 /// TypeSet - A set of types.
7891 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7892 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7893
7894 /// PointerTypes - The set of pointer types that will be used in the
7895 /// built-in candidates.
7896 TypeSet PointerTypes;
7897
7898 /// MemberPointerTypes - The set of member pointer types that will be
7899 /// used in the built-in candidates.
7900 TypeSet MemberPointerTypes;
7901
7902 /// EnumerationTypes - The set of enumeration types that will be
7903 /// used in the built-in candidates.
7904 TypeSet EnumerationTypes;
7905
7906 /// The set of vector types that will be used in the built-in
7907 /// candidates.
7908 TypeSet VectorTypes;
7909
7910 /// The set of matrix types that will be used in the built-in
7911 /// candidates.
7912 TypeSet MatrixTypes;
7913
7914 /// A flag indicating non-record types are viable candidates
7915 bool HasNonRecordTypes;
7916
7917 /// A flag indicating whether either arithmetic or enumeration types
7918 /// were present in the candidate set.
7919 bool HasArithmeticOrEnumeralTypes;
7920
7921 /// A flag indicating whether the nullptr type was present in the
7922 /// candidate set.
7923 bool HasNullPtrType;
7924
7925 /// Sema - The semantic analysis instance where we are building the
7926 /// candidate type set.
7927 Sema &SemaRef;
7928
7929 /// Context - The AST context in which we will build the type sets.
7930 ASTContext &Context;
7931
7932 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7933 const Qualifiers &VisibleQuals);
7934 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7935
7936public:
7937 /// iterator - Iterates through the types that are part of the set.
7938 typedef TypeSet::iterator iterator;
7939
7940 BuiltinCandidateTypeSet(Sema &SemaRef)
7941 : HasNonRecordTypes(false),
7942 HasArithmeticOrEnumeralTypes(false),
7943 HasNullPtrType(false),
7944 SemaRef(SemaRef),
7945 Context(SemaRef.Context) { }
7946
7947 void AddTypesConvertedFrom(QualType Ty,
7948 SourceLocation Loc,
7949 bool AllowUserConversions,
7950 bool AllowExplicitConversions,
7951 const Qualifiers &VisibleTypeConversionsQuals);
7952
7953 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7954 llvm::iterator_range<iterator> member_pointer_types() {
7955 return MemberPointerTypes;
7956 }
7957 llvm::iterator_range<iterator> enumeration_types() {
7958 return EnumerationTypes;
7959 }
7960 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7961 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7962
7963 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7964 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7965 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7966 bool hasNullPtrType() const { return HasNullPtrType; }
7967};
7968
7969} // end anonymous namespace
7970
7971/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7972/// the set of pointer types along with any more-qualified variants of
7973/// that type. For example, if @p Ty is "int const *", this routine
7974/// will add "int const *", "int const volatile *", "int const
7975/// restrict *", and "int const volatile restrict *" to the set of
7976/// pointer types. Returns true if the add of @p Ty itself succeeded,
7977/// false otherwise.
7978///
7979/// FIXME: what to do about extended qualifiers?
7980bool
7981BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7982 const Qualifiers &VisibleQuals) {
7983
7984 // Insert this type.
7985 if (!PointerTypes.insert(Ty))
7986 return false;
7987
7988 QualType PointeeTy;
7989 const PointerType *PointerTy = Ty->getAs<PointerType>();
7990 bool buildObjCPtr = false;
7991 if (!PointerTy) {
7992 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7993 PointeeTy = PTy->getPointeeType();
7994 buildObjCPtr = true;
7995 } else {
7996 PointeeTy = PointerTy->getPointeeType();
7997 }
7998
7999 // Don't add qualified variants of arrays. For one, they're not allowed
8000 // (the qualifier would sink to the element type), and for another, the
8001 // only overload situation where it matters is subscript or pointer +- int,
8002 // and those shouldn't have qualifier variants anyway.
8003 if (PointeeTy->isArrayType())
8004 return true;
8005
8006 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8007 bool hasVolatile = VisibleQuals.hasVolatile();
8008 bool hasRestrict = VisibleQuals.hasRestrict();
8009
8010 // Iterate through all strict supersets of BaseCVR.
8011 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8012 if ((CVR | BaseCVR) != CVR) continue;
8013 // Skip over volatile if no volatile found anywhere in the types.
8014 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8015
8016 // Skip over restrict if no restrict found anywhere in the types, or if
8017 // the type cannot be restrict-qualified.
8018 if ((CVR & Qualifiers::Restrict) &&
8019 (!hasRestrict ||
8020 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8021 continue;
8022
8023 // Build qualified pointee type.
8024 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8025
8026 // Build qualified pointer type.
8027 QualType QPointerTy;
8028 if (!buildObjCPtr)
8029 QPointerTy = Context.getPointerType(QPointeeTy);
8030 else
8031 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8032
8033 // Insert qualified pointer type.
8034 PointerTypes.insert(QPointerTy);
8035 }
8036
8037 return true;
8038}
8039
8040/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8041/// to the set of pointer types along with any more-qualified variants of
8042/// that type. For example, if @p Ty is "int const *", this routine
8043/// will add "int const *", "int const volatile *", "int const
8044/// restrict *", and "int const volatile restrict *" to the set of
8045/// pointer types. Returns true if the add of @p Ty itself succeeded,
8046/// false otherwise.
8047///
8048/// FIXME: what to do about extended qualifiers?
8049bool
8050BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8051 QualType Ty) {
8052 // Insert this type.
8053 if (!MemberPointerTypes.insert(Ty))
8054 return false;
8055
8056 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8057 assert(PointerTy && "type was not a member pointer type!")(static_cast <bool> (PointerTy && "type was not a member pointer type!"
) ? void (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "clang/lib/Sema/SemaOverload.cpp", 8057, __extension__ __PRETTY_FUNCTION__
))
;
8058
8059 QualType PointeeTy = PointerTy->getPointeeType();
8060 // Don't add qualified variants of arrays. For one, they're not allowed
8061 // (the qualifier would sink to the element type), and for another, the
8062 // only overload situation where it matters is subscript or pointer +- int,
8063 // and those shouldn't have qualifier variants anyway.
8064 if (PointeeTy->isArrayType())
8065 return true;
8066 const Type *ClassTy = PointerTy->getClass();
8067
8068 // Iterate through all strict supersets of the pointee type's CVR
8069 // qualifiers.
8070 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8071 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8072 if ((CVR | BaseCVR) != CVR) continue;
8073
8074 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8075 MemberPointerTypes.insert(
8076 Context.getMemberPointerType(QPointeeTy, ClassTy));
8077 }
8078
8079 return true;
8080}
8081
8082/// AddTypesConvertedFrom - Add each of the types to which the type @p
8083/// Ty can be implicit converted to the given set of @p Types. We're
8084/// primarily interested in pointer types and enumeration types. We also
8085/// take member pointer types, for the conditional operator.
8086/// AllowUserConversions is true if we should look at the conversion
8087/// functions of a class type, and AllowExplicitConversions if we
8088/// should also include the explicit conversion functions of a class
8089/// type.
8090void
8091BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8092 SourceLocation Loc,
8093 bool AllowUserConversions,
8094 bool AllowExplicitConversions,
8095 const Qualifiers &VisibleQuals) {
8096 // Only deal with canonical types.
8097 Ty = Context.getCanonicalType(Ty);
8098
8099 // Look through reference types; they aren't part of the type of an
8100 // expression for the purposes of conversions.
8101 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8102 Ty = RefTy->getPointeeType();
8103
8104 // If we're dealing with an array type, decay to the pointer.
8105 if (Ty->isArrayType())
8106 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8107
8108 // Otherwise, we don't care about qualifiers on the type.
8109 Ty = Ty.getLocalUnqualifiedType();
8110
8111 // Flag if we ever add a non-record type.
8112 const RecordType *TyRec = Ty->getAs<RecordType>();
8113 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8114
8115 // Flag if we encounter an arithmetic type.
8116 HasArithmeticOrEnumeralTypes =
8117 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8118
8119 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8120 PointerTypes.insert(Ty);
8121 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8122 // Insert our type, and its more-qualified variants, into the set
8123 // of types.
8124 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8125 return;
8126 } else if (Ty->isMemberPointerType()) {
8127 // Member pointers are far easier, since the pointee can't be converted.
8128 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8129 return;
8130 } else if (Ty->isEnumeralType()) {
8131 HasArithmeticOrEnumeralTypes = true;
8132 EnumerationTypes.insert(Ty);
8133 } else if (Ty->isVectorType()) {
8134 // We treat vector types as arithmetic types in many contexts as an
8135 // extension.
8136 HasArithmeticOrEnumeralTypes = true;
8137 VectorTypes.insert(Ty);
8138 } else if (Ty->isMatrixType()) {
8139 // Similar to vector types, we treat vector types as arithmetic types in
8140 // many contexts as an extension.
8141 HasArithmeticOrEnumeralTypes = true;
8142 MatrixTypes.insert(Ty);
8143 } else if (Ty->isNullPtrType()) {
8144 HasNullPtrType = true;
8145 } else if (AllowUserConversions && TyRec) {
8146 // No conversion functions in incomplete types.
8147 if (!SemaRef.isCompleteType(Loc, Ty))
8148 return;
8149
8150 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8151 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8152 if (isa<UsingShadowDecl>(D))
8153 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8154
8155 // Skip conversion function templates; they don't tell us anything
8156 // about which builtin types we can convert to.
8157 if (isa<FunctionTemplateDecl>(D))
8158 continue;
8159
8160 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8161 if (AllowExplicitConversions || !Conv->isExplicit()) {
8162 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8163 VisibleQuals);
8164 }
8165 }
8166 }
8167}
8168/// Helper function for adjusting address spaces for the pointer or reference
8169/// operands of builtin operators depending on the argument.
8170static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8171 Expr *Arg) {
8172 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8173}
8174
8175/// Helper function for AddBuiltinOperatorCandidates() that adds
8176/// the volatile- and non-volatile-qualified assignment operators for the
8177/// given type to the candidate set.
8178static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8179 QualType T,
8180 ArrayRef<Expr *> Args,
8181 OverloadCandidateSet &CandidateSet) {
8182 QualType ParamTypes[2];
8183
8184 // T& operator=(T&, T)
8185 ParamTypes[0] = S.Context.getLValueReferenceType(
8186 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8187 ParamTypes[1] = T;
8188 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8189 /*IsAssignmentOperator=*/true);
8190
8191 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8192 // volatile T& operator=(volatile T&, T)
8193 ParamTypes[0] = S.Context.getLValueReferenceType(
8194 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8195 Args[0]));
8196 ParamTypes[1] = T;
8197 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8198 /*IsAssignmentOperator=*/true);
8199 }
8200}
8201
8202/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8203/// if any, found in visible type conversion functions found in ArgExpr's type.
8204static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8205 Qualifiers VRQuals;
8206 const RecordType *TyRec;
8207 if (const MemberPointerType *RHSMPType =
8208 ArgExpr->getType()->getAs<MemberPointerType>())
8209 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8210 else
8211 TyRec = ArgExpr->getType()->getAs<RecordType>();
8212 if (!TyRec) {
8213 // Just to be safe, assume the worst case.
8214 VRQuals.addVolatile();
8215 VRQuals.addRestrict();
8216 return VRQuals;
8217 }
8218
8219 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8220 if (!ClassDecl->hasDefinition())
8221 return VRQuals;
8222
8223 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8224 if (isa<UsingShadowDecl>(D))
8225 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8226 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8227 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8228 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8229 CanTy = ResTypeRef->getPointeeType();
8230 // Need to go down the pointer/mempointer chain and add qualifiers
8231 // as see them.
8232 bool done = false;
8233 while (!done) {
8234 if (CanTy.isRestrictQualified())
8235 VRQuals.addRestrict();
8236 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8237 CanTy = ResTypePtr->getPointeeType();
8238 else if (const MemberPointerType *ResTypeMPtr =
8239 CanTy->getAs<MemberPointerType>())
8240 CanTy = ResTypeMPtr->getPointeeType();
8241 else
8242 done = true;
8243 if (CanTy.isVolatileQualified())
8244 VRQuals.addVolatile();
8245 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8246 return VRQuals;
8247 }
8248 }
8249 }
8250 return VRQuals;
8251}
8252
8253// Note: We're currently only handling qualifiers that are meaningful for the
8254// LHS of compound assignment overloading.
8255static void forAllQualifierCombinationsImpl(
8256 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8257 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8258 // _Atomic
8259 if (Available.hasAtomic()) {
8260 Available.removeAtomic();
8261 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8262 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8263 return;
8264 }
8265
8266 // volatile
8267 if (Available.hasVolatile()) {
8268 Available.removeVolatile();
8269 assert(!Applied.hasVolatile())(static_cast <bool> (!Applied.hasVolatile()) ? void (0)
: __assert_fail ("!Applied.hasVolatile()", "clang/lib/Sema/SemaOverload.cpp"
, 8269, __extension__ __PRETTY_FUNCTION__))
;
8270 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8271 Callback);
8272 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8273 return;
8274 }
8275
8276 Callback(Applied);
8277}
8278
8279static void forAllQualifierCombinations(
8280 QualifiersAndAtomic Quals,
8281 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8282 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8283 Callback);
8284}
8285
8286static QualType makeQualifiedLValueReferenceType(QualType Base,
8287 QualifiersAndAtomic Quals,
8288 Sema &S) {
8289 if (Quals.hasAtomic())
8290 Base = S.Context.getAtomicType(Base);
8291 if (Quals.hasVolatile())
8292 Base = S.Context.getVolatileType(Base);
8293 return S.Context.getLValueReferenceType(Base);
8294}
8295
8296namespace {
8297
8298/// Helper class to manage the addition of builtin operator overload
8299/// candidates. It provides shared state and utility methods used throughout
8300/// the process, as well as a helper method to add each group of builtin
8301/// operator overloads from the standard to a candidate set.
8302class BuiltinOperatorOverloadBuilder {
8303 // Common instance state available to all overload candidate addition methods.
8304 Sema &S;
8305 ArrayRef<Expr *> Args;
8306 QualifiersAndAtomic VisibleTypeConversionsQuals;
8307 bool HasArithmeticOrEnumeralCandidateType;
8308 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8309 OverloadCandidateSet &CandidateSet;
8310
8311 static constexpr int ArithmeticTypesCap = 24;
8312 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8313
8314 // Define some indices used to iterate over the arithmetic types in
8315 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8316 // types are that preserved by promotion (C++ [over.built]p2).
8317 unsigned FirstIntegralType,
8318 LastIntegralType;
8319 unsigned FirstPromotedIntegralType,
8320 LastPromotedIntegralType;
8321 unsigned FirstPromotedArithmeticType,
8322 LastPromotedArithmeticType;
8323 unsigned NumArithmeticTypes;
8324
8325 void InitArithmeticTypes() {
8326 // Start of promoted types.
8327 FirstPromotedArithmeticType = 0;
8328 ArithmeticTypes.push_back(S.Context.FloatTy);
8329 ArithmeticTypes.push_back(S.Context.DoubleTy);
8330 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8331 if (S.Context.getTargetInfo().hasFloat128Type())
8332 ArithmeticTypes.push_back(S.Context.Float128Ty);
8333 if (S.Context.getTargetInfo().hasIbm128Type())
8334 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8335
8336 // Start of integral types.
8337 FirstIntegralType = ArithmeticTypes.size();
8338 FirstPromotedIntegralType = ArithmeticTypes.size();
8339 ArithmeticTypes.push_back(S.Context.IntTy);
8340 ArithmeticTypes.push_back(S.Context.LongTy);
8341 ArithmeticTypes.push_back(S.Context.LongLongTy);
8342 if (S.Context.getTargetInfo().hasInt128Type() ||
8343 (S.Context.getAuxTargetInfo() &&
8344 S.Context.getAuxTargetInfo()->hasInt128Type()))
8345 ArithmeticTypes.push_back(S.Context.Int128Ty);
8346 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8347 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8348 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8349 if (S.Context.getTargetInfo().hasInt128Type() ||
8350 (S.Context.getAuxTargetInfo() &&
8351 S.Context.getAuxTargetInfo()->hasInt128Type()))
8352 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8353 LastPromotedIntegralType = ArithmeticTypes.size();
8354 LastPromotedArithmeticType = ArithmeticTypes.size();
8355 // End of promoted types.
8356
8357 ArithmeticTypes.push_back(S.Context.BoolTy);
8358 ArithmeticTypes.push_back(S.Context.CharTy);
8359 ArithmeticTypes.push_back(S.Context.WCharTy);
8360 if (S.Context.getLangOpts().Char8)
8361 ArithmeticTypes.push_back(S.Context.Char8Ty);
8362 ArithmeticTypes.push_back(S.Context.Char16Ty);
8363 ArithmeticTypes.push_back(S.Context.Char32Ty);
8364 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8365 ArithmeticTypes.push_back(S.Context.ShortTy);
8366 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8367 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8368 LastIntegralType = ArithmeticTypes.size();
8369 NumArithmeticTypes = ArithmeticTypes.size();
8370 // End of integral types.
8371 // FIXME: What about complex? What about half?
8372
8373 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "clang/lib/Sema/SemaOverload.cpp", 8374, __extension__ __PRETTY_FUNCTION__
))
8374 "Enough inline storage for all arithmetic types.")(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "clang/lib/Sema/SemaOverload.cpp", 8374, __extension__ __PRETTY_FUNCTION__
))
;
8375 }
8376
8377 /// Helper method to factor out the common pattern of adding overloads
8378 /// for '++' and '--' builtin operators.
8379 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8380 bool HasVolatile,
8381 bool HasRestrict) {
8382 QualType ParamTypes[2] = {
8383 S.Context.getLValueReferenceType(CandidateTy),
8384 S.Context.IntTy
8385 };
8386
8387 // Non-volatile version.
8388 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8389
8390 // Use a heuristic to reduce number of builtin candidates in the set:
8391 // add volatile version only if there are conversions to a volatile type.
8392 if (HasVolatile) {
8393 ParamTypes[0] =
8394 S.Context.getLValueReferenceType(
8395 S.Context.getVolatileType(CandidateTy));
8396 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8397 }
8398
8399 // Add restrict version only if there are conversions to a restrict type
8400 // and our candidate type is a non-restrict-qualified pointer.
8401 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8402 !CandidateTy.isRestrictQualified()) {
8403 ParamTypes[0]
8404 = S.Context.getLValueReferenceType(
8405 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8406 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8407
8408 if (HasVolatile) {
8409 ParamTypes[0]
8410 = S.Context.getLValueReferenceType(
8411 S.Context.getCVRQualifiedType(CandidateTy,
8412 (Qualifiers::Volatile |
8413 Qualifiers::Restrict)));
8414 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8415 }
8416 }
8417
8418 }
8419
8420 /// Helper to add an overload candidate for a binary builtin with types \p L
8421 /// and \p R.
8422 void AddCandidate(QualType L, QualType R) {
8423 QualType LandR[2] = {L, R};
8424 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8425 }
8426
8427public:
8428 BuiltinOperatorOverloadBuilder(
8429 Sema &S, ArrayRef<Expr *> Args,
8430 QualifiersAndAtomic VisibleTypeConversionsQuals,
8431 bool HasArithmeticOrEnumeralCandidateType,
8432 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8433 OverloadCandidateSet &CandidateSet)
8434 : S(S), Args(Args),
8435 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8436 HasArithmeticOrEnumeralCandidateType(
8437 HasArithmeticOrEnumeralCandidateType),
8438 CandidateTypes(CandidateTypes),
8439 CandidateSet(CandidateSet) {
8440
8441 InitArithmeticTypes();
8442 }
8443
8444 // Increment is deprecated for bool since C++17.
8445 //
8446 // C++ [over.built]p3:
8447 //
8448 // For every pair (T, VQ), where T is an arithmetic type other
8449 // than bool, and VQ is either volatile or empty, there exist
8450 // candidate operator functions of the form
8451 //
8452 // VQ T& operator++(VQ T&);
8453 // T operator++(VQ T&, int);
8454 //
8455 // C++ [over.built]p4:
8456 //
8457 // For every pair (T, VQ), where T is an arithmetic type other
8458 // than bool, and VQ is either volatile or empty, there exist
8459 // candidate operator functions of the form
8460 //
8461 // VQ T& operator--(VQ T&);
8462 // T operator--(VQ T&, int);
8463 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8464 if (!HasArithmeticOrEnumeralCandidateType)
8465 return;
8466
8467 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8468 const auto TypeOfT = ArithmeticTypes[Arith];
8469 if (TypeOfT == S.Context.BoolTy) {
8470 if (Op == OO_MinusMinus)
8471 continue;
8472 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8473 continue;
8474 }
8475 addPlusPlusMinusMinusStyleOverloads(
8476 TypeOfT,
8477 VisibleTypeConversionsQuals.hasVolatile(),
8478 VisibleTypeConversionsQuals.hasRestrict());
8479 }
8480 }
8481
8482 // C++ [over.built]p5:
8483 //
8484 // For every pair (T, VQ), where T is a cv-qualified or
8485 // cv-unqualified object type, and VQ is either volatile or
8486 // empty, there exist candidate operator functions of the form
8487 //
8488 // T*VQ& operator++(T*VQ&);
8489 // T*VQ& operator--(T*VQ&);
8490 // T* operator++(T*VQ&, int);
8491 // T* operator--(T*VQ&, int);
8492 void addPlusPlusMinusMinusPointerOverloads() {
8493 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8494 // Skip pointer types that aren't pointers to object types.
8495 if (!PtrTy->getPointeeType()->isObjectType())
8496 continue;
8497
8498 addPlusPlusMinusMinusStyleOverloads(
8499 PtrTy,
8500 (!PtrTy.isVolatileQualified() &&
8501 VisibleTypeConversionsQuals.hasVolatile()),
8502 (!PtrTy.isRestrictQualified() &&
8503 VisibleTypeConversionsQuals.hasRestrict()));
8504 }
8505 }
8506
8507 // C++ [over.built]p6:
8508 // For every cv-qualified or cv-unqualified object type T, there
8509 // exist candidate operator functions of the form
8510 //
8511 // T& operator*(T*);
8512 //
8513 // C++ [over.built]p7:
8514 // For every function type T that does not have cv-qualifiers or a
8515 // ref-qualifier, there exist candidate operator functions of the form
8516 // T& operator*(T*);
8517 void addUnaryStarPointerOverloads() {
8518 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8519 QualType PointeeTy = ParamTy->getPointeeType();
8520 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8521 continue;
8522
8523 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8524 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8525 continue;
8526
8527 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8528 }
8529 }
8530
8531 // C++ [over.built]p9:
8532 // For every promoted arithmetic type T, there exist candidate
8533 // operator functions of the form
8534 //
8535 // T operator+(T);
8536 // T operator-(T);
8537 void addUnaryPlusOrMinusArithmeticOverloads() {
8538 if (!HasArithmeticOrEnumeralCandidateType)
8539 return;
8540
8541 for (unsigned Arith = FirstPromotedArithmeticType;
8542 Arith < LastPromotedArithmeticType; ++Arith) {
8543 QualType ArithTy = ArithmeticTypes[Arith];
8544 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8545 }
8546
8547 // Extension: We also add these operators for vector types.
8548 for (QualType VecTy : CandidateTypes[0].vector_types())
8549 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8550 }
8551
8552 // C++ [over.built]p8:
8553 // For every type T, there exist candidate operator functions of
8554 // the form
8555 //
8556 // T* operator+(T*);
8557 void addUnaryPlusPointerOverloads() {
8558 for (QualType ParamTy : CandidateTypes[0].pointer_types())
8559 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8560 }
8561
8562 // C++ [over.built]p10:
8563 // For every promoted integral type T, there exist candidate
8564 // operator functions of the form
8565 //
8566 // T operator~(T);
8567 void addUnaryTildePromotedIntegralOverloads() {
8568 if (!HasArithmeticOrEnumeralCandidateType)
8569 return;
8570
8571 for (unsigned Int = FirstPromotedIntegralType;
8572 Int < LastPromotedIntegralType; ++Int) {
8573 QualType IntTy = ArithmeticTypes[Int];
8574 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8575 }
8576
8577 // Extension: We also add this operator for vector types.
8578 for (QualType VecTy : CandidateTypes[0].vector_types())
8579 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8580 }
8581
8582 // C++ [over.match.oper]p16:
8583 // For every pointer to member type T or type std::nullptr_t, there
8584 // exist candidate operator functions of the form
8585 //
8586 // bool operator==(T,T);
8587 // bool operator!=(T,T);
8588 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8589 /// Set of (canonical) types that we've already handled.
8590 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8591
8592 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8593 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8594 // Don't add the same builtin candidate twice.
8595 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8596 continue;
8597
8598 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8599 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8600 }
8601
8602 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8603 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8604 if (AddedTypes.insert(NullPtrTy).second) {
8605 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8606 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8607 }
8608 }
8609 }
8610 }
8611
8612 // C++ [over.built]p15:
8613 //
8614 // For every T, where T is an enumeration type or a pointer type,
8615 // there exist candidate operator functions of the form
8616 //
8617 // bool operator<(T, T);
8618 // bool operator>(T, T);
8619 // bool operator<=(T, T);
8620 // bool operator>=(T, T);
8621 // bool operator==(T, T);
8622 // bool operator!=(T, T);
8623 // R operator<=>(T, T)
8624 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8625 // C++ [over.match.oper]p3:
8626 // [...]the built-in candidates include all of the candidate operator
8627 // functions defined in 13.6 that, compared to the given operator, [...]
8628 // do not have the same parameter-type-list as any non-template non-member
8629 // candidate.
8630 //
8631 // Note that in practice, this only affects enumeration types because there
8632 // aren't any built-in candidates of record type, and a user-defined operator
8633 // must have an operand of record or enumeration type. Also, the only other
8634 // overloaded operator with enumeration arguments, operator=,
8635 // cannot be overloaded for enumeration types, so this is the only place
8636 // where we must suppress candidates like this.
8637 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8638 UserDefinedBinaryOperators;
8639
8640 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8641 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8642 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8643 CEnd = CandidateSet.end();
8644 C != CEnd; ++C) {
8645 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8646 continue;
8647
8648 if (C->Function->isFunctionTemplateSpecialization())
8649 continue;
8650
8651 // We interpret "same parameter-type-list" as applying to the
8652 // "synthesized candidate, with the order of the two parameters
8653 // reversed", not to the original function.
8654 bool Reversed = C->isReversed();
8655 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8656 ->getType()
8657 .getUnqualifiedType();
8658 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8659 ->getType()
8660 .getUnqualifiedType();
8661
8662 // Skip if either parameter isn't of enumeral type.
8663 if (!FirstParamType->isEnumeralType() ||
8664 !SecondParamType->isEnumeralType())
8665 continue;
8666
8667 // Add this operator to the set of known user-defined operators.
8668 UserDefinedBinaryOperators.insert(
8669 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8670 S.Context.getCanonicalType(SecondParamType)));
8671 }
8672 }
8673 }
8674
8675 /// Set of (canonical) types that we've already handled.
8676 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8677
8678 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8679 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8680 // Don't add the same builtin candidate twice.
8681 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8682 continue;
8683 if (IsSpaceship && PtrTy->isFunctionPointerType())
8684 continue;
8685
8686 QualType ParamTypes[2] = {PtrTy, PtrTy};
8687 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8688 }
8689 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8690 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8691
8692 // Don't add the same builtin candidate twice, or if a user defined
8693 // candidate exists.
8694 if (!AddedTypes.insert(CanonType).second ||
8695 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8696 CanonType)))
8697 continue;
8698 QualType ParamTypes[2] = {EnumTy, EnumTy};
8699 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8700 }
8701 }
8702 }
8703
8704 // C++ [over.built]p13:
8705 //
8706 // For every cv-qualified or cv-unqualified object type T
8707 // there exist candidate operator functions of the form
8708 //
8709 // T* operator+(T*, ptrdiff_t);
8710 // T& operator[](T*, ptrdiff_t); [BELOW]
8711 // T* operator-(T*, ptrdiff_t);
8712 // T* operator+(ptrdiff_t, T*);
8713 // T& operator[](ptrdiff_t, T*); [BELOW]
8714 //
8715 // C++ [over.built]p14:
8716 //
8717 // For every T, where T is a pointer to object type, there
8718 // exist candidate operator functions of the form
8719 //
8720 // ptrdiff_t operator-(T, T);
8721 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8722 /// Set of (canonical) types that we've already handled.
8723 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8724
8725 for (int Arg = 0; Arg < 2; ++Arg) {
8726 QualType AsymmetricParamTypes[2] = {
8727 S.Context.getPointerDiffType(),
8728 S.Context.getPointerDiffType(),
8729 };
8730 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8731 QualType PointeeTy = PtrTy->getPointeeType();
8732 if (!PointeeTy->isObjectType())
8733 continue;
8734
8735 AsymmetricParamTypes[Arg] = PtrTy;
8736 if (Arg == 0 || Op == OO_Plus) {
8737 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8738 // T* operator+(ptrdiff_t, T*);
8739 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8740 }
8741 if (Op == OO_Minus) {
8742 // ptrdiff_t operator-(T, T);
8743 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8744 continue;
8745
8746 QualType ParamTypes[2] = {PtrTy, PtrTy};
8747 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8748 }
8749 }
8750 }
8751 }
8752
8753 // C++ [over.built]p12:
8754 //
8755 // For every pair of promoted arithmetic types L and R, there
8756 // exist candidate operator functions of the form
8757 //
8758 // LR operator*(L, R);
8759 // LR operator/(L, R);
8760 // LR operator+(L, R);
8761 // LR operator-(L, R);
8762 // bool operator<(L, R);
8763 // bool operator>(L, R);
8764 // bool operator<=(L, R);
8765 // bool operator>=(L, R);
8766 // bool operator==(L, R);
8767 // bool operator!=(L, R);
8768 //
8769 // where LR is the result of the usual arithmetic conversions
8770 // between types L and R.
8771 //
8772 // C++ [over.built]p24:
8773 //
8774 // For every pair of promoted arithmetic types L and R, there exist
8775 // candidate operator functions of the form
8776 //
8777 // LR operator?(bool, L, R);
8778 //
8779 // where LR is the result of the usual arithmetic conversions
8780 // between types L and R.
8781 // Our candidates ignore the first parameter.
8782 void addGenericBinaryArithmeticOverloads() {
8783 if (!HasArithmeticOrEnumeralCandidateType)
8784 return;
8785
8786 for (unsigned Left = FirstPromotedArithmeticType;
8787 Left < LastPromotedArithmeticType; ++Left) {
8788 for (unsigned Right = FirstPromotedArithmeticType;
8789 Right < LastPromotedArithmeticType; ++Right) {
8790 QualType LandR[2] = { ArithmeticTypes[Left],
8791 ArithmeticTypes[Right] };
8792 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8793 }
8794 }
8795
8796 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8797 // conditional operator for vector types.
8798 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8799 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8800 QualType LandR[2] = {Vec1Ty, Vec2Ty};
8801 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8802 }
8803 }
8804
8805 /// Add binary operator overloads for each candidate matrix type M1, M2:
8806 /// * (M1, M1) -> M1
8807 /// * (M1, M1.getElementType()) -> M1
8808 /// * (M2.getElementType(), M2) -> M2
8809 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8810 void addMatrixBinaryArithmeticOverloads() {
8811 if (!HasArithmeticOrEnumeralCandidateType)
8812 return;
8813
8814 for (QualType M1 : CandidateTypes[0].matrix_types()) {
8815 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8816 AddCandidate(M1, M1);
8817 }
8818
8819 for (QualType M2 : CandidateTypes[1].matrix_types()) {
8820 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8821 if (!CandidateTypes[0].containsMatrixType(M2))
8822 AddCandidate(M2, M2);
8823 }
8824 }
8825
8826 // C++2a [over.built]p14:
8827 //
8828 // For every integral type T there exists a candidate operator function
8829 // of the form
8830 //
8831 // std::strong_ordering operator<=>(T, T)
8832 //
8833 // C++2a [over.built]p15:
8834 //
8835 // For every pair of floating-point types L and R, there exists a candidate
8836 // operator function of the form
8837 //
8838 // std::partial_ordering operator<=>(L, R);
8839 //
8840 // FIXME: The current specification for integral types doesn't play nice with
8841 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8842 // comparisons. Under the current spec this can lead to ambiguity during
8843 // overload resolution. For example:
8844 //
8845 // enum A : int {a};
8846 // auto x = (a <=> (long)42);
8847 //
8848 // error: call is ambiguous for arguments 'A' and 'long'.
8849 // note: candidate operator<=>(int, int)
8850 // note: candidate operator<=>(long, long)
8851 //
8852 // To avoid this error, this function deviates from the specification and adds
8853 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8854 // arithmetic types (the same as the generic relational overloads).
8855 //
8856 // For now this function acts as a placeholder.
8857 void addThreeWayArithmeticOverloads() {
8858 addGenericBinaryArithmeticOverloads();
8859 }
8860
8861 // C++ [over.built]p17:
8862 //
8863 // For every pair of promoted integral types L and R, there
8864 // exist candidate operator functions of the form
8865 //
8866 // LR operator%(L, R);
8867 // LR operator&(L, R);
8868 // LR operator^(L, R);
8869 // LR operator|(L, R);
8870 // L operator<<(L, R);
8871 // L operator>>(L, R);
8872 //
8873 // where LR is the result of the usual arithmetic conversions
8874 // between types L and R.
8875 void addBinaryBitwiseArithmeticOverloads() {
8876 if (!HasArithmeticOrEnumeralCandidateType)
8877 return;
8878
8879 for (unsigned Left = FirstPromotedIntegralType;
8880 Left < LastPromotedIntegralType; ++Left) {
8881 for (unsigned Right = FirstPromotedIntegralType;
8882 Right < LastPromotedIntegralType; ++Right) {
8883 QualType LandR[2] = { ArithmeticTypes[Left],
8884 ArithmeticTypes[Right] };
8885 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8886 }
8887 }
8888 }
8889
8890 // C++ [over.built]p20:
8891 //
8892 // For every pair (T, VQ), where T is an enumeration or
8893 // pointer to member type and VQ is either volatile or
8894 // empty, there exist candidate operator functions of the form
8895 //
8896 // VQ T& operator=(VQ T&, T);
8897 void addAssignmentMemberPointerOrEnumeralOverloads() {
8898 /// Set of (canonical) types that we've already handled.
8899 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8900
8901 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8902 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8903 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8904 continue;
8905
8906 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8907 }
8908
8909 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8910 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8911 continue;
8912
8913 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8914 }
8915 }
8916 }
8917
8918 // C++ [over.built]p19:
8919 //
8920 // For every pair (T, VQ), where T is any type and VQ is either
8921 // volatile or empty, there exist candidate operator functions
8922 // of the form
8923 //
8924 // T*VQ& operator=(T*VQ&, T*);
8925 //
8926 // C++ [over.built]p21:
8927 //
8928 // For every pair (T, VQ), where T is a cv-qualified or
8929 // cv-unqualified object type and VQ is either volatile or
8930 // empty, there exist candidate operator functions of the form
8931 //
8932 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8933 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8934 void addAssignmentPointerOverloads(bool isEqualOp) {
8935 /// Set of (canonical) types that we've already handled.
8936 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8937
8938 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8939 // If this is operator=, keep track of the builtin candidates we added.
8940 if (isEqualOp)
8941 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8942 else if (!PtrTy->getPointeeType()->isObjectType())
8943 continue;
8944
8945 // non-volatile version
8946 QualType ParamTypes[2] = {
8947 S.Context.getLValueReferenceType(PtrTy),
8948 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8949 };
8950 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8951 /*IsAssignmentOperator=*/ isEqualOp);
8952
8953 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8954 VisibleTypeConversionsQuals.hasVolatile();
8955 if (NeedVolatile) {
8956 // volatile version
8957 ParamTypes[0] =
8958 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8959 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8960 /*IsAssignmentOperator=*/isEqualOp);
8961 }
8962
8963 if (!PtrTy.isRestrictQualified() &&
8964 VisibleTypeConversionsQuals.hasRestrict()) {
8965 // restrict version
8966 ParamTypes[0] =
8967 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8968 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8969 /*IsAssignmentOperator=*/isEqualOp);
8970
8971 if (NeedVolatile) {
8972 // volatile restrict version
8973 ParamTypes[0] =
8974 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8975 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8976 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8977 /*IsAssignmentOperator=*/isEqualOp);
8978 }
8979 }
8980 }
8981
8982 if (isEqualOp) {
8983 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8984 // Make sure we don't add the same candidate twice.
8985 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8986 continue;
8987
8988 QualType ParamTypes[2] = {
8989 S.Context.getLValueReferenceType(PtrTy),
8990 PtrTy,
8991 };
8992
8993 // non-volatile version
8994 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8995 /*IsAssignmentOperator=*/true);
8996
8997 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8998 VisibleTypeConversionsQuals.hasVolatile();
8999 if (NeedVolatile) {
9000 // volatile version
9001 ParamTypes[0] = S.Context.getLValueReferenceType(
9002 S.Context.getVolatileType(PtrTy));
9003 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9004 /*IsAssignmentOperator=*/true);
9005 }
9006
9007 if (!PtrTy.isRestrictQualified() &&
9008 VisibleTypeConversionsQuals.hasRestrict()) {
9009 // restrict version
9010 ParamTypes[0] = S.Context.getLValueReferenceType(
9011 S.Context.getRestrictType(PtrTy));
9012 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9013 /*IsAssignmentOperator=*/true);
9014
9015 if (NeedVolatile) {
9016 // volatile restrict version
9017 ParamTypes[0] =
9018 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9019 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9020 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9021 /*IsAssignmentOperator=*/true);
9022 }
9023 }
9024 }
9025 }
9026 }
9027
9028 // C++ [over.built]p18:
9029 //
9030 // For every triple (L, VQ, R), where L is an arithmetic type,
9031 // VQ is either volatile or empty, and R is a promoted
9032 // arithmetic type, there exist candidate operator functions of
9033 // the form
9034 //
9035 // VQ L& operator=(VQ L&, R);
9036 // VQ L& operator*=(VQ L&, R);
9037 // VQ L& operator/=(VQ L&, R);
9038 // VQ L& operator+=(VQ L&, R);
9039 // VQ L& operator-=(VQ L&, R);
9040 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9041 if (!HasArithmeticOrEnumeralCandidateType)
9042 return;
9043
9044 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9045 for (unsigned Right = FirstPromotedArithmeticType;
9046 Right < LastPromotedArithmeticType; ++Right) {
9047 QualType ParamTypes[2];
9048 ParamTypes[1] = ArithmeticTypes[Right];
9049 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9050 S, ArithmeticTypes[Left], Args[0]);
9051
9052 forAllQualifierCombinations(
9053 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9054 ParamTypes[0] =
9055 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9056 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9057 /*IsAssignmentOperator=*/isEqualOp);
9058 });
9059 }
9060 }
9061
9062 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9063 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9064 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9065 QualType ParamTypes[2];
9066 ParamTypes[1] = Vec2Ty;
9067 // Add this built-in operator as a candidate (VQ is empty).
9068 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9069 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9070 /*IsAssignmentOperator=*/isEqualOp);
9071
9072 // Add this built-in operator as a candidate (VQ is 'volatile').
9073 if (VisibleTypeConversionsQuals.hasVolatile()) {
9074 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9075 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9076 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9077 /*IsAssignmentOperator=*/isEqualOp);
9078 }
9079 }
9080 }
9081
9082 // C++ [over.built]p22:
9083 //
9084 // For every triple (L, VQ, R), where L is an integral type, VQ
9085 // is either volatile or empty, and R is a promoted integral
9086 // type, there exist candidate operator functions of the form
9087 //
9088 // VQ L& operator%=(VQ L&, R);
9089 // VQ L& operator<<=(VQ L&, R);
9090 // VQ L& operator>>=(VQ L&, R);
9091 // VQ L& operator&=(VQ L&, R);
9092 // VQ L& operator^=(VQ L&, R);
9093 // VQ L& operator|=(VQ L&, R);
9094 void addAssignmentIntegralOverloads() {
9095 if (!HasArithmeticOrEnumeralCandidateType)
9096 return;
9097
9098 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9099 for (unsigned Right = FirstPromotedIntegralType;
9100 Right < LastPromotedIntegralType; ++Right) {
9101 QualType ParamTypes[2];
9102 ParamTypes[1] = ArithmeticTypes[Right];
9103 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9104 S, ArithmeticTypes[Left], Args[0]);
9105
9106 forAllQualifierCombinations(
9107 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9108 ParamTypes[0] =
9109 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9110 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9111 });
9112 }
9113 }
9114 }
9115
9116 // C++ [over.operator]p23:
9117 //
9118 // There also exist candidate operator functions of the form
9119 //
9120 // bool operator!(bool);
9121 // bool operator&&(bool, bool);
9122 // bool operator||(bool, bool);
9123 void addExclaimOverload() {
9124 QualType ParamTy = S.Context.BoolTy;
9125 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9126 /*IsAssignmentOperator=*/false,
9127 /*NumContextualBoolArguments=*/1);
9128 }
9129 void addAmpAmpOrPipePipeOverload() {
9130 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9131 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9132 /*IsAssignmentOperator=*/false,
9133 /*NumContextualBoolArguments=*/2);
9134 }
9135
9136 // C++ [over.built]p13:
9137 //
9138 // For every cv-qualified or cv-unqualified object type T there
9139 // exist candidate operator functions of the form
9140 //
9141 // T* operator+(T*, ptrdiff_t); [ABOVE]
9142 // T& operator[](T*, ptrdiff_t);
9143 // T* operator-(T*, ptrdiff_t); [ABOVE]
9144 // T* operator+(ptrdiff_t, T*); [ABOVE]
9145 // T& operator[](ptrdiff_t, T*);
9146 void addSubscriptOverloads() {
9147 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9148 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9149 QualType PointeeType = PtrTy->getPointeeType();
9150 if (!PointeeType->isObjectType())
9151 continue;
9152
9153 // T& operator[](T*, ptrdiff_t)
9154 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9155 }
9156
9157 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9158 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9159 QualType PointeeType = PtrTy->getPointeeType();
9160 if (!PointeeType->isObjectType())
9161 continue;
9162
9163 // T& operator[](ptrdiff_t, T*)
9164 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9165 }
9166 }
9167
9168 // C++ [over.built]p11:
9169 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9170 // C1 is the same type as C2 or is a derived class of C2, T is an object
9171 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9172 // there exist candidate operator functions of the form
9173 //
9174 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9175 //
9176 // where CV12 is the union of CV1 and CV2.
9177 void addArrowStarOverloads() {
9178 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9179 QualType C1Ty = PtrTy;
9180 QualType C1;
9181 QualifierCollector Q1;
9182 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9183 if (!isa<RecordType>(C1))
9184 continue;
9185 // heuristic to reduce number of builtin candidates in the set.
9186 // Add volatile/restrict version only if there are conversions to a
9187 // volatile/restrict type.
9188 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9189 continue;
9190 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9191 continue;
9192 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9193 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9194 QualType C2 = QualType(mptr->getClass(), 0);
9195 C2 = C2.getUnqualifiedType();
9196 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9197 break;
9198 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9199 // build CV12 T&
9200 QualType T = mptr->getPointeeType();
9201 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9202 T.isVolatileQualified())
9203 continue;
9204 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9205 T.isRestrictQualified())
9206 continue;
9207 T = Q1.apply(S.Context, T);
9208 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9209 }
9210 }
9211 }
9212
9213 // Note that we don't consider the first argument, since it has been
9214 // contextually converted to bool long ago. The candidates below are
9215 // therefore added as binary.
9216 //
9217 // C++ [over.built]p25:
9218 // For every type T, where T is a pointer, pointer-to-member, or scoped
9219 // enumeration type, there exist candidate operator functions of the form
9220 //
9221 // T operator?(bool, T, T);
9222 //
9223 void addConditionalOperatorOverloads() {
9224 /// Set of (canonical) types that we've already handled.
9225 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9226
9227 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9228 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9229 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9230 continue;
9231
9232 QualType ParamTypes[2] = {PtrTy, PtrTy};
9233 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9234 }
9235
9236 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9237 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9238 continue;
9239
9240 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9241 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9242 }
9243
9244 if (S.getLangOpts().CPlusPlus11) {
9245 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9246 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9247 continue;
9248
9249 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9250 continue;
9251
9252 QualType ParamTypes[2] = {EnumTy, EnumTy};
9253 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9254 }
9255 }
9256 }
9257 }
9258};
9259
9260} // end anonymous namespace
9261
9262/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9263/// operator overloads to the candidate set (C++ [over.built]), based
9264/// on the operator @p Op and the arguments given. For example, if the
9265/// operator is a binary '+', this routine might add "int
9266/// operator+(int, int)" to cover integer addition.
9267void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9268 SourceLocation OpLoc,
9269 ArrayRef<Expr *> Args,
9270 OverloadCandidateSet &CandidateSet) {
9271 // Find all of the types that the arguments can convert to, but only
9272 // if the operator we're looking at has built-in operator candidates
9273 // that make use of these types. Also record whether we encounter non-record
9274 // candidate types or either arithmetic or enumeral candidate types.
9275 QualifiersAndAtomic VisibleTypeConversionsQuals;
9276 VisibleTypeConversionsQuals.addConst();
9277 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9278 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9279 if (Args[ArgIdx]->getType()->isAtomicType())
9280 VisibleTypeConversionsQuals.addAtomic();
9281 }
9282
9283 bool HasNonRecordCandidateType = false;
9284 bool HasArithmeticOrEnumeralCandidateType = false;
9285 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9286 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9287 CandidateTypes.emplace_back(*this);
9288 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9289 OpLoc,
9290 true,
9291 (Op == OO_Exclaim ||
9292 Op == OO_AmpAmp ||
9293 Op == OO_PipePipe),
9294 VisibleTypeConversionsQuals);
9295 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9296 CandidateTypes[ArgIdx].hasNonRecordTypes();
9297 HasArithmeticOrEnumeralCandidateType =
9298 HasArithmeticOrEnumeralCandidateType ||
9299 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9300 }
9301
9302 // Exit early when no non-record types have been added to the candidate set
9303 // for any of the arguments to the operator.
9304 //
9305 // We can't exit early for !, ||, or &&, since there we have always have
9306 // 'bool' overloads.
9307 if (!HasNonRecordCandidateType &&
9308 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9309 return;
9310
9311 // Setup an object to manage the common state for building overloads.
9312 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9313 VisibleTypeConversionsQuals,
9314 HasArithmeticOrEnumeralCandidateType,
9315 CandidateTypes, CandidateSet);
9316
9317 // Dispatch over the operation to add in only those overloads which apply.
9318 switch (Op) {
9319 case OO_None:
9320 case NUM_OVERLOADED_OPERATORS:
9321 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "clang/lib/Sema/SemaOverload.cpp", 9321)
;
9322
9323 case OO_New:
9324 case OO_Delete:
9325 case OO_Array_New:
9326 case OO_Array_Delete:
9327 case OO_Call:
9328 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "clang/lib/Sema/SemaOverload.cpp", 9329)
9329 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "clang/lib/Sema/SemaOverload.cpp", 9329)
;
9330
9331 case OO_Comma:
9332 case OO_Arrow:
9333 case OO_Coawait:
9334 // C++ [over.match.oper]p3:
9335 // -- For the operator ',', the unary operator '&', the
9336 // operator '->', or the operator 'co_await', the
9337 // built-in candidates set is empty.
9338 break;
9339
9340 case OO_Plus: // '+' is either unary or binary
9341 if (Args.size() == 1)
9342 OpBuilder.addUnaryPlusPointerOverloads();
9343 [[fallthrough]];
9344
9345 case OO_Minus: // '-' is either unary or binary
9346 if (Args.size() == 1) {
9347 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9348 } else {
9349 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9350 OpBuilder.addGenericBinaryArithmeticOverloads();
9351 OpBuilder.addMatrixBinaryArithmeticOverloads();
9352 }
9353 break;
9354
9355 case OO_Star: // '*' is either unary or binary
9356 if (Args.size() == 1)
9357 OpBuilder.addUnaryStarPointerOverloads();
9358 else {
9359 OpBuilder.addGenericBinaryArithmeticOverloads();
9360 OpBuilder.addMatrixBinaryArithmeticOverloads();
9361 }
9362 break;
9363
9364 case OO_Slash:
9365 OpBuilder.addGenericBinaryArithmeticOverloads();
9366 break;
9367
9368 case OO_PlusPlus:
9369 case OO_MinusMinus:
9370 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9371 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9372 break;
9373
9374 case OO_EqualEqual:
9375 case OO_ExclaimEqual:
9376 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9377 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9378 OpBuilder.addGenericBinaryArithmeticOverloads();
9379 break;
9380
9381 case OO_Less:
9382 case OO_Greater:
9383 case OO_LessEqual:
9384 case OO_GreaterEqual:
9385 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9386 OpBuilder.addGenericBinaryArithmeticOverloads();
9387 break;
9388
9389 case OO_Spaceship:
9390 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9391 OpBuilder.addThreeWayArithmeticOverloads();
9392 break;
9393
9394 case OO_Percent:
9395 case OO_Caret:
9396 case OO_Pipe:
9397 case OO_LessLess:
9398 case OO_GreaterGreater:
9399 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9400 break;
9401
9402 case OO_Amp: // '&' is either unary or binary
9403 if (Args.size() == 1)
9404 // C++ [over.match.oper]p3:
9405 // -- For the operator ',', the unary operator '&', or the
9406 // operator '->', the built-in candidates set is empty.
9407 break;
9408
9409 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9410 break;
9411
9412 case OO_Tilde:
9413 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9414 break;
9415
9416 case OO_Equal:
9417 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9418 [[fallthrough]];
9419
9420 case OO_PlusEqual:
9421 case OO_MinusEqual:
9422 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9423 [[fallthrough]];
9424
9425 case OO_StarEqual:
9426 case OO_SlashEqual:
9427 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9428 break;
9429
9430 case OO_PercentEqual:
9431 case OO_LessLessEqual:
9432 case OO_GreaterGreaterEqual:
9433 case OO_AmpEqual:
9434 case OO_CaretEqual:
9435 case OO_PipeEqual:
9436 OpBuilder.addAssignmentIntegralOverloads();
9437 break;
9438
9439 case OO_Exclaim:
9440 OpBuilder.addExclaimOverload();
9441 break;
9442
9443 case OO_AmpAmp:
9444 case OO_PipePipe:
9445 OpBuilder.addAmpAmpOrPipePipeOverload();
9446 break;
9447
9448 case OO_Subscript:
9449 if (Args.size() == 2)
9450 OpBuilder.addSubscriptOverloads();
9451 break;
9452
9453 case OO_ArrowStar:
9454 OpBuilder.addArrowStarOverloads();
9455 break;
9456
9457 case OO_Conditional:
9458 OpBuilder.addConditionalOperatorOverloads();
9459 OpBuilder.addGenericBinaryArithmeticOverloads();
9460 break;
9461 }
9462}
9463
9464/// Add function candidates found via argument-dependent lookup
9465/// to the set of overloading candidates.
9466///
9467/// This routine performs argument-dependent name lookup based on the
9468/// given function name (which may also be an operator name) and adds
9469/// all of the overload candidates found by ADL to the overload
9470/// candidate set (C++ [basic.lookup.argdep]).
9471void
9472Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9473 SourceLocation Loc,
9474 ArrayRef<Expr *> Args,
9475 TemplateArgumentListInfo *ExplicitTemplateArgs,
9476 OverloadCandidateSet& CandidateSet,
9477 bool PartialOverloading) {
9478 ADLResult Fns;
9479
9480 // FIXME: This approach for uniquing ADL results (and removing
9481 // redundant candidates from the set) relies on pointer-equality,
9482 // which means we need to key off the canonical decl. However,
9483 // always going back to the canonical decl might not get us the
9484 // right set of default arguments. What default arguments are
9485 // we supposed to consider on ADL candidates, anyway?
9486
9487 // FIXME: Pass in the explicit template arguments?
9488 ArgumentDependentLookup(Name, Loc, Args, Fns);
9489
9490 // Erase all of the candidates we already knew about.
9491 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9492 CandEnd = CandidateSet.end();
9493 Cand != CandEnd; ++Cand)
9494 if (Cand->Function) {
9495 Fns.erase(Cand->Function);
9496 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9497 Fns.erase(FunTmpl);
9498 }
9499
9500 // For each of the ADL candidates we found, add it to the overload
9501 // set.
9502 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9503 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9504
9505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9506 if (ExplicitTemplateArgs)
9507 continue;
9508
9509 AddOverloadCandidate(
9510 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9511 PartialOverloading, /*AllowExplicit=*/true,
9512 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9513 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9514 AddOverloadCandidate(
9515 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9516 /*SuppressUserConversions=*/false, PartialOverloading,
9517 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9518 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9519 }
9520 } else {
9521 auto *FTD = cast<FunctionTemplateDecl>(*I);
9522 AddTemplateOverloadCandidate(
9523 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9524 /*SuppressUserConversions=*/false, PartialOverloading,
9525 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9526 if (CandidateSet.getRewriteInfo().shouldAddReversed(
9527 Context, FTD->getTemplatedDecl())) {
9528 AddTemplateOverloadCandidate(
9529 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9530 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9531 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9532 OverloadCandidateParamOrder::Reversed);
9533 }
9534 }
9535 }
9536}
9537
9538namespace {
9539enum class Comparison { Equal, Better, Worse };
9540}
9541
9542/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9543/// overload resolution.
9544///
9545/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9546/// Cand1's first N enable_if attributes have precisely the same conditions as
9547/// Cand2's first N enable_if attributes (where N = the number of enable_if
9548/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9549///
9550/// Note that you can have a pair of candidates such that Cand1's enable_if
9551/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9552/// worse than Cand1's.
9553static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9554 const FunctionDecl *Cand2) {
9555 // Common case: One (or both) decls don't have enable_if attrs.
9556 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9557 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9558 if (!Cand1Attr || !Cand2Attr) {
9559 if (Cand1Attr == Cand2Attr)
9560 return Comparison::Equal;
9561 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9562 }
9563
9564 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9565 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9566
9567 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9568 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9569 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9570 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9571
9572 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9573 // has fewer enable_if attributes than Cand2, and vice versa.
9574 if (!Cand1A)
9575 return Comparison::Worse;
9576 if (!Cand2A)
9577 return Comparison::Better;
9578
9579 Cand1ID.clear();
9580 Cand2ID.clear();
9581
9582 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9583 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9584 if (Cand1ID != Cand2ID)
9585 return Comparison::Worse;
9586 }
9587
9588 return Comparison::Equal;
9589}
9590
9591static Comparison
9592isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9593 const OverloadCandidate &Cand2) {
9594 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9595 !Cand2.Function->isMultiVersion())
9596 return Comparison::Equal;
9597
9598 // If both are invalid, they are equal. If one of them is invalid, the other
9599 // is better.
9600 if (Cand1.Function->isInvalidDecl()) {
9601 if (Cand2.Function->isInvalidDecl())
9602 return Comparison::Equal;
9603 return Comparison::Worse;
9604 }
9605 if (Cand2.Function->isInvalidDecl())
9606 return Comparison::Better;
9607
9608 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9609 // cpu_dispatch, else arbitrarily based on the identifiers.
9610 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9611 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9612 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9613 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9614
9615 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9616 return Comparison::Equal;
9617
9618 if (Cand1CPUDisp && !Cand2CPUDisp)
9619 return Comparison::Better;
9620 if (Cand2CPUDisp && !Cand1CPUDisp)
9621 return Comparison::Worse;
9622
9623 if (Cand1CPUSpec && Cand2CPUSpec) {
9624 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9625 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9626 ? Comparison::Better
9627 : Comparison::Worse;
9628
9629 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9630 FirstDiff = std::mismatch(
9631 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9632 Cand2CPUSpec->cpus_begin(),
9633 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9634 return LHS->getName() == RHS->getName();
9635 });
9636
9637 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "clang/lib/Sema/SemaOverload.cpp", 9639, __extension__ __PRETTY_FUNCTION__
))
9638 "Two different cpu-specific versions should not have the same "(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "clang/lib/Sema/SemaOverload.cpp", 9639, __extension__ __PRETTY_FUNCTION__
))
9639 "identifier list, otherwise they'd be the same decl!")(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "clang/lib/Sema/SemaOverload.cpp", 9639, __extension__ __PRETTY_FUNCTION__
))
;
9640 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9641 ? Comparison::Better
9642 : Comparison::Worse;
9643 }
9644 llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch"
, "clang/lib/Sema/SemaOverload.cpp", 9644)
;
9645}
9646
9647/// Compute the type of the implicit object parameter for the given function,
9648/// if any. Returns None if there is no implicit object parameter, and a null
9649/// QualType if there is a 'matches anything' implicit object parameter.
9650static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9651 const FunctionDecl *F) {
9652 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9653 return llvm::None;
9654
9655 auto *M = cast<CXXMethodDecl>(F);
9656 // Static member functions' object parameters match all types.
9657 if (M->isStatic())
9658 return QualType();
9659
9660 QualType T = M->getThisObjectType();
9661 if (M->getRefQualifier() == RQ_RValue)
9662 return Context.getRValueReferenceType(T);
9663 return Context.getLValueReferenceType(T);
9664}
9665
9666static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9667 const FunctionDecl *F2, unsigned NumParams) {
9668 if (declaresSameEntity(F1, F2))
9669 return true;
9670
9671 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9672 if (First) {
9673 if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9674 return *T;
9675 }
9676 assert(I < F->getNumParams())(static_cast <bool> (I < F->getNumParams()) ? void
(0) : __assert_fail ("I < F->getNumParams()", "clang/lib/Sema/SemaOverload.cpp"
, 9676, __extension__ __PRETTY_FUNCTION__))
;
9677 return F->getParamDecl(I++)->getType();
9678 };
9679
9680 unsigned I1 = 0, I2 = 0;
9681 for (unsigned I = 0; I != NumParams; ++I) {
9682 QualType T1 = NextParam(F1, I1, I == 0);
9683 QualType T2 = NextParam(F2, I2, I == 0);
9684 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types")(static_cast <bool> (!T1.isNull() && !T2.isNull
() && "Unexpected null param types") ? void (0) : __assert_fail
("!T1.isNull() && !T2.isNull() && \"Unexpected null param types\""
, "clang/lib/Sema/SemaOverload.cpp", 9684, __extension__ __PRETTY_FUNCTION__
))
;
9685 if (!Context.hasSameUnqualifiedType(T1, T2))
9686 return false;
9687 }
9688 return true;
9689}
9690
9691/// We're allowed to use constraints partial ordering only if the candidates
9692/// have the same parameter types:
9693/// [temp.func.order]p6.2.2 [...] or if the function parameters that
9694/// positionally correspond between the two templates are not of the same type,
9695/// neither template is more specialized than the other.
9696/// [over.match.best]p2.6
9697/// F1 and F2 are non-template functions with the same parameter-type-lists,
9698/// and F1 is more constrained than F2 [...]
9699static bool canCompareFunctionConstraints(Sema &S,
9700 const OverloadCandidate &Cand1,
9701 const OverloadCandidate &Cand2) {
9702 // FIXME: Per P2113R0 we also need to compare the template parameter lists
9703 // when comparing template functions.
9704 if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
9705 Cand2.Function->hasPrototype()) {
9706 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9707 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9708 if (PT1->getNumParams() == PT2->getNumParams() &&
9709 PT1->isVariadic() == PT2->isVariadic() &&
9710 S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9711 Cand1.isReversed() ^ Cand2.isReversed()))
9712 return true;
9713 }
9714 return false;
9715}
9716
9717/// isBetterOverloadCandidate - Determines whether the first overload
9718/// candidate is a better candidate than the second (C++ 13.3.3p1).
9719bool clang::isBetterOverloadCandidate(
9720 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9721 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9722 // Define viable functions to be better candidates than non-viable
9723 // functions.
9724 if (!Cand2.Viable)
9725 return Cand1.Viable;
9726 else if (!Cand1.Viable)
9727 return false;
9728
9729 // [CUDA] A function with 'never' preference is marked not viable, therefore
9730 // is never shown up here. The worst preference shown up here is 'wrong side',
9731 // e.g. an H function called by a HD function in device compilation. This is
9732 // valid AST as long as the HD function is not emitted, e.g. it is an inline
9733 // function which is called only by an H function. A deferred diagnostic will
9734 // be triggered if it is emitted. However a wrong-sided function is still
9735 // a viable candidate here.
9736 //
9737 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9738 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9739 // can be emitted, Cand1 is not better than Cand2. This rule should have
9740 // precedence over other rules.
9741 //
9742 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9743 // other rules should be used to determine which is better. This is because
9744 // host/device based overloading resolution is mostly for determining
9745 // viability of a function. If two functions are both viable, other factors
9746 // should take precedence in preference, e.g. the standard-defined preferences
9747 // like argument conversion ranks or enable_if partial-ordering. The
9748 // preference for pass-object-size parameters is probably most similar to a
9749 // type-based-overloading decision and so should take priority.
9750 //
9751 // If other rules cannot determine which is better, CUDA preference will be
9752 // used again to determine which is better.
9753 //
9754 // TODO: Currently IdentifyCUDAPreference does not return correct values
9755 // for functions called in global variable initializers due to missing
9756 // correct context about device/host. Therefore we can only enforce this
9757 // rule when there is a caller. We should enforce this rule for functions
9758 // in global variable initializers once proper context is added.
9759 //
9760 // TODO: We can only enable the hostness based overloading resolution when
9761 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9762 // overloading resolution diagnostics.
9763 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9764 S.getLangOpts().GPUExcludeWrongSideOverloads) {
9765 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9766 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9767 bool IsCand1ImplicitHD =
9768 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9769 bool IsCand2ImplicitHD =
9770 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9771 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9772 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9773 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never)(static_cast <bool> (P1 != Sema::CFP_Never && P2
!= Sema::CFP_Never) ? void (0) : __assert_fail ("P1 != Sema::CFP_Never && P2 != Sema::CFP_Never"
, "clang/lib/Sema/SemaOverload.cpp", 9773, __extension__ __PRETTY_FUNCTION__
))
;
9774 // The implicit HD function may be a function in a system header which
9775 // is forced by pragma. In device compilation, if we prefer HD candidates
9776 // over wrong-sided candidates, overloading resolution may change, which
9777 // may result in non-deferrable diagnostics. As a workaround, we let
9778 // implicit HD candidates take equal preference as wrong-sided candidates.
9779 // This will preserve the overloading resolution.
9780 // TODO: We still need special handling of implicit HD functions since
9781 // they may incur other diagnostics to be deferred. We should make all
9782 // host/device related diagnostics deferrable and remove special handling
9783 // of implicit HD functions.
9784 auto EmitThreshold =
9785 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9786 (IsCand1ImplicitHD || IsCand2ImplicitHD))
9787 ? Sema::CFP_Never
9788 : Sema::CFP_WrongSide;
9789 auto Cand1Emittable = P1 > EmitThreshold;
9790 auto Cand2Emittable = P2 > EmitThreshold;
9791 if (Cand1Emittable && !Cand2Emittable)
9792 return true;
9793 if (!Cand1Emittable && Cand2Emittable)
9794 return false;
9795 }
9796 }
9797
9798 // C++ [over.match.best]p1: (Changed in C++2b)
9799 //
9800 // -- if F is a static member function, ICS1(F) is defined such
9801 // that ICS1(F) is neither better nor worse than ICS1(G) for
9802 // any function G, and, symmetrically, ICS1(G) is neither
9803 // better nor worse than ICS1(F).
9804 unsigned StartArg = 0;
9805 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9806 StartArg = 1;
9807
9808 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9809 // We don't allow incompatible pointer conversions in C++.
9810 if (!S.getLangOpts().CPlusPlus)
9811 return ICS.isStandard() &&
9812 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9813
9814 // The only ill-formed conversion we allow in C++ is the string literal to
9815 // char* conversion, which is only considered ill-formed after C++11.
9816 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9817 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9818 };
9819
9820 // Define functions that don't require ill-formed conversions for a given
9821 // argument to be better candidates than functions that do.
9822 unsigned NumArgs = Cand1.Conversions.size();
9823 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")(static_cast <bool> (Cand2.Conversions.size() == NumArgs
&& "Overload candidate mismatch") ? void (0) : __assert_fail
("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "clang/lib/Sema/SemaOverload.cpp", 9823, __extension__ __PRETTY_FUNCTION__
))
;
9824 bool HasBetterConversion = false;
9825 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9826 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9827 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9828 if (Cand1Bad != Cand2Bad) {
9829 if (Cand1Bad)
9830 return false;
9831 HasBetterConversion = true;
9832 }
9833 }
9834
9835 if (HasBetterConversion)
9836 return true;
9837
9838 // C++ [over.match.best]p1:
9839 // A viable function F1 is defined to be a better function than another
9840 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9841 // conversion sequence than ICSi(F2), and then...
9842 bool HasWorseConversion = false;
9843 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9844 switch (CompareImplicitConversionSequences(S, Loc,
9845 Cand1.Conversions[ArgIdx],
9846 Cand2.Conversions[ArgIdx])) {
9847 case ImplicitConversionSequence::Better:
9848 // Cand1 has a better conversion sequence.
9849 HasBetterConversion = true;
9850 break;
9851
9852 case ImplicitConversionSequence::Worse:
9853 if (Cand1.Function && Cand2.Function &&
9854 Cand1.isReversed() != Cand2.isReversed() &&
9855 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9856 NumArgs)) {
9857 // Work around large-scale breakage caused by considering reversed
9858 // forms of operator== in C++20:
9859 //
9860 // When comparing a function against a reversed function with the same
9861 // parameter types, if we have a better conversion for one argument and
9862 // a worse conversion for the other, the implicit conversion sequences
9863 // are treated as being equally good.
9864 //
9865 // This prevents a comparison function from being considered ambiguous
9866 // with a reversed form that is written in the same way.
9867 //
9868 // We diagnose this as an extension from CreateOverloadedBinOp.
9869 HasWorseConversion = true;
9870 break;
9871 }
9872
9873 // Cand1 can't be better than Cand2.
9874 return false;
9875
9876 case ImplicitConversionSequence::Indistinguishable:
9877 // Do nothing.
9878 break;
9879 }
9880 }
9881
9882 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9883 // ICSj(F2), or, if not that,
9884 if (HasBetterConversion && !HasWorseConversion)
9885 return true;
9886
9887 // -- the context is an initialization by user-defined conversion
9888 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9889 // from the return type of F1 to the destination type (i.e.,
9890 // the type of the entity being initialized) is a better
9891 // conversion sequence than the standard conversion sequence
9892 // from the return type of F2 to the destination type.
9893 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9894 Cand1.Function && Cand2.Function &&
9895 isa<CXXConversionDecl>(Cand1.Function) &&
9896 isa<CXXConversionDecl>(Cand2.Function)) {
9897 // First check whether we prefer one of the conversion functions over the
9898 // other. This only distinguishes the results in non-standard, extension
9899 // cases such as the conversion from a lambda closure type to a function
9900 // pointer or block.
9901 ImplicitConversionSequence::CompareKind Result =
9902 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9903 if (Result == ImplicitConversionSequence::Indistinguishable)
9904 Result = CompareStandardConversionSequences(S, Loc,
9905 Cand1.FinalConversion,
9906 Cand2.FinalConversion);
9907
9908 if (Result != ImplicitConversionSequence::Indistinguishable)
9909 return Result == ImplicitConversionSequence::Better;
9910
9911 // FIXME: Compare kind of reference binding if conversion functions
9912 // convert to a reference type used in direct reference binding, per
9913 // C++14 [over.match.best]p1 section 2 bullet 3.
9914 }
9915
9916 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9917 // as combined with the resolution to CWG issue 243.
9918 //
9919 // When the context is initialization by constructor ([over.match.ctor] or
9920 // either phase of [over.match.list]), a constructor is preferred over
9921 // a conversion function.
9922 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9923 Cand1.Function && Cand2.Function &&
9924 isa<CXXConstructorDecl>(Cand1.Function) !=
9925 isa<CXXConstructorDecl>(Cand2.Function))
9926 return isa<CXXConstructorDecl>(Cand1.Function);
9927
9928 // -- F1 is a non-template function and F2 is a function template
9929 // specialization, or, if not that,
9930 bool Cand1IsSpecialization = Cand1.Function &&
9931 Cand1.Function->getPrimaryTemplate();
9932 bool Cand2IsSpecialization = Cand2.Function &&
9933 Cand2.Function->getPrimaryTemplate();
9934 if (Cand1IsSpecialization != Cand2IsSpecialization)
9935 return Cand2IsSpecialization;
9936
9937 // -- F1 and F2 are function template specializations, and the function
9938 // template for F1 is more specialized than the template for F2
9939 // according to the partial ordering rules described in 14.5.5.2, or,
9940 // if not that,
9941 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9942 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9943 Cand1.Function->getPrimaryTemplate(),
9944 Cand2.Function->getPrimaryTemplate(), Loc,
9945 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9946 : TPOC_Call,
9947 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9948 Cand1.isReversed() ^ Cand2.isReversed(),
9949 canCompareFunctionConstraints(S, Cand1, Cand2)))
9950 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9951 }
9952
9953 // -— F1 and F2 are non-template functions with the same
9954 // parameter-type-lists, and F1 is more constrained than F2 [...],
9955 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
9956 canCompareFunctionConstraints(S, Cand1, Cand2)) {
9957 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9958 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9959 if (RC1 && RC2) {
9960 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9961 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2},
9962 AtLeastAsConstrained1) ||
9963 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1},
9964 AtLeastAsConstrained2))
9965 return false;
9966 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9967 return AtLeastAsConstrained1;
9968 } else if (RC1 || RC2) {
9969 return RC1 != nullptr;
9970 }
9971 }
9972
9973 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9974 // class B of D, and for all arguments the corresponding parameters of
9975 // F1 and F2 have the same type.
9976 // FIXME: Implement the "all parameters have the same type" check.
9977 bool Cand1IsInherited =
9978 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9979 bool Cand2IsInherited =
9980 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9981 if (Cand1IsInherited != Cand2IsInherited)
9982 return Cand2IsInherited;
9983 else if (Cand1IsInherited) {
9984 assert(Cand2IsInherited)(static_cast <bool> (Cand2IsInherited) ? void (0) : __assert_fail
("Cand2IsInherited", "clang/lib/Sema/SemaOverload.cpp", 9984
, __extension__ __PRETTY_FUNCTION__))
;
9985 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9986 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9987 if (Cand1Class->isDerivedFrom(Cand2Class))
9988 return true;
9989 if (Cand2Class->isDerivedFrom(Cand1Class))
9990 return false;
9991 // Inherited from sibling base classes: still ambiguous.
9992 }
9993
9994 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9995 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9996 // with reversed order of parameters and F1 is not
9997 //
9998 // We rank reversed + different operator as worse than just reversed, but
9999 // that comparison can never happen, because we only consider reversing for
10000 // the maximally-rewritten operator (== or <=>).
10001 if (Cand1.RewriteKind != Cand2.RewriteKind)
10002 return Cand1.RewriteKind < Cand2.RewriteKind;
10003
10004 // Check C++17 tie-breakers for deduction guides.
10005 {
10006 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10007 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10008 if (Guide1 && Guide2) {
10009 // -- F1 is generated from a deduction-guide and F2 is not
10010 if (Guide1->isImplicit() != Guide2->isImplicit())
10011 return Guide2->isImplicit();
10012
10013 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10014 if (Guide1->isCopyDeductionCandidate())
10015 return true;
10016 }
10017 }
10018
10019 // Check for enable_if value-based overload resolution.
10020 if (Cand1.Function && Cand2.Function) {
10021 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10022 if (Cmp != Comparison::Equal)
10023 return Cmp == Comparison::Better;
10024 }
10025
10026 bool HasPS1 = Cand1.Function != nullptr &&
10027 functionHasPassObjectSizeParams(Cand1.Function);
10028 bool HasPS2 = Cand2.Function != nullptr &&
10029 functionHasPassObjectSizeParams(Cand2.Function);
10030 if (HasPS1 != HasPS2 && HasPS1)
10031 return true;
10032
10033 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10034 if (MV == Comparison::Better)
10035 return true;
10036 if (MV == Comparison::Worse)
10037 return false;
10038
10039 // If other rules cannot determine which is better, CUDA preference is used
10040 // to determine which is better.
10041 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10042 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10043 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10044 S.IdentifyCUDAPreference(Caller, Cand2.Function);
10045 }
10046
10047 // General member function overloading is handled above, so this only handles
10048 // constructors with address spaces.
10049 // This only handles address spaces since C++ has no other
10050 // qualifier that can be used with constructors.
10051 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10052 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10053 if (CD1 && CD2) {
10054 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10055 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10056 if (AS1 != AS2) {
10057 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10058 return true;
10059 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10060 return false;
10061 }
10062 }
10063
10064 return false;
10065}
10066
10067/// Determine whether two declarations are "equivalent" for the purposes of
10068/// name lookup and overload resolution. This applies when the same internal/no
10069/// linkage entity is defined by two modules (probably by textually including
10070/// the same header). In such a case, we don't consider the declarations to
10071/// declare the same entity, but we also don't want lookups with both
10072/// declarations visible to be ambiguous in some cases (this happens when using
10073/// a modularized libstdc++).
10074bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10075 const NamedDecl *B) {
10076 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10077 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10078 if (!VA || !VB)
10079 return false;
10080
10081 // The declarations must be declaring the same name as an internal linkage
10082 // entity in different modules.
10083 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10084 VB->getDeclContext()->getRedeclContext()) ||
10085 getOwningModule(VA) == getOwningModule(VB) ||
10086 VA->isExternallyVisible() || VB->isExternallyVisible())
10087 return false;
10088
10089 // Check that the declarations appear to be equivalent.
10090 //
10091 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10092 // For constants and functions, we should check the initializer or body is
10093 // the same. For non-constant variables, we shouldn't allow it at all.
10094 if (Context.hasSameType(VA->getType(), VB->getType()))
10095 return true;
10096
10097 // Enum constants within unnamed enumerations will have different types, but
10098 // may still be similar enough to be interchangeable for our purposes.
10099 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10100 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10101 // Only handle anonymous enums. If the enumerations were named and
10102 // equivalent, they would have been merged to the same type.
10103 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10104 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10105 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10106 !Context.hasSameType(EnumA->getIntegerType(),
10107 EnumB->getIntegerType()))
10108 return false;
10109 // Allow this only if the value is the same for both enumerators.
10110 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10111 }
10112 }
10113
10114 // Nothing else is sufficiently similar.
10115 return false;
10116}
10117
10118void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10119 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10120 assert(D && "Unknown declaration")(static_cast <bool> (D && "Unknown declaration"
) ? void (0) : __assert_fail ("D && \"Unknown declaration\""
, "clang/lib/Sema/SemaOverload.cpp", 10120, __extension__ __PRETTY_FUNCTION__
))
;
10121 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10122
10123 Module *M = getOwningModule(D);
10124 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10125 << !M << (M ? M->getFullModuleName() : "");
10126
10127 for (auto *E : Equiv) {
10128 Module *M = getOwningModule(E);
10129 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10130 << !M << (M ? M->getFullModuleName() : "");
10131 }
10132}
10133
10134bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10135 return FailureKind == ovl_fail_bad_deduction &&
10136 DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied &&
10137 static_cast<CNSInfo *>(DeductionFailure.Data)
10138 ->Satisfaction.ContainsErrors;
10139}
10140
10141/// Computes the best viable function (C++ 13.3.3)
10142/// within an overload candidate set.
10143///
10144/// \param Loc The location of the function name (or operator symbol) for
10145/// which overload resolution occurs.
10146///
10147/// \param Best If overload resolution was successful or found a deleted
10148/// function, \p Best points to the candidate function found.
10149///
10150/// \returns The result of overload resolution.
10151OverloadingResult
10152OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10153 iterator &Best) {
10154 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10155 std::transform(begin(), end(), std::back_inserter(Candidates),
10156 [](OverloadCandidate &Cand) { return &Cand; });
10157
10158 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10159 // are accepted by both clang and NVCC. However, during a particular
10160 // compilation mode only one call variant is viable. We need to
10161 // exclude non-viable overload candidates from consideration based
10162 // only on their host/device attributes. Specifically, if one
10163 // candidate call is WrongSide and the other is SameSide, we ignore
10164 // the WrongSide candidate.
10165 // We only need to remove wrong-sided candidates here if
10166 // -fgpu-exclude-wrong-side-overloads is off. When
10167 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10168 // uniformly in isBetterOverloadCandidate.
10169 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10170 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10171 bool ContainsSameSideCandidate =
10172 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10173 // Check viable function only.
10174 return Cand->Viable && Cand->Function &&
10175 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10176 Sema::CFP_SameSide;
10177 });
10178 if (ContainsSameSideCandidate) {
10179 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10180 // Check viable function only to avoid unnecessary data copying/moving.
10181 return Cand->Viable && Cand->Function &&
10182 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10183 Sema::CFP_WrongSide;
10184 };
10185 llvm::erase_if(Candidates, IsWrongSideCandidate);
10186 }
10187 }
10188
10189 // Find the best viable function.
10190 Best = end();
10191 for (auto *Cand : Candidates) {
10192 Cand->Best = false;
10193 if (Cand->Viable) {
10194 if (Best == end() ||
10195 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10196 Best = Cand;
10197 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10198 // This candidate has constraint that we were unable to evaluate because
10199 // it referenced an expression that contained an error. Rather than fall
10200 // back onto a potentially unintended candidate (made worse by by
10201 // subsuming constraints), treat this as 'no viable candidate'.
10202 Best = end();
10203 return OR_No_Viable_Function;
10204 }
10205 }
10206
10207 // If we didn't find any viable functions, abort.
10208 if (Best == end())
10209 return OR_No_Viable_Function;
10210
10211 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10212
10213 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10214 PendingBest.push_back(&*Best);
10215 Best->Best = true;
10216
10217 // Make sure that this function is better than every other viable
10218 // function. If not, we have an ambiguity.
10219 while (!PendingBest.empty()) {
10220 auto *Curr = PendingBest.pop_back_val();
10221 for (auto *Cand : Candidates) {
10222 if (Cand->Viable && !Cand->Best &&
10223 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10224 PendingBest.push_back(Cand);
10225 Cand->Best = true;
10226
10227 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10228 Curr->Function))
10229 EquivalentCands.push_back(Cand->Function);
10230 else
10231 Best = end();
10232 }
10233 }
10234 }
10235
10236 // If we found more than one best candidate, this is ambiguous.
10237 if (Best == end())
10238 return OR_Ambiguous;
10239
10240 // Best is the best viable function.
10241 if (Best->Function && Best->Function->isDeleted())
10242 return OR_Deleted;
10243
10244 if (!EquivalentCands.empty())
10245 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10246 EquivalentCands);
10247
10248 return OR_Success;
10249}
10250
10251namespace {
10252
10253enum OverloadCandidateKind {
10254 oc_function,
10255 oc_method,
10256 oc_reversed_binary_operator,
10257 oc_constructor,
10258 oc_implicit_default_constructor,
10259 oc_implicit_copy_constructor,
10260 oc_implicit_move_constructor,
10261 oc_implicit_copy_assignment,
10262 oc_implicit_move_assignment,
10263 oc_implicit_equality_comparison,
10264 oc_inherited_constructor
10265};
10266
10267enum OverloadCandidateSelect {
10268 ocs_non_template,
10269 ocs_template,
10270 ocs_described_template,
10271};
10272
10273static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10274ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10275 OverloadCandidateRewriteKind CRK,
10276 std::string &Description) {
10277
10278 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10279 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10280 isTemplate = true;
10281 Description = S.getTemplateArgumentBindingsText(
10282 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10283 }
10284
10285 OverloadCandidateSelect Select = [&]() {
10286 if (!Description.empty())
10287 return ocs_described_template;
10288 return isTemplate ? ocs_template : ocs_non_template;
10289 }();
10290
10291 OverloadCandidateKind Kind = [&]() {
10292 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10293 return oc_implicit_equality_comparison;
10294
10295 if (CRK & CRK_Reversed)
10296 return oc_reversed_binary_operator;
10297
10298 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10299 if (!Ctor->isImplicit()) {
10300 if (isa<ConstructorUsingShadowDecl>(Found))
10301 return oc_inherited_constructor;
10302 else
10303 return oc_constructor;
10304 }
10305
10306 if (Ctor->isDefaultConstructor())
10307 return oc_implicit_default_constructor;
10308
10309 if (Ctor->isMoveConstructor())
10310 return oc_implicit_move_constructor;
10311
10312 assert(Ctor->isCopyConstructor() &&(static_cast <bool> (Ctor->isCopyConstructor() &&
"unexpected sort of implicit constructor") ? void (0) : __assert_fail
("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "clang/lib/Sema/SemaOverload.cpp", 10313, __extension__ __PRETTY_FUNCTION__
))
10313 "unexpected sort of implicit constructor")(static_cast <bool> (Ctor->isCopyConstructor() &&
"unexpected sort of implicit constructor") ? void (0) : __assert_fail
("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "clang/lib/Sema/SemaOverload.cpp", 10313, __extension__ __PRETTY_FUNCTION__
))
;
10314 return oc_implicit_copy_constructor;
10315 }
10316
10317 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10318 // This actually gets spelled 'candidate function' for now, but
10319 // it doesn't hurt to split it out.
10320 if (!Meth->isImplicit())
10321 return oc_method;
10322
10323 if (Meth->isMoveAssignmentOperator())
10324 return oc_implicit_move_assignment;
10325
10326 if (Meth->isCopyAssignmentOperator())
10327 return oc_implicit_copy_assignment;
10328
10329 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")(static_cast <bool> (isa<CXXConversionDecl>(Meth)
&& "expected conversion") ? void (0) : __assert_fail
("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "clang/lib/Sema/SemaOverload.cpp", 10329, __extension__ __PRETTY_FUNCTION__
))
;
10330 return oc_method;
10331 }
10332
10333 return oc_function;
10334 }();
10335
10336 return std::make_pair(Kind, Select);
10337}
10338
10339void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10340 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10341 // set.
10342 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10343 S.Diag(FoundDecl->getLocation(),
10344 diag::note_ovl_candidate_inherited_constructor)
10345 << Shadow->getNominatedBaseClass();
10346}
10347
10348} // end anonymous namespace
10349
10350static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10351 const FunctionDecl *FD) {
10352 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10353 bool AlwaysTrue;
10354 if (EnableIf->getCond()->isValueDependent() ||
10355 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10356 return false;
10357 if (!AlwaysTrue)
10358 return false;
10359 }
10360 return true;
10361}
10362
10363/// Returns true if we can take the address of the function.
10364///
10365/// \param Complain - If true, we'll emit a diagnostic
10366/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10367/// we in overload resolution?
10368/// \param Loc - The location of the statement we're complaining about. Ignored
10369/// if we're not complaining, or if we're in overload resolution.
10370static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10371 bool Complain,
10372 bool InOverloadResolution,
10373 SourceLocation Loc) {
10374 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10375 if (Complain) {
10376 if (InOverloadResolution)
10377 S.Diag(FD->getBeginLoc(),
10378 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10379 else
10380 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10381 }
10382 return false;
10383 }
10384
10385 if (FD->getTrailingRequiresClause()) {
10386 ConstraintSatisfaction Satisfaction;
10387 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10388 return false;
10389 if (!Satisfaction.IsSatisfied) {
10390 if (Complain) {
10391 if (InOverloadResolution) {
10392 SmallString<128> TemplateArgString;
10393 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10394 TemplateArgString += " ";
10395 TemplateArgString += S.getTemplateArgumentBindingsText(
10396 FunTmpl->getTemplateParameters(),
10397 *FD->getTemplateSpecializationArgs());
10398 }
10399
10400 S.Diag(FD->getBeginLoc(),
10401 diag::note_ovl_candidate_unsatisfied_constraints)
10402 << TemplateArgString;
10403 } else
10404 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10405 << FD;
10406 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10407 }
10408 return false;
10409 }
10410 }
10411
10412 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10413 return P->hasAttr<PassObjectSizeAttr>();
10414 });
10415 if (I == FD->param_end())
10416 return true;
10417
10418 if (Complain) {
10419 // Add one to ParamNo because it's user-facing
10420 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10421 if (InOverloadResolution)
10422 S.Diag(FD->getLocation(),
10423 diag::note_ovl_candidate_has_pass_object_size_params)
10424 << ParamNo;
10425 else
10426 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10427 << FD << ParamNo;
10428 }
10429 return false;
10430}
10431
10432static bool checkAddressOfCandidateIsAvailable(Sema &S,
10433 const FunctionDecl *FD) {
10434 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10435 /*InOverloadResolution=*/true,
10436 /*Loc=*/SourceLocation());
10437}
10438
10439bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10440 bool Complain,
10441 SourceLocation Loc) {
10442 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10443 /*InOverloadResolution=*/false,
10444 Loc);
10445}
10446
10447// Don't print candidates other than the one that matches the calling
10448// convention of the call operator, since that is guaranteed to exist.
10449static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10450 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10451
10452 if (!ConvD)
10453 return false;
10454 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10455 if (!RD->isLambda())
10456 return false;
10457
10458 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10459 CallingConv CallOpCC =
10460 CallOp->getType()->castAs<FunctionType>()->getCallConv();
10461 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10462 CallingConv ConvToCC =
10463 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10464
10465 return ConvToCC != CallOpCC;
10466}
10467
10468// Notes the location of an overload candidate.
10469void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10470 OverloadCandidateRewriteKind RewriteKind,
10471 QualType DestType, bool TakingAddress) {
10472 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10473 return;
10474 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10475 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10476 return;
10477 if (shouldSkipNotingLambdaConversionDecl(Fn))
10478 return;
10479
10480 std::string FnDesc;
10481 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10482 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10483 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10484 << (unsigned)KSPair.first << (unsigned)KSPair.second
10485 << Fn << FnDesc;
10486
10487 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10488 Diag(Fn->getLocation(), PD);
10489 MaybeEmitInheritedConstructorNote(*this, Found);
10490}
10491
10492static void
10493MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10494 // Perhaps the ambiguity was caused by two atomic constraints that are
10495 // 'identical' but not equivalent:
10496 //
10497 // void foo() requires (sizeof(T) > 4) { } // #1
10498 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10499 //
10500 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10501 // #2 to subsume #1, but these constraint are not considered equivalent
10502 // according to the subsumption rules because they are not the same
10503 // source-level construct. This behavior is quite confusing and we should try
10504 // to help the user figure out what happened.
10505
10506 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10507 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10508 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10509 if (!I->Function)
10510 continue;
10511 SmallVector<const Expr *, 3> AC;
10512 if (auto *Template = I->Function->getPrimaryTemplate())
10513 Template->getAssociatedConstraints(AC);
10514 else
10515 I->Function->getAssociatedConstraints(AC);
10516 if (AC.empty())
10517 continue;
10518 if (FirstCand == nullptr) {
10519 FirstCand = I->Function;
10520 FirstAC = AC;
10521 } else if (SecondCand == nullptr) {
10522 SecondCand = I->Function;
10523 SecondAC = AC;
10524 } else {
10525 // We have more than one pair of constrained functions - this check is
10526 // expensive and we'd rather not try to diagnose it.
10527 return;
10528 }
10529 }
10530 if (!SecondCand)
10531 return;
10532 // The diagnostic can only happen if there are associated constraints on
10533 // both sides (there needs to be some identical atomic constraint).
10534 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10535 SecondCand, SecondAC))
10536 // Just show the user one diagnostic, they'll probably figure it out
10537 // from here.
10538 return;
10539}
10540
10541// Notes the location of all overload candidates designated through
10542// OverloadedExpr
10543void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10544 bool TakingAddress) {
10545 assert(OverloadedExpr->getType() == Context.OverloadTy)(static_cast <bool> (OverloadedExpr->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 10545, __extension__ __PRETTY_FUNCTION__
))
;
10546
10547 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10548 OverloadExpr *OvlExpr = Ovl.Expression;
10549
10550 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10551 IEnd = OvlExpr->decls_end();
10552 I != IEnd; ++I) {
10553 if (FunctionTemplateDecl *FunTmpl =
10554 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10555 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10556 TakingAddress);
10557 } else if (FunctionDecl *Fun
10558 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10559 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10560 }
10561 }
10562}
10563
10564/// Diagnoses an ambiguous conversion. The partial diagnostic is the
10565/// "lead" diagnostic; it will be given two arguments, the source and
10566/// target types of the conversion.
10567void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10568 Sema &S,
10569 SourceLocation CaretLoc,
10570 const PartialDiagnostic &PDiag) const {
10571 S.Diag(CaretLoc, PDiag)
10572 << Ambiguous.getFromType() << Ambiguous.getToType();
10573 unsigned CandsShown = 0;
10574 AmbiguousConversionSequence::const_iterator I, E;
10575 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10576 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10577 break;
10578 ++CandsShown;
10579 S.NoteOverloadCandidate(I->first, I->second);
10580 }
10581 S.Diags.overloadCandidatesShown(CandsShown);
10582 if (I != E)
10583 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10584}
10585
10586static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10587 unsigned I, bool TakingCandidateAddress) {
10588 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10589 assert(Conv.isBad())(static_cast <bool> (Conv.isBad()) ? void (0) : __assert_fail
("Conv.isBad()", "clang/lib/Sema/SemaOverload.cpp", 10589, __extension__
__PRETTY_FUNCTION__))
;
10590 assert(Cand->Function && "for now, candidate must be a function")(static_cast <bool> (Cand->Function && "for now, candidate must be a function"
) ? void (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "clang/lib/Sema/SemaOverload.cpp", 10590, __extension__ __PRETTY_FUNCTION__
))
;
10591 FunctionDecl *Fn = Cand->Function;
10592
10593 // There's a conversion slot for the object argument if this is a
10594 // non-constructor method. Note that 'I' corresponds the
10595 // conversion-slot index.
10596 bool isObjectArgument = false;
10597 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10598 if (I == 0)
10599 isObjectArgument = true;
10600 else
10601 I--;
10602 }
10603
10604 std::string FnDesc;
10605 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10606 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10607 FnDesc);
10608
10609 Expr *FromExpr = Conv.Bad.FromExpr;
10610 QualType FromTy = Conv.Bad.getFromType();
10611 QualType ToTy = Conv.Bad.getToType();
10612
10613 if (FromTy == S.Context.OverloadTy) {
10614 assert(FromExpr && "overload set argument came from implicit argument?")(static_cast <bool> (FromExpr && "overload set argument came from implicit argument?"
) ? void (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "clang/lib/Sema/SemaOverload.cpp", 10614, __extension__ __PRETTY_FUNCTION__
))
;
10615 Expr *E = FromExpr->IgnoreParens();
10616 if (isa<UnaryOperator>(E))
10617 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10618 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10619
10620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10621 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10622 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10623 << Name << I + 1;
10624 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10625 return;
10626 }
10627
10628 // Do some hand-waving analysis to see if the non-viability is due
10629 // to a qualifier mismatch.
10630 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10631 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10632 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10633 CToTy = RT->getPointeeType();
10634 else {
10635 // TODO: detect and diagnose the full richness of const mismatches.
10636 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10637 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10638 CFromTy = FromPT->getPointeeType();
10639 CToTy = ToPT->getPointeeType();
10640 }
10641 }
10642
10643 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10644 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10645 Qualifiers FromQs = CFromTy.getQualifiers();
10646 Qualifiers ToQs = CToTy.getQualifiers();
10647
10648 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10649 if (isObjectArgument)
10650 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10651 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10652 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10653 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10654 else
10655 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10656 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10657 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10658 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10659 << ToTy->isReferenceType() << I + 1;
10660 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10661 return;
10662 }
10663
10664 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10666 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10667 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10668 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10669 << (unsigned)isObjectArgument << I + 1;
10670 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10671 return;
10672 }
10673
10674 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10675 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10676 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10677 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10678 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10679 << (unsigned)isObjectArgument << I + 1;
10680 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10681 return;
10682 }
10683
10684 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10685 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10686 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10687 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10688 << FromQs.hasUnaligned() << I + 1;
10689 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10690 return;
10691 }
10692
10693 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10694 assert(CVR && "expected qualifiers mismatch")(static_cast <bool> (CVR && "expected qualifiers mismatch"
) ? void (0) : __assert_fail ("CVR && \"expected qualifiers mismatch\""
, "clang/lib/Sema/SemaOverload.cpp", 10694, __extension__ __PRETTY_FUNCTION__
))
;
10695
10696 if (isObjectArgument) {
10697 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10698 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10699 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10700 << (CVR - 1);
10701 } else {
10702 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10703 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10704 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10705 << (CVR - 1) << I + 1;
10706 }
10707 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10708 return;
10709 }
10710
10711 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10712 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10713 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10714 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10715 << (unsigned)isObjectArgument << I + 1
10716 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10717 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10718 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10719 return;
10720 }
10721
10722 // Special diagnostic for failure to convert an initializer list, since
10723 // telling the user that it has type void is not useful.
10724 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10725 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10726 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10727 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10728 << ToTy << (unsigned)isObjectArgument << I + 1
10729 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10730 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10731 ? 2
10732 : 0);
10733 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10734 return;
10735 }
10736
10737 // Diagnose references or pointers to incomplete types differently,
10738 // since it's far from impossible that the incompleteness triggered
10739 // the failure.
10740 QualType TempFromTy = FromTy.getNonReferenceType();
10741 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10742 TempFromTy = PTy->getPointeeType();
10743 if (TempFromTy->isIncompleteType()) {
10744 // Emit the generic diagnostic and, optionally, add the hints to it.
10745 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10746 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10747 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10748 << ToTy << (unsigned)isObjectArgument << I + 1
10749 << (unsigned)(Cand->Fix.Kind);
10750
10751 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10752 return;
10753 }
10754
10755 // Diagnose base -> derived pointer conversions.
10756 unsigned BaseToDerivedConversion = 0;
10757 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10758 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10759 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10760 FromPtrTy->getPointeeType()) &&
10761 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10762 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10763 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10764 FromPtrTy->getPointeeType()))
10765 BaseToDerivedConversion = 1;
10766 }
10767 } else if (const ObjCObjectPointerType *FromPtrTy
10768 = FromTy->getAs<ObjCObjectPointerType>()) {
10769 if (const ObjCObjectPointerType *ToPtrTy
10770 = ToTy->getAs<ObjCObjectPointerType>())
10771 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10772 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10773 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10774 FromPtrTy->getPointeeType()) &&
10775 FromIface->isSuperClassOf(ToIface))
10776 BaseToDerivedConversion = 2;
10777 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10778 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10779 !FromTy->isIncompleteType() &&
10780 !ToRefTy->getPointeeType()->isIncompleteType() &&
10781 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10782 BaseToDerivedConversion = 3;
10783 }
10784 }
10785
10786 if (BaseToDerivedConversion) {
10787 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10788 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10789 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10790 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10791 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10792 return;
10793 }
10794
10795 if (isa<ObjCObjectPointerType>(CFromTy) &&
10796 isa<PointerType>(CToTy)) {
10797 Qualifiers FromQs = CFromTy.getQualifiers();
10798 Qualifiers ToQs = CToTy.getQualifiers();
10799 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10800 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10801 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10802 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10803 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10804 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10805 return;
10806 }
10807 }
10808
10809 if (TakingCandidateAddress &&
10810 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10811 return;
10812
10813 // Emit the generic diagnostic and, optionally, add the hints to it.
10814 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10815 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10816 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10817 << ToTy << (unsigned)isObjectArgument << I + 1
10818 << (unsigned)(Cand->Fix.Kind);
10819
10820 // If we can fix the conversion, suggest the FixIts.
10821 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10822 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10823 FDiag << *HI;
10824 S.Diag(Fn->getLocation(), FDiag);
10825
10826 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10827}
10828
10829/// Additional arity mismatch diagnosis specific to a function overload
10830/// candidates. This is not covered by the more general DiagnoseArityMismatch()
10831/// over a candidate in any candidate set.
10832static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10833 unsigned NumArgs) {
10834 FunctionDecl *Fn = Cand->Function;
10835 unsigned MinParams = Fn->getMinRequiredArguments();
10836
10837 // With invalid overloaded operators, it's possible that we think we
10838 // have an arity mismatch when in fact it looks like we have the
10839 // right number of arguments, because only overloaded operators have
10840 // the weird behavior of overloading member and non-member functions.
10841 // Just don't report anything.
10842 if (Fn->isInvalidDecl() &&
10843 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10844 return true;
10845
10846 if (NumArgs < MinParams) {
10847 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10849, __extension__ __PRETTY_FUNCTION__
))
10848 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10849, __extension__ __PRETTY_FUNCTION__
))
10849 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10849, __extension__ __PRETTY_FUNCTION__
))
;
10850 } else {
10851 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10853, __extension__ __PRETTY_FUNCTION__
))
10852 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10853, __extension__ __PRETTY_FUNCTION__
))
10853 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10853, __extension__ __PRETTY_FUNCTION__
))
;
10854 }
10855
10856 return false;
10857}
10858
10859/// General arity mismatch diagnosis over a candidate in a candidate set.
10860static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10861 unsigned NumFormalArgs) {
10862 assert(isa<FunctionDecl>(D) &&(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10865, __extension__ __PRETTY_FUNCTION__
))
10863 "The templated declaration should at least be a function"(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10865, __extension__ __PRETTY_FUNCTION__
))
10864 " when diagnosing bad template argument deduction due to too many"(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10865, __extension__ __PRETTY_FUNCTION__
))
10865 " or too few arguments")(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10865, __extension__ __PRETTY_FUNCTION__
))
;
10866
10867 FunctionDecl *Fn = cast<FunctionDecl>(D);
10868
10869 // TODO: treat calls to a missing default constructor as a special case
10870 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10871 unsigned MinParams = Fn->getMinRequiredArguments();
10872
10873 // at least / at most / exactly
10874 unsigned mode, modeCount;
10875 if (NumFormalArgs < MinParams) {
10876 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10877 FnTy->isTemplateVariadic())
10878 mode = 0; // "at least"
10879 else
10880 mode = 2; // "exactly"
10881 modeCount = MinParams;
10882 } else {
10883 if (MinParams != FnTy->getNumParams())
10884 mode = 1; // "at most"
10885 else
10886 mode = 2; // "exactly"
10887 modeCount = FnTy->getNumParams();
10888 }
10889
10890 std::string Description;
10891 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10892 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10893
10894 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10895 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10896 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10897 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10898 else
10899 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10900 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10901 << Description << mode << modeCount << NumFormalArgs;
10902
10903 MaybeEmitInheritedConstructorNote(S, Found);
10904}
10905
10906/// Arity mismatch diagnosis specific to a function overload candidate.
10907static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10908 unsigned NumFormalArgs) {
10909 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10910 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10911}
10912
10913static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10914 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10915 return TD;
10916 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp"
, 10917)
10917 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp"
, 10917)
;
10918}
10919
10920/// Diagnose a failed template-argument deduction.
10921static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10922 DeductionFailureInfo &DeductionFailure,
10923 unsigned NumArgs,
10924 bool TakingCandidateAddress) {
10925 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10926 NamedDecl *ParamD;
10927 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10928 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10929 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10930 switch (DeductionFailure.Result) {
10931 case Sema::TDK_Success:
10932 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "clang/lib/Sema/SemaOverload.cpp", 10932)
;
10933
10934 case Sema::TDK_Incomplete: {
10935 assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10935, __extension__ __PRETTY_FUNCTION__
))
;
10936 S.Diag(Templated->getLocation(),
10937 diag::note_ovl_candidate_incomplete_deduction)
10938 << ParamD->getDeclName();
10939 MaybeEmitInheritedConstructorNote(S, Found);
10940 return;
10941 }
10942
10943 case Sema::TDK_IncompletePack: {
10944 assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10944, __extension__ __PRETTY_FUNCTION__
))
;
10945 S.Diag(Templated->getLocation(),
10946 diag::note_ovl_candidate_incomplete_deduction_pack)
10947 << ParamD->getDeclName()
10948 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10949 << *DeductionFailure.getFirstArg();
10950 MaybeEmitInheritedConstructorNote(S, Found);
10951 return;
10952 }
10953
10954 case Sema::TDK_Underqualified: {
10955 assert(ParamD && "no parameter found for bad qualifiers deduction result")(static_cast <bool> (ParamD && "no parameter found for bad qualifiers deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10955, __extension__ __PRETTY_FUNCTION__
))
;
10956 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10957
10958 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10959
10960 // Param will have been canonicalized, but it should just be a
10961 // qualified version of ParamD, so move the qualifiers to that.
10962 QualifierCollector Qs;
10963 Qs.strip(Param);
10964 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10965 assert(S.Context.hasSameType(Param, NonCanonParam))(static_cast <bool> (S.Context.hasSameType(Param, NonCanonParam
)) ? void (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "clang/lib/Sema/SemaOverload.cpp", 10965, __extension__ __PRETTY_FUNCTION__
))
;
10966
10967 // Arg has also been canonicalized, but there's nothing we can do
10968 // about that. It also doesn't matter as much, because it won't
10969 // have any template parameters in it (because deduction isn't
10970 // done on dependent types).
10971 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10972
10973 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10974 << ParamD->getDeclName() << Arg << NonCanonParam;
10975 MaybeEmitInheritedConstructorNote(S, Found);
10976 return;
10977 }
10978
10979 case Sema::TDK_Inconsistent: {
10980 assert(ParamD && "no parameter found for inconsistent deduction result")(static_cast <bool> (ParamD && "no parameter found for inconsistent deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10980, __extension__ __PRETTY_FUNCTION__
))
;
10981 int which = 0;
10982 if (isa<TemplateTypeParmDecl>(ParamD))
10983 which = 0;
10984 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10985 // Deduction might have failed because we deduced arguments of two
10986 // different types for a non-type template parameter.
10987 // FIXME: Use a different TDK value for this.
10988 QualType T1 =
10989 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10990 QualType T2 =
10991 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10992 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10993 S.Diag(Templated->getLocation(),
10994 diag::note_ovl_candidate_inconsistent_deduction_types)
10995 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10996 << *DeductionFailure.getSecondArg() << T2;
10997 MaybeEmitInheritedConstructorNote(S, Found);
10998 return;
10999 }
11000
11001 which = 1;
11002 } else {
11003 which = 2;
11004 }
11005
11006 // Tweak the diagnostic if the problem is that we deduced packs of
11007 // different arities. We'll print the actual packs anyway in case that
11008 // includes additional useful information.
11009 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11010 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11011 DeductionFailure.getFirstArg()->pack_size() !=
11012 DeductionFailure.getSecondArg()->pack_size()) {
11013 which = 3;
11014 }
11015
11016 S.Diag(Templated->getLocation(),
11017 diag::note_ovl_candidate_inconsistent_deduction)
11018 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11019 << *DeductionFailure.getSecondArg();
11020 MaybeEmitInheritedConstructorNote(S, Found);
11021 return;
11022 }
11023
11024 case Sema::TDK_InvalidExplicitArguments:
11025 assert(ParamD && "no parameter found for invalid explicit arguments")(static_cast <bool> (ParamD && "no parameter found for invalid explicit arguments"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 11025, __extension__ __PRETTY_FUNCTION__
))
;
11026 if (ParamD->getDeclName())
11027 S.Diag(Templated->getLocation(),
11028 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11029 << ParamD->getDeclName();
11030 else {
11031 int index = 0;
11032 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11033 index = TTP->getIndex();
11034 else if (NonTypeTemplateParmDecl *NTTP
11035 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11036 index = NTTP->getIndex();
11037 else
11038 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11039 S.Diag(Templated->getLocation(),
11040 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11041 << (index + 1);
11042 }
11043 MaybeEmitInheritedConstructorNote(S, Found);
11044 return;
11045
11046 case Sema::TDK_ConstraintsNotSatisfied: {
11047 // Format the template argument list into the argument string.
11048 SmallString<128> TemplateArgString;
11049 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11050 TemplateArgString = " ";
11051 TemplateArgString += S.getTemplateArgumentBindingsText(
11052 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11053 if (TemplateArgString.size() == 1)
11054 TemplateArgString.clear();
11055 S.Diag(Templated->getLocation(),
11056 diag::note_ovl_candidate_unsatisfied_constraints)
11057 << TemplateArgString;
11058
11059 S.DiagnoseUnsatisfiedConstraint(
11060 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11061 return;
11062 }
11063 case Sema::TDK_TooManyArguments:
11064 case Sema::TDK_TooFewArguments:
11065 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11066 return;
11067
11068 case Sema::TDK_InstantiationDepth:
11069 S.Diag(Templated->getLocation(),
11070 diag::note_ovl_candidate_instantiation_depth);
11071 MaybeEmitInheritedConstructorNote(S, Found);
11072 return;
11073
11074 case Sema::TDK_SubstitutionFailure: {
11075 // Format the template argument list into the argument string.
11076 SmallString<128> TemplateArgString;
11077 if (TemplateArgumentList *Args =
11078 DeductionFailure.getTemplateArgumentList()) {
11079 TemplateArgString = " ";
11080 TemplateArgString += S.getTemplateArgumentBindingsText(
11081 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11082 if (TemplateArgString.size() == 1)
11083 TemplateArgString.clear();
11084 }
11085
11086 // If this candidate was disabled by enable_if, say so.
11087 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11088 if (PDiag && PDiag->second.getDiagID() ==
11089 diag::err_typename_nested_not_found_enable_if) {
11090 // FIXME: Use the source range of the condition, and the fully-qualified
11091 // name of the enable_if template. These are both present in PDiag.
11092 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11093 << "'enable_if'" << TemplateArgString;
11094 return;
11095 }
11096
11097 // We found a specific requirement that disabled the enable_if.
11098 if (PDiag && PDiag->second.getDiagID() ==
11099 diag::err_typename_nested_not_found_requirement) {
11100 S.Diag(Templated->getLocation(),
11101 diag::note_ovl_candidate_disabled_by_requirement)
11102 << PDiag->second.getStringArg(0) << TemplateArgString;
11103 return;
11104 }
11105
11106 // Format the SFINAE diagnostic into the argument string.
11107 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11108 // formatted message in another diagnostic.
11109 SmallString<128> SFINAEArgString;
11110 SourceRange R;
11111 if (PDiag) {
11112 SFINAEArgString = ": ";
11113 R = SourceRange(PDiag->first, PDiag->first);
11114 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11115 }
11116
11117 S.Diag(Templated->getLocation(),
11118 diag::note_ovl_candidate_substitution_failure)
11119 << TemplateArgString << SFINAEArgString << R;
11120 MaybeEmitInheritedConstructorNote(S, Found);
11121 return;
11122 }
11123
11124 case Sema::TDK_DeducedMismatch:
11125 case Sema::TDK_DeducedMismatchNested: {
11126 // Format the template argument list into the argument string.
11127 SmallString<128> TemplateArgString;
11128 if (TemplateArgumentList *Args =
11129 DeductionFailure.getTemplateArgumentList()) {
11130 TemplateArgString = " ";
11131 TemplateArgString += S.getTemplateArgumentBindingsText(
11132 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11133 if (TemplateArgString.size() == 1)
11134 TemplateArgString.clear();
11135 }
11136
11137 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11138 << (*DeductionFailure.getCallArgIndex() + 1)
11139 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11140 << TemplateArgString
11141 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11142 break;
11143 }
11144
11145 case Sema::TDK_NonDeducedMismatch: {
11146 // FIXME: Provide a source location to indicate what we couldn't match.
11147 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11148 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11149 if (FirstTA.getKind() == TemplateArgument::Template &&
11150 SecondTA.getKind() == TemplateArgument::Template) {
11151 TemplateName FirstTN = FirstTA.getAsTemplate();
11152 TemplateName SecondTN = SecondTA.getAsTemplate();
11153 if (FirstTN.getKind() == TemplateName::Template &&
11154 SecondTN.getKind() == TemplateName::Template) {
11155 if (FirstTN.getAsTemplateDecl()->getName() ==
11156 SecondTN.getAsTemplateDecl()->getName()) {
11157 // FIXME: This fixes a bad diagnostic where both templates are named
11158 // the same. This particular case is a bit difficult since:
11159 // 1) It is passed as a string to the diagnostic printer.
11160 // 2) The diagnostic printer only attempts to find a better
11161 // name for types, not decls.
11162 // Ideally, this should folded into the diagnostic printer.
11163 S.Diag(Templated->getLocation(),
11164 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11165 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11166 return;
11167 }
11168 }
11169 }
11170
11171 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11172 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11173 return;
11174
11175 // FIXME: For generic lambda parameters, check if the function is a lambda
11176 // call operator, and if so, emit a prettier and more informative
11177 // diagnostic that mentions 'auto' and lambda in addition to
11178 // (or instead of?) the canonical template type parameters.
11179 S.Diag(Templated->getLocation(),
11180 diag::note_ovl_candidate_non_deduced_mismatch)
11181 << FirstTA << SecondTA;
11182 return;
11183 }
11184 // TODO: diagnose these individually, then kill off
11185 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11186 case Sema::TDK_MiscellaneousDeductionFailure:
11187 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11188 MaybeEmitInheritedConstructorNote(S, Found);
11189 return;
11190 case Sema::TDK_CUDATargetMismatch:
11191 S.Diag(Templated->getLocation(),
11192 diag::note_cuda_ovl_candidate_target_mismatch);
11193 return;
11194 }
11195}
11196
11197/// Diagnose a failed template-argument deduction, for function calls.
11198static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11199 unsigned NumArgs,
11200 bool TakingCandidateAddress) {
11201 unsigned TDK = Cand->DeductionFailure.Result;
11202 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11203 if (CheckArityMismatch(S, Cand, NumArgs))
11204 return;
11205 }
11206 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11207 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11208}
11209
11210/// CUDA: diagnose an invalid call across targets.
11211static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11212 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11213 FunctionDecl *Callee = Cand->Function;
11214
11215 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11216 CalleeTarget = S.IdentifyCUDATarget(Callee);
11217
11218 std::string FnDesc;
11219 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11220 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11221 Cand->getRewriteKind(), FnDesc);
11222
11223 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11224 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11225 << FnDesc /* Ignored */
11226 << CalleeTarget << CallerTarget;
11227
11228 // This could be an implicit constructor for which we could not infer the
11229 // target due to a collsion. Diagnose that case.
11230 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11231 if (Meth != nullptr && Meth->isImplicit()) {
11232 CXXRecordDecl *ParentClass = Meth->getParent();
11233 Sema::CXXSpecialMember CSM;
11234
11235 switch (FnKindPair.first) {
11236 default:
11237 return;
11238 case oc_implicit_default_constructor:
11239 CSM = Sema::CXXDefaultConstructor;
11240 break;
11241 case oc_implicit_copy_constructor:
11242 CSM = Sema::CXXCopyConstructor;
11243 break;
11244 case oc_implicit_move_constructor:
11245 CSM = Sema::CXXMoveConstructor;
11246 break;
11247 case oc_implicit_copy_assignment:
11248 CSM = Sema::CXXCopyAssignment;
11249 break;
11250 case oc_implicit_move_assignment:
11251 CSM = Sema::CXXMoveAssignment;
11252 break;
11253 };
11254
11255 bool ConstRHS = false;
11256 if (Meth->getNumParams()) {
11257 if (const ReferenceType *RT =
11258 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11259 ConstRHS = RT->getPointeeType().isConstQualified();
11260 }
11261 }
11262
11263 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11264 /* ConstRHS */ ConstRHS,
11265 /* Diagnose */ true);
11266 }
11267}
11268
11269static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11270 FunctionDecl *Callee = Cand->Function;
11271 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11272
11273 S.Diag(Callee->getLocation(),
11274 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11275 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11276}
11277
11278static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11279 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11280 assert(ES.isExplicit() && "not an explicit candidate")(static_cast <bool> (ES.isExplicit() && "not an explicit candidate"
) ? void (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "clang/lib/Sema/SemaOverload.cpp", 11280, __extension__ __PRETTY_FUNCTION__
))
;
11281
11282 unsigned Kind;
11283 switch (Cand->Function->getDeclKind()) {
11284 case Decl::Kind::CXXConstructor:
11285 Kind = 0;
11286 break;
11287 case Decl::Kind::CXXConversion:
11288 Kind = 1;
11289 break;
11290 case Decl::Kind::CXXDeductionGuide:
11291 Kind = Cand->Function->isImplicit() ? 0 : 2;
11292 break;
11293 default:
11294 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "clang/lib/Sema/SemaOverload.cpp"
, 11294)
;
11295 }
11296
11297 // Note the location of the first (in-class) declaration; a redeclaration
11298 // (particularly an out-of-class definition) will typically lack the
11299 // 'explicit' specifier.
11300 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11301 FunctionDecl *First = Cand->Function->getFirstDecl();
11302 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11303 First = Pattern->getFirstDecl();
11304
11305 S.Diag(First->getLocation(),
11306 diag::note_ovl_candidate_explicit)
11307 << Kind << (ES.getExpr() ? 1 : 0)
11308 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11309}
11310
11311/// Generates a 'note' diagnostic for an overload candidate. We've
11312/// already generated a primary error at the call site.
11313///
11314/// It really does need to be a single diagnostic with its caret
11315/// pointed at the candidate declaration. Yes, this creates some
11316/// major challenges of technical writing. Yes, this makes pointing
11317/// out problems with specific arguments quite awkward. It's still
11318/// better than generating twenty screens of text for every failed
11319/// overload.
11320///
11321/// It would be great to be able to express per-candidate problems
11322/// more richly for those diagnostic clients that cared, but we'd
11323/// still have to be just as careful with the default diagnostics.
11324/// \param CtorDestAS Addr space of object being constructed (for ctor
11325/// candidates only).
11326static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11327 unsigned NumArgs,
11328 bool TakingCandidateAddress,
11329 LangAS CtorDestAS = LangAS::Default) {
11330 FunctionDecl *Fn = Cand->Function;
11331 if (shouldSkipNotingLambdaConversionDecl(Fn))
11332 return;
11333
11334 // There is no physical candidate declaration to point to for OpenCL builtins.
11335 // Except for failed conversions, the notes are identical for each candidate,
11336 // so do not generate such notes.
11337 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11338 Cand->FailureKind != ovl_fail_bad_conversion)
11339 return;
11340
11341 // Note deleted candidates, but only if they're viable.
11342 if (Cand->Viable) {
11343 if (Fn->isDeleted()) {
11344 std::string FnDesc;
11345 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11346 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11347 Cand->getRewriteKind(), FnDesc);
11348
11349 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11350 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11351 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11352 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11353 return;
11354 }
11355
11356 // We don't really have anything else to say about viable candidates.
11357 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11358 return;
11359 }
11360
11361 switch (Cand->FailureKind) {
11362 case ovl_fail_too_many_arguments:
11363 case ovl_fail_too_few_arguments:
11364 return DiagnoseArityMismatch(S, Cand, NumArgs);
11365
11366 case ovl_fail_bad_deduction:
11367 return DiagnoseBadDeduction(S, Cand, NumArgs,
11368 TakingCandidateAddress);
11369
11370 case ovl_fail_illegal_constructor: {
11371 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11372 << (Fn->getPrimaryTemplate() ? 1 : 0);
11373 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11374 return;
11375 }
11376
11377 case ovl_fail_object_addrspace_mismatch: {
11378 Qualifiers QualsForPrinting;
11379 QualsForPrinting.setAddressSpace(CtorDestAS);
11380 S.Diag(Fn->getLocation(),
11381 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11382 << QualsForPrinting;
11383 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11384 return;
11385 }
11386
11387 case ovl_fail_trivial_conversion:
11388 case ovl_fail_bad_final_conversion:
11389 case ovl_fail_final_conversion_not_exact:
11390 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11391
11392 case ovl_fail_bad_conversion: {
11393 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11394 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11395 if (Cand->Conversions[I].isBad())
11396 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11397
11398 // FIXME: this currently happens when we're called from SemaInit
11399 // when user-conversion overload fails. Figure out how to handle
11400 // those conditions and diagnose them well.
11401 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11402 }
11403
11404 case ovl_fail_bad_target:
11405 return DiagnoseBadTarget(S, Cand);
11406
11407 case ovl_fail_enable_if:
11408 return DiagnoseFailedEnableIfAttr(S, Cand);
11409
11410 case ovl_fail_explicit:
11411 return DiagnoseFailedExplicitSpec(S, Cand);
11412
11413 case ovl_fail_inhctor_slice:
11414 // It's generally not interesting to note copy/move constructors here.
11415 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11416 return;
11417 S.Diag(Fn->getLocation(),
11418 diag::note_ovl_candidate_inherited_constructor_slice)
11419 << (Fn->getPrimaryTemplate() ? 1 : 0)
11420 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11421 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11422 return;
11423
11424 case ovl_fail_addr_not_available: {
11425 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11426 (void)Available;
11427 assert(!Available)(static_cast <bool> (!Available) ? void (0) : __assert_fail
("!Available", "clang/lib/Sema/SemaOverload.cpp", 11427, __extension__
__PRETTY_FUNCTION__))
;
11428 break;
11429 }
11430 case ovl_non_default_multiversion_function:
11431 // Do nothing, these should simply be ignored.
11432 break;
11433
11434 case ovl_fail_constraints_not_satisfied: {
11435 std::string FnDesc;
11436 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11437 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11438 Cand->getRewriteKind(), FnDesc);
11439
11440 S.Diag(Fn->getLocation(),
11441 diag::note_ovl_candidate_constraints_not_satisfied)
11442 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11443 << FnDesc /* Ignored */;
11444 ConstraintSatisfaction Satisfaction;
11445 if (S.CheckFunctionConstraints(Fn, Satisfaction))
11446 break;
11447 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11448 }
11449 }
11450}
11451
11452static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11453 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11454 return;
11455
11456 // Desugar the type of the surrogate down to a function type,
11457 // retaining as many typedefs as possible while still showing
11458 // the function type (and, therefore, its parameter types).
11459 QualType FnType = Cand->Surrogate->getConversionType();
11460 bool isLValueReference = false;
11461 bool isRValueReference = false;
11462 bool isPointer = false;
11463 if (const LValueReferenceType *FnTypeRef =
11464 FnType->getAs<LValueReferenceType>()) {
11465 FnType = FnTypeRef->getPointeeType();
11466 isLValueReference = true;
11467 } else if (const RValueReferenceType *FnTypeRef =
11468 FnType->getAs<RValueReferenceType>()) {
11469 FnType = FnTypeRef->getPointeeType();
11470 isRValueReference = true;
11471 }
11472 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11473 FnType = FnTypePtr->getPointeeType();
11474 isPointer = true;
11475 }
11476 // Desugar down to a function type.
11477 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11478 // Reconstruct the pointer/reference as appropriate.
11479 if (isPointer) FnType = S.Context.getPointerType(FnType);
11480 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11481 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11482
11483 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11484 << FnType;
11485}
11486
11487static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11488 SourceLocation OpLoc,
11489 OverloadCandidate *Cand) {
11490 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")(static_cast <bool> (Cand->Conversions.size() <= 2
&& "builtin operator is not binary") ? void (0) : __assert_fail
("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "clang/lib/Sema/SemaOverload.cpp", 11490, __extension__ __PRETTY_FUNCTION__
))
;
11491 std::string TypeStr("operator");
11492 TypeStr += Opc;
11493 TypeStr += "(";
11494 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11495 if (Cand->Conversions.size() == 1) {
11496 TypeStr += ")";
11497 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11498 } else {
11499 TypeStr += ", ";
11500 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11501 TypeStr += ")";
11502 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11503 }
11504}
11505
11506static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11507 OverloadCandidate *Cand) {
11508 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11509 if (ICS.isBad()) break; // all meaningless after first invalid
11510 if (!ICS.isAmbiguous()) continue;
11511
11512 ICS.DiagnoseAmbiguousConversion(
11513 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11514 }
11515}
11516
11517static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11518 if (Cand->Function)
11519 return Cand->Function->getLocation();
11520 if (Cand->IsSurrogate)
11521 return Cand->Surrogate->getLocation();
11522 return SourceLocation();
11523}
11524
11525static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11526 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11527 case Sema::TDK_Success:
11528 case Sema::TDK_NonDependentConversionFailure:
11529 case Sema::TDK_AlreadyDiagnosed:
11530 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "clang/lib/Sema/SemaOverload.cpp", 11530)
;
11531
11532 case Sema::TDK_Invalid:
11533 case Sema::TDK_Incomplete:
11534 case Sema::TDK_IncompletePack:
11535 return 1;
11536
11537 case Sema::TDK_Underqualified:
11538 case Sema::TDK_Inconsistent:
11539 return 2;
11540
11541 case Sema::TDK_SubstitutionFailure:
11542 case Sema::TDK_DeducedMismatch:
11543 case Sema::TDK_ConstraintsNotSatisfied:
11544 case Sema::TDK_DeducedMismatchNested:
11545 case Sema::TDK_NonDeducedMismatch:
11546 case Sema::TDK_MiscellaneousDeductionFailure:
11547 case Sema::TDK_CUDATargetMismatch:
11548 return 3;
11549
11550 case Sema::TDK_InstantiationDepth:
11551 return 4;
11552
11553 case Sema::TDK_InvalidExplicitArguments:
11554 return 5;
11555
11556 case Sema::TDK_TooManyArguments:
11557 case Sema::TDK_TooFewArguments:
11558 return 6;
11559 }
11560 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "clang/lib/Sema/SemaOverload.cpp", 11560)
;
11561}
11562
11563namespace {
11564struct CompareOverloadCandidatesForDisplay {
11565 Sema &S;
11566 SourceLocation Loc;
11567 size_t NumArgs;
11568 OverloadCandidateSet::CandidateSetKind CSK;
11569
11570 CompareOverloadCandidatesForDisplay(
11571 Sema &S, SourceLocation Loc, size_t NArgs,
11572 OverloadCandidateSet::CandidateSetKind CSK)
11573 : S(S), NumArgs(NArgs), CSK(CSK) {}
11574
11575 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11576 // If there are too many or too few arguments, that's the high-order bit we
11577 // want to sort by, even if the immediate failure kind was something else.
11578 if (C->FailureKind == ovl_fail_too_many_arguments ||
11579 C->FailureKind == ovl_fail_too_few_arguments)
11580 return static_cast<OverloadFailureKind>(C->FailureKind);
11581
11582 if (C->Function) {
11583 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11584 return ovl_fail_too_many_arguments;
11585 if (NumArgs < C->Function->getMinRequiredArguments())
11586 return ovl_fail_too_few_arguments;
11587 }
11588
11589 return static_cast<OverloadFailureKind>(C->FailureKind);
11590 }
11591
11592 bool operator()(const OverloadCandidate *L,
11593 const OverloadCandidate *R) {
11594 // Fast-path this check.
11595 if (L == R) return false;
11596
11597 // Order first by viability.
11598 if (L->Viable) {
11599 if (!R->Viable) return true;
11600
11601 // TODO: introduce a tri-valued comparison for overload
11602 // candidates. Would be more worthwhile if we had a sort
11603 // that could exploit it.
11604 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11605 return true;
11606 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11607 return false;
11608 } else if (R->Viable)
11609 return false;
11610
11611 assert(L->Viable == R->Viable)(static_cast <bool> (L->Viable == R->Viable) ? void
(0) : __assert_fail ("L->Viable == R->Viable", "clang/lib/Sema/SemaOverload.cpp"
, 11611, __extension__ __PRETTY_FUNCTION__))
;
11612
11613 // Criteria by which we can sort non-viable candidates:
11614 if (!L->Viable) {
11615 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11616 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11617
11618 // 1. Arity mismatches come after other candidates.
11619 if (LFailureKind == ovl_fail_too_many_arguments ||
11620 LFailureKind == ovl_fail_too_few_arguments) {
11621 if (RFailureKind == ovl_fail_too_many_arguments ||
11622 RFailureKind == ovl_fail_too_few_arguments) {
11623 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11624 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11625 if (LDist == RDist) {
11626 if (LFailureKind == RFailureKind)
11627 // Sort non-surrogates before surrogates.
11628 return !L->IsSurrogate && R->IsSurrogate;
11629 // Sort candidates requiring fewer parameters than there were
11630 // arguments given after candidates requiring more parameters
11631 // than there were arguments given.
11632 return LFailureKind == ovl_fail_too_many_arguments;
11633 }
11634 return LDist < RDist;
11635 }
11636 return false;
11637 }
11638 if (RFailureKind == ovl_fail_too_many_arguments ||
11639 RFailureKind == ovl_fail_too_few_arguments)
11640 return true;
11641
11642 // 2. Bad conversions come first and are ordered by the number
11643 // of bad conversions and quality of good conversions.
11644 if (LFailureKind == ovl_fail_bad_conversion) {
11645 if (RFailureKind != ovl_fail_bad_conversion)
11646 return true;
11647
11648 // The conversion that can be fixed with a smaller number of changes,
11649 // comes first.
11650 unsigned numLFixes = L->Fix.NumConversionsFixed;
11651 unsigned numRFixes = R->Fix.NumConversionsFixed;
11652 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
11653 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
11654 if (numLFixes != numRFixes) {
11655 return numLFixes < numRFixes;
11656 }
11657
11658 // If there's any ordering between the defined conversions...
11659 // FIXME: this might not be transitive.
11660 assert(L->Conversions.size() == R->Conversions.size())(static_cast <bool> (L->Conversions.size() == R->
Conversions.size()) ? void (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "clang/lib/Sema/SemaOverload.cpp", 11660, __extension__ __PRETTY_FUNCTION__
))
;
11661
11662 int leftBetter = 0;
11663 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11664 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11665 switch (CompareImplicitConversionSequences(S, Loc,
11666 L->Conversions[I],
11667 R->Conversions[I])) {
11668 case ImplicitConversionSequence::Better:
11669 leftBetter++;
11670 break;
11671
11672 case ImplicitConversionSequence::Worse:
11673 leftBetter--;
11674 break;
11675
11676 case ImplicitConversionSequence::Indistinguishable:
11677 break;
11678 }
11679 }
11680 if (leftBetter > 0) return true;
11681 if (leftBetter < 0) return false;
11682
11683 } else if (RFailureKind == ovl_fail_bad_conversion)
11684 return false;
11685
11686 if (LFailureKind == ovl_fail_bad_deduction) {
11687 if (RFailureKind != ovl_fail_bad_deduction)
11688 return true;
11689
11690 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11691 return RankDeductionFailure(L->DeductionFailure)
11692 < RankDeductionFailure(R->DeductionFailure);
11693 } else if (RFailureKind == ovl_fail_bad_deduction)
11694 return false;
11695
11696 // TODO: others?
11697 }
11698
11699 // Sort everything else by location.
11700 SourceLocation LLoc = GetLocationForCandidate(L);
11701 SourceLocation RLoc = GetLocationForCandidate(R);
11702
11703 // Put candidates without locations (e.g. builtins) at the end.
11704 if (LLoc.isInvalid()) return false;
11705 if (RLoc.isInvalid()) return true;
11706
11707 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11708 }
11709};
11710}
11711
11712/// CompleteNonViableCandidate - Normally, overload resolution only
11713/// computes up to the first bad conversion. Produces the FixIt set if
11714/// possible.
11715static void
11716CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11717 ArrayRef<Expr *> Args,
11718 OverloadCandidateSet::CandidateSetKind CSK) {
11719 assert(!Cand->Viable)(static_cast <bool> (!Cand->Viable) ? void (0) : __assert_fail
("!Cand->Viable", "clang/lib/Sema/SemaOverload.cpp", 11719
, __extension__ __PRETTY_FUNCTION__))
;
11720
11721 // Don't do anything on failures other than bad conversion.
11722 if (Cand->FailureKind != ovl_fail_bad_conversion)
11723 return;
11724
11725 // We only want the FixIts if all the arguments can be corrected.
11726 bool Unfixable = false;
11727 // Use a implicit copy initialization to check conversion fixes.
11728 Cand->Fix.setConversionChecker(TryCopyInitialization);
11729
11730 // Attempt to fix the bad conversion.
11731 unsigned ConvCount = Cand->Conversions.size();
11732 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11733 ++ConvIdx) {
11734 assert(ConvIdx != ConvCount && "no bad conversion in candidate")(static_cast <bool> (ConvIdx != ConvCount && "no bad conversion in candidate"
) ? void (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "clang/lib/Sema/SemaOverload.cpp", 11734, __extension__ __PRETTY_FUNCTION__
))
;
11735 if (Cand->Conversions[ConvIdx].isInitialized() &&
11736 Cand->Conversions[ConvIdx].isBad()) {
11737 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11738 break;
11739 }
11740 }
11741
11742 // FIXME: this should probably be preserved from the overload
11743 // operation somehow.
11744 bool SuppressUserConversions = false;
11745
11746 unsigned ConvIdx = 0;
11747 unsigned ArgIdx = 0;
11748 ArrayRef<QualType> ParamTypes;
11749 bool Reversed = Cand->isReversed();
11750
11751 if (Cand->IsSurrogate) {
11752 QualType ConvType
11753 = Cand->Surrogate->getConversionType().getNonReferenceType();
11754 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11755 ConvType = ConvPtrType->getPointeeType();
11756 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11757 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11758 ConvIdx = 1;
11759 } else if (Cand->Function) {
11760 ParamTypes =
11761 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11762 if (isa<CXXMethodDecl>(Cand->Function) &&
11763 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11764 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11765 ConvIdx = 1;
11766 if (CSK == OverloadCandidateSet::CSK_Operator &&
11767 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11768 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11769 OO_Subscript)
11770 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11771 ArgIdx = 1;
11772 }
11773 } else {
11774 // Builtin operator.
11775 assert(ConvCount <= 3)(static_cast <bool> (ConvCount <= 3) ? void (0) : __assert_fail
("ConvCount <= 3", "clang/lib/Sema/SemaOverload.cpp", 11775
, __extension__ __PRETTY_FUNCTION__))
;
11776 ParamTypes = Cand->BuiltinParamTypes;
11777 }
11778
11779 // Fill in the rest of the conversions.
11780 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11781 ConvIdx != ConvCount;
11782 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11783 assert(ArgIdx < Args.size() && "no argument for this arg conversion")(static_cast <bool> (ArgIdx < Args.size() &&
"no argument for this arg conversion") ? void (0) : __assert_fail
("ArgIdx < Args.size() && \"no argument for this arg conversion\""
, "clang/lib/Sema/SemaOverload.cpp", 11783, __extension__ __PRETTY_FUNCTION__
))
;
11784 if (Cand->Conversions[ConvIdx].isInitialized()) {
11785 // We've already checked this conversion.
11786 } else if (ParamIdx < ParamTypes.size()) {
11787 if (ParamTypes[ParamIdx]->isDependentType())
11788 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11789 Args[ArgIdx]->getType());
11790 else {
11791 Cand->Conversions[ConvIdx] =
11792 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11793 SuppressUserConversions,
11794 /*InOverloadResolution=*/true,
11795 /*AllowObjCWritebackConversion=*/
11796 S.getLangOpts().ObjCAutoRefCount);
11797 // Store the FixIt in the candidate if it exists.
11798 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11799 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11800 }
11801 } else
11802 Cand->Conversions[ConvIdx].setEllipsis();
11803 }
11804}
11805
11806SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11807 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11808 SourceLocation OpLoc,
11809 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11810 // Sort the candidates by viability and position. Sorting directly would
11811 // be prohibitive, so we make a set of pointers and sort those.
11812 SmallVector<OverloadCandidate*, 32> Cands;
11813 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11814 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11815 if (!Filter(*Cand))
11816 continue;
11817 switch (OCD) {
11818 case OCD_AllCandidates:
11819 if (!Cand->Viable) {
11820 if (!Cand->Function && !Cand->IsSurrogate) {
11821 // This a non-viable builtin candidate. We do not, in general,
11822 // want to list every possible builtin candidate.
11823 continue;
11824 }
11825 CompleteNonViableCandidate(S, Cand, Args, Kind);
11826 }
11827 break;
11828
11829 case OCD_ViableCandidates:
11830 if (!Cand->Viable)
11831 continue;
11832 break;
11833
11834 case OCD_AmbiguousCandidates:
11835 if (!Cand->Best)
11836 continue;
11837 break;
11838 }
11839
11840 Cands.push_back(Cand);
11841 }
11842
11843 llvm::stable_sort(
11844 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11845
11846 return Cands;
11847}
11848
11849bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11850 SourceLocation OpLoc) {
11851 bool DeferHint = false;
11852 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11853 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11854 // host device candidates.
11855 auto WrongSidedCands =
11856 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11857 return (Cand.Viable == false &&
11858 Cand.FailureKind == ovl_fail_bad_target) ||
11859 (Cand.Function &&
11860 Cand.Function->template hasAttr<CUDAHostAttr>() &&
11861 Cand.Function->template hasAttr<CUDADeviceAttr>());
11862 });
11863 DeferHint = !WrongSidedCands.empty();
11864 }
11865 return DeferHint;
11866}
11867
11868/// When overload resolution fails, prints diagnostic messages containing the
11869/// candidates in the candidate set.
11870void OverloadCandidateSet::NoteCandidates(
11871 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11872 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11873 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11874
11875 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11876
11877 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11878
11879 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11880
11881 if (OCD == OCD_AmbiguousCandidates)
11882 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11883}
11884
11885void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11886 ArrayRef<OverloadCandidate *> Cands,
11887 StringRef Opc, SourceLocation OpLoc) {
11888 bool ReportedAmbiguousConversions = false;
11889
11890 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11891 unsigned CandsShown = 0;
11892 auto I = Cands.begin(), E = Cands.end();
11893 for (; I != E; ++I) {
11894 OverloadCandidate *Cand = *I;
11895
11896 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11897 ShowOverloads == Ovl_Best) {
11898 break;
11899 }
11900 ++CandsShown;
11901
11902 if (Cand->Function)
11903 NoteFunctionCandidate(S, Cand, Args.size(),
11904 /*TakingCandidateAddress=*/false, DestAS);
11905 else if (Cand->IsSurrogate)
11906 NoteSurrogateCandidate(S, Cand);
11907 else {
11908 assert(Cand->Viable &&(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 11909, __extension__ __PRETTY_FUNCTION__
))
11909 "Non-viable built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 11909, __extension__ __PRETTY_FUNCTION__
))
;
11910 // Generally we only see ambiguities including viable builtin
11911 // operators if overload resolution got screwed up by an
11912 // ambiguous user-defined conversion.
11913 //
11914 // FIXME: It's quite possible for different conversions to see
11915 // different ambiguities, though.
11916 if (!ReportedAmbiguousConversions) {
11917 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11918 ReportedAmbiguousConversions = true;
11919 }
11920
11921 // If this is a viable builtin, print it.
11922 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11923 }
11924 }
11925
11926 // Inform S.Diags that we've shown an overload set with N elements. This may
11927 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11928 S.Diags.overloadCandidatesShown(CandsShown);
11929
11930 if (I != E)
11931 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11932 shouldDeferDiags(S, Args, OpLoc))
11933 << int(E - I);
11934}
11935
11936static SourceLocation
11937GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11938 return Cand->Specialization ? Cand->Specialization->getLocation()
11939 : SourceLocation();
11940}
11941
11942namespace {
11943struct CompareTemplateSpecCandidatesForDisplay {
11944 Sema &S;
11945 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11946
11947 bool operator()(const TemplateSpecCandidate *L,
11948 const TemplateSpecCandidate *R) {
11949 // Fast-path this check.
11950 if (L == R)
11951 return false;
11952
11953 // Assuming that both candidates are not matches...
11954
11955 // Sort by the ranking of deduction failures.
11956 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11957 return RankDeductionFailure(L->DeductionFailure) <
11958 RankDeductionFailure(R->DeductionFailure);
11959
11960 // Sort everything else by location.
11961 SourceLocation LLoc = GetLocationForCandidate(L);
11962 SourceLocation RLoc = GetLocationForCandidate(R);
11963
11964 // Put candidates without locations (e.g. builtins) at the end.
11965 if (LLoc.isInvalid())
11966 return false;
11967 if (RLoc.isInvalid())
11968 return true;
11969
11970 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11971 }
11972};
11973}
11974
11975/// Diagnose a template argument deduction failure.
11976/// We are treating these failures as overload failures due to bad
11977/// deductions.
11978void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11979 bool ForTakingAddress) {
11980 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11981 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11982}
11983
11984void TemplateSpecCandidateSet::destroyCandidates() {
11985 for (iterator i = begin(), e = end(); i != e; ++i) {
11986 i->DeductionFailure.Destroy();
11987 }
11988}
11989
11990void TemplateSpecCandidateSet::clear() {
11991 destroyCandidates();
11992 Candidates.clear();
11993}
11994
11995/// NoteCandidates - When no template specialization match is found, prints
11996/// diagnostic messages containing the non-matching specializations that form
11997/// the candidate set.
11998/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11999/// OCD == OCD_AllCandidates and Cand->Viable == false.
12000void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12001 // Sort the candidates by position (assuming no candidate is a match).
12002 // Sorting directly would be prohibitive, so we make a set of pointers
12003 // and sort those.
12004 SmallVector<TemplateSpecCandidate *, 32> Cands;
12005 Cands.reserve(size());
12006 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12007 if (Cand->Specialization)
12008 Cands.push_back(Cand);
12009 // Otherwise, this is a non-matching builtin candidate. We do not,
12010 // in general, want to list every possible builtin candidate.
12011 }
12012
12013 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12014
12015 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12016 // for generalization purposes (?).
12017 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12018
12019 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12020 unsigned CandsShown = 0;
12021 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12022 TemplateSpecCandidate *Cand = *I;
12023
12024 // Set an arbitrary limit on the number of candidates we'll spam
12025 // the user with. FIXME: This limit should depend on details of the
12026 // candidate list.
12027 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12028 break;
12029 ++CandsShown;
12030
12031 assert(Cand->Specialization &&(static_cast <bool> (Cand->Specialization &&
"Non-matching built-in candidates are not added to Cands.") ?
void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 12032, __extension__ __PRETTY_FUNCTION__
))
12032 "Non-matching built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Specialization &&
"Non-matching built-in candidates are not added to Cands.") ?
void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 12032, __extension__ __PRETTY_FUNCTION__
))
;
12033 Cand->NoteDeductionFailure(S, ForTakingAddress);
12034 }
12035
12036 if (I != E)
12037 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12038}
12039
12040// [PossiblyAFunctionType] --> [Return]
12041// NonFunctionType --> NonFunctionType
12042// R (A) --> R(A)
12043// R (*)(A) --> R (A)
12044// R (&)(A) --> R (A)
12045// R (S::*)(A) --> R (A)
12046QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12047 QualType Ret = PossiblyAFunctionType;
12048 if (const PointerType *ToTypePtr =
12049 PossiblyAFunctionType->getAs<PointerType>())
12050 Ret = ToTypePtr->getPointeeType();
12051 else if (const ReferenceType *ToTypeRef =
12052 PossiblyAFunctionType->getAs<ReferenceType>())
12053 Ret = ToTypeRef->getPointeeType();
12054 else if (const MemberPointerType *MemTypePtr =
12055 PossiblyAFunctionType->getAs<MemberPointerType>())
12056 Ret = MemTypePtr->getPointeeType();
12057 Ret =
12058 Context.getCanonicalType(Ret).getUnqualifiedType();
12059 return Ret;
12060}
12061
12062static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12063 bool Complain = true) {
12064 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12065 S.DeduceReturnType(FD, Loc, Complain))
12066 return true;
12067
12068 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12069 if (S.getLangOpts().CPlusPlus17 &&
12070 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12071 !S.ResolveExceptionSpec(Loc, FPT))
12072 return true;
12073
12074 return false;
12075}
12076
12077namespace {
12078// A helper class to help with address of function resolution
12079// - allows us to avoid passing around all those ugly parameters
12080class AddressOfFunctionResolver {
12081 Sema& S;
12082 Expr* SourceExpr;
12083 const QualType& TargetType;
12084 QualType TargetFunctionType; // Extracted function type from target type
12085
12086 bool Complain;
12087 //DeclAccessPair& ResultFunctionAccessPair;
12088 ASTContext& Context;
12089
12090 bool TargetTypeIsNonStaticMemberFunction;
12091 bool FoundNonTemplateFunction;
12092 bool StaticMemberFunctionFromBoundPointer;
12093 bool HasComplained;
12094
12095 OverloadExpr::FindResult OvlExprInfo;
12096 OverloadExpr *OvlExpr;
12097 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12098 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12099 TemplateSpecCandidateSet FailedCandidates;
12100
12101public:
12102 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12103 const QualType &TargetType, bool Complain)
12104 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12105 Complain(Complain), Context(S.getASTContext()),
12106 TargetTypeIsNonStaticMemberFunction(
12107 !!TargetType->getAs<MemberPointerType>()),
12108 FoundNonTemplateFunction(false),
12109 StaticMemberFunctionFromBoundPointer(false),
12110 HasComplained(false),
12111 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12112 OvlExpr(OvlExprInfo.Expression),
12113 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12114 ExtractUnqualifiedFunctionTypeFromTargetType();
12115
12116 if (TargetFunctionType->isFunctionType()) {
12117 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12118 if (!UME->isImplicitAccess() &&
12119 !S.ResolveSingleFunctionTemplateSpecialization(UME))
12120 StaticMemberFunctionFromBoundPointer = true;
12121 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12122 DeclAccessPair dap;
12123 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12124 OvlExpr, false, &dap)) {
12125 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12126 if (!Method->isStatic()) {
12127 // If the target type is a non-function type and the function found
12128 // is a non-static member function, pretend as if that was the
12129 // target, it's the only possible type to end up with.
12130 TargetTypeIsNonStaticMemberFunction = true;
12131
12132 // And skip adding the function if its not in the proper form.
12133 // We'll diagnose this due to an empty set of functions.
12134 if (!OvlExprInfo.HasFormOfMemberPointer)
12135 return;
12136 }
12137
12138 Matches.push_back(std::make_pair(dap, Fn));
12139 }
12140 return;
12141 }
12142
12143 if (OvlExpr->hasExplicitTemplateArgs())
12144 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12145
12146 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12147 // C++ [over.over]p4:
12148 // If more than one function is selected, [...]
12149 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12150 if (FoundNonTemplateFunction)
12151 EliminateAllTemplateMatches();
12152 else
12153 EliminateAllExceptMostSpecializedTemplate();
12154 }
12155 }
12156
12157 if (S.getLangOpts().CUDA && Matches.size() > 1)
12158 EliminateSuboptimalCudaMatches();
12159 }
12160
12161 bool hasComplained() const { return HasComplained; }
12162
12163private:
12164 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12165 QualType Discard;
12166 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12167 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12168 }
12169
12170 /// \return true if A is considered a better overload candidate for the
12171 /// desired type than B.
12172 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12173 // If A doesn't have exactly the correct type, we don't want to classify it
12174 // as "better" than anything else. This way, the user is required to
12175 // disambiguate for us if there are multiple candidates and no exact match.
12176 return candidateHasExactlyCorrectType(A) &&
12177 (!candidateHasExactlyCorrectType(B) ||
12178 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12179 }
12180
12181 /// \return true if we were able to eliminate all but one overload candidate,
12182 /// false otherwise.
12183 bool eliminiateSuboptimalOverloadCandidates() {
12184 // Same algorithm as overload resolution -- one pass to pick the "best",
12185 // another pass to be sure that nothing is better than the best.
12186 auto Best = Matches.begin();
12187 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12188 if (isBetterCandidate(I->second, Best->second))
12189 Best = I;
12190
12191 const FunctionDecl *BestFn = Best->second;
12192 auto IsBestOrInferiorToBest = [this, BestFn](
12193 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12194 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12195 };
12196
12197 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12198 // option, so we can potentially give the user a better error
12199 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12200 return false;
12201 Matches[0] = *Best;
12202 Matches.resize(1);
12203 return true;
12204 }
12205
12206 bool isTargetTypeAFunction() const {
12207 return TargetFunctionType->isFunctionType();
12208 }
12209
12210 // [ToType] [Return]
12211
12212 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12213 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12214 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12215 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12216 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12217 }
12218
12219 // return true if any matching specializations were found
12220 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12221 const DeclAccessPair& CurAccessFunPair) {
12222 if (CXXMethodDecl *Method
12223 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12224 // Skip non-static function templates when converting to pointer, and
12225 // static when converting to member pointer.
12226 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12227 return false;
12228 }
12229 else if (TargetTypeIsNonStaticMemberFunction)
12230 return false;
12231
12232 // C++ [over.over]p2:
12233 // If the name is a function template, template argument deduction is
12234 // done (14.8.2.2), and if the argument deduction succeeds, the
12235 // resulting template argument list is used to generate a single
12236 // function template specialization, which is added to the set of
12237 // overloaded functions considered.
12238 FunctionDecl *Specialization = nullptr;
12239 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12240 if (Sema::TemplateDeductionResult Result
12241 = S.DeduceTemplateArguments(FunctionTemplate,
12242 &OvlExplicitTemplateArgs,
12243 TargetFunctionType, Specialization,
12244 Info, /*IsAddressOfFunction*/true)) {
12245 // Make a note of the failed deduction for diagnostics.
12246 FailedCandidates.addCandidate()
12247 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12248 MakeDeductionFailureInfo(Context, Result, Info));
12249 return false;
12250 }
12251
12252 // Template argument deduction ensures that we have an exact match or
12253 // compatible pointer-to-function arguments that would be adjusted by ICS.
12254 // This function template specicalization works.
12255 assert(S.isSameOrCompatibleFunctionType((static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "clang/lib/Sema/SemaOverload.cpp", 12257, __extension__ __PRETTY_FUNCTION__
))
12256 Context.getCanonicalType(Specialization->getType()),(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "clang/lib/Sema/SemaOverload.cpp", 12257, __extension__ __PRETTY_FUNCTION__
))
12257 Context.getCanonicalType(TargetFunctionType)))(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "clang/lib/Sema/SemaOverload.cpp", 12257, __extension__ __PRETTY_FUNCTION__
))
;
12258
12259 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12260 return false;
12261
12262 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12263 return true;
12264 }
12265
12266 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12267 const DeclAccessPair& CurAccessFunPair) {
12268 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12269 // Skip non-static functions when converting to pointer, and static
12270 // when converting to member pointer.
12271 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12272 return false;
12273 }
12274 else if (TargetTypeIsNonStaticMemberFunction)
12275 return false;
12276
12277 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12278 if (S.getLangOpts().CUDA)
12279 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12280 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12281 return false;
12282 if (FunDecl->isMultiVersion()) {
12283 const auto *TA = FunDecl->getAttr<TargetAttr>();
12284 if (TA && !TA->isDefaultVersion())
12285 return false;
12286 }
12287
12288 // If any candidate has a placeholder return type, trigger its deduction
12289 // now.
12290 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12291 Complain)) {
12292 HasComplained |= Complain;
12293 return false;
12294 }
12295
12296 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12297 return false;
12298
12299 // If we're in C, we need to support types that aren't exactly identical.
12300 if (!S.getLangOpts().CPlusPlus ||
12301 candidateHasExactlyCorrectType(FunDecl)) {
12302 Matches.push_back(std::make_pair(
12303 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12304 FoundNonTemplateFunction = true;
12305 return true;
12306 }
12307 }
12308
12309 return false;
12310 }
12311
12312 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12313 bool Ret = false;
12314
12315 // If the overload expression doesn't have the form of a pointer to
12316 // member, don't try to convert it to a pointer-to-member type.
12317 if (IsInvalidFormOfPointerToMemberFunction())
12318 return false;
12319
12320 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12321 E = OvlExpr->decls_end();
12322 I != E; ++I) {
12323 // Look through any using declarations to find the underlying function.
12324 NamedDecl *Fn = (*I)->getUnderlyingDecl();
12325
12326 // C++ [over.over]p3:
12327 // Non-member functions and static member functions match
12328 // targets of type "pointer-to-function" or "reference-to-function."
12329 // Nonstatic member functions match targets of
12330 // type "pointer-to-member-function."
12331 // Note that according to DR 247, the containing class does not matter.
12332 if (FunctionTemplateDecl *FunctionTemplate
12333 = dyn_cast<FunctionTemplateDecl>(Fn)) {
12334 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12335 Ret = true;
12336 }
12337 // If we have explicit template arguments supplied, skip non-templates.
12338 else if (!OvlExpr->hasExplicitTemplateArgs() &&
12339 AddMatchingNonTemplateFunction(Fn, I.getPair()))
12340 Ret = true;
12341 }
12342 assert(Ret || Matches.empty())(static_cast <bool> (Ret || Matches.empty()) ? void (0)
: __assert_fail ("Ret || Matches.empty()", "clang/lib/Sema/SemaOverload.cpp"
, 12342, __extension__ __PRETTY_FUNCTION__))
;
12343 return Ret;
12344 }
12345
12346 void EliminateAllExceptMostSpecializedTemplate() {
12347 // [...] and any given function template specialization F1 is
12348 // eliminated if the set contains a second function template
12349 // specialization whose function template is more specialized
12350 // than the function template of F1 according to the partial
12351 // ordering rules of 14.5.5.2.
12352
12353 // The algorithm specified above is quadratic. We instead use a
12354 // two-pass algorithm (similar to the one used to identify the
12355 // best viable function in an overload set) that identifies the
12356 // best function template (if it exists).
12357
12358 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12359 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12360 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12361
12362 // TODO: It looks like FailedCandidates does not serve much purpose
12363 // here, since the no_viable diagnostic has index 0.
12364 UnresolvedSetIterator Result = S.getMostSpecialized(
12365 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12366 SourceExpr->getBeginLoc(), S.PDiag(),
12367 S.PDiag(diag::err_addr_ovl_ambiguous)
12368 << Matches[0].second->getDeclName(),
12369 S.PDiag(diag::note_ovl_candidate)
12370 << (unsigned)oc_function << (unsigned)ocs_described_template,
12371 Complain, TargetFunctionType);
12372
12373 if (Result != MatchesCopy.end()) {
12374 // Make it the first and only element
12375 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12376 Matches[0].second = cast<FunctionDecl>(*Result);
12377 Matches.resize(1);
12378 } else
12379 HasComplained |= Complain;
12380 }
12381
12382 void EliminateAllTemplateMatches() {
12383 // [...] any function template specializations in the set are
12384 // eliminated if the set also contains a non-template function, [...]
12385 for (unsigned I = 0, N = Matches.size(); I != N; ) {
12386 if (Matches[I].second->getPrimaryTemplate() == nullptr)
12387 ++I;
12388 else {
12389 Matches[I] = Matches[--N];
12390 Matches.resize(N);
12391 }
12392 }
12393 }
12394
12395 void EliminateSuboptimalCudaMatches() {
12396 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12397 Matches);
12398 }
12399
12400public:
12401 void ComplainNoMatchesFound() const {
12402 assert(Matches.empty())(static_cast <bool> (Matches.empty()) ? void (0) : __assert_fail
("Matches.empty()", "clang/lib/Sema/SemaOverload.cpp", 12402
, __extension__ __PRETTY_FUNCTION__))
;
12403 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12404 << OvlExpr->getName() << TargetFunctionType
12405 << OvlExpr->getSourceRange();
12406 if (FailedCandidates.empty())
12407 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12408 /*TakingAddress=*/true);
12409 else {
12410 // We have some deduction failure messages. Use them to diagnose
12411 // the function templates, and diagnose the non-template candidates
12412 // normally.
12413 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12414 IEnd = OvlExpr->decls_end();
12415 I != IEnd; ++I)
12416 if (FunctionDecl *Fun =
12417 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12418 if (!functionHasPassObjectSizeParams(Fun))
12419 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12420 /*TakingAddress=*/true);
12421 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12422 }
12423 }
12424
12425 bool IsInvalidFormOfPointerToMemberFunction() const {
12426 return TargetTypeIsNonStaticMemberFunction &&
12427 !OvlExprInfo.HasFormOfMemberPointer;
12428 }
12429
12430 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12431 // TODO: Should we condition this on whether any functions might
12432 // have matched, or is it more appropriate to do that in callers?
12433 // TODO: a fixit wouldn't hurt.
12434 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12435 << TargetType << OvlExpr->getSourceRange();
12436 }
12437
12438 bool IsStaticMemberFunctionFromBoundPointer() const {
12439 return StaticMemberFunctionFromBoundPointer;
12440 }
12441
12442 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12443 S.Diag(OvlExpr->getBeginLoc(),
12444 diag::err_invalid_form_pointer_member_function)
12445 << OvlExpr->getSourceRange();
12446 }
12447
12448 void ComplainOfInvalidConversion() const {
12449 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12450 << OvlExpr->getName() << TargetType;
12451 }
12452
12453 void ComplainMultipleMatchesFound() const {
12454 assert(Matches.size() > 1)(static_cast <bool> (Matches.size() > 1) ? void (0) :
__assert_fail ("Matches.size() > 1", "clang/lib/Sema/SemaOverload.cpp"
, 12454, __extension__ __PRETTY_FUNCTION__))
;
12455 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12456 << OvlExpr->getName() << OvlExpr->getSourceRange();
12457 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12458 /*TakingAddress=*/true);
12459 }
12460
12461 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12462
12463 int getNumMatches() const { return Matches.size(); }
12464
12465 FunctionDecl* getMatchingFunctionDecl() const {
12466 if (Matches.size() != 1) return nullptr;
12467 return Matches[0].second;
12468 }
12469
12470 const DeclAccessPair* getMatchingFunctionAccessPair() const {
12471 if (Matches.size() != 1) return nullptr;
12472 return &Matches[0].first;
12473 }
12474};
12475}
12476
12477/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12478/// an overloaded function (C++ [over.over]), where @p From is an
12479/// expression with overloaded function type and @p ToType is the type
12480/// we're trying to resolve to. For example:
12481///
12482/// @code
12483/// int f(double);
12484/// int f(int);
12485///
12486/// int (*pfd)(double) = f; // selects f(double)
12487/// @endcode
12488///
12489/// This routine returns the resulting FunctionDecl if it could be
12490/// resolved, and NULL otherwise. When @p Complain is true, this
12491/// routine will emit diagnostics if there is an error.
12492FunctionDecl *
12493Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12494 QualType TargetType,
12495 bool Complain,
12496 DeclAccessPair &FoundResult,
12497 bool *pHadMultipleCandidates) {
12498 assert(AddressOfExpr->getType() == Context.OverloadTy)(static_cast <bool> (AddressOfExpr->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 12498, __extension__ __PRETTY_FUNCTION__
))
;
12499
12500 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12501 Complain);
12502 int NumMatches = Resolver.getNumMatches();
12503 FunctionDecl *Fn = nullptr;
12504 bool ShouldComplain = Complain && !Resolver.hasComplained();
12505 if (NumMatches == 0 && ShouldComplain) {
12506 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12507 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12508 else
12509 Resolver.ComplainNoMatchesFound();
12510 }
12511 else if (NumMatches > 1 && ShouldComplain)
12512 Resolver.ComplainMultipleMatchesFound();
12513 else if (NumMatches == 1) {
12514 Fn = Resolver.getMatchingFunctionDecl();
12515 assert(Fn)(static_cast <bool> (Fn) ? void (0) : __assert_fail ("Fn"
, "clang/lib/Sema/SemaOverload.cpp", 12515, __extension__ __PRETTY_FUNCTION__
))
;
12516 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12517 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12518 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12519 if (Complain) {
12520 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12521 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12522 else
12523 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12524 }
12525 }
12526
12527 if (pHadMultipleCandidates)
12528 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12529 return Fn;
12530}
12531
12532/// Given an expression that refers to an overloaded function, try to
12533/// resolve that function to a single function that can have its address taken.
12534/// This will modify `Pair` iff it returns non-null.
12535///
12536/// This routine can only succeed if from all of the candidates in the overload
12537/// set for SrcExpr that can have their addresses taken, there is one candidate
12538/// that is more constrained than the rest.
12539FunctionDecl *
12540Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12541 OverloadExpr::FindResult R = OverloadExpr::find(E);
12542 OverloadExpr *Ovl = R.Expression;
12543 bool IsResultAmbiguous = false;
12544 FunctionDecl *Result = nullptr;
12545 DeclAccessPair DAP;
12546 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12547
12548 auto CheckMoreConstrained =
12549 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12550 SmallVector<const Expr *, 1> AC1, AC2;
12551 FD1->getAssociatedConstraints(AC1);
12552 FD2->getAssociatedConstraints(AC2);
12553 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12554 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12555 return None;
12556 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12557 return None;
12558 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12559 return None;
12560 return AtLeastAsConstrained1;
12561 };
12562
12563 // Don't use the AddressOfResolver because we're specifically looking for
12564 // cases where we have one overload candidate that lacks
12565 // enable_if/pass_object_size/...
12566 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12567 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12568 if (!FD)
12569 return nullptr;
12570
12571 if (!checkAddressOfFunctionIsAvailable(FD))
12572 continue;
12573
12574 // We have more than one result - see if it is more constrained than the
12575 // previous one.
12576 if (Result) {
12577 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12578 Result);
12579 if (!MoreConstrainedThanPrevious) {
12580 IsResultAmbiguous = true;
12581 AmbiguousDecls.push_back(FD);
12582 continue;
12583 }
12584 if (!*MoreConstrainedThanPrevious)
12585 continue;
12586 // FD is more constrained - replace Result with it.
12587 }
12588 IsResultAmbiguous = false;
12589 DAP = I.getPair();
12590 Result = FD;
12591 }
12592
12593 if (IsResultAmbiguous)
12594 return nullptr;
12595
12596 if (Result) {
12597 SmallVector<const Expr *, 1> ResultAC;
12598 // We skipped over some ambiguous declarations which might be ambiguous with
12599 // the selected result.
12600 for (FunctionDecl *Skipped : AmbiguousDecls)
12601 if (!CheckMoreConstrained(Skipped, Result))
12602 return nullptr;
12603 Pair = DAP;
12604 }
12605 return Result;
12606}
12607
12608/// Given an overloaded function, tries to turn it into a non-overloaded
12609/// function reference using resolveAddressOfSingleOverloadCandidate. This
12610/// will perform access checks, diagnose the use of the resultant decl, and, if
12611/// requested, potentially perform a function-to-pointer decay.
12612///
12613/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12614/// Otherwise, returns true. This may emit diagnostics and return true.
12615bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12616 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
12617 Expr *E = SrcExpr.get();
12618 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")(static_cast <bool> (E->getType() == Context.OverloadTy
&& "SrcExpr must be an overload") ? void (0) : __assert_fail
("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "clang/lib/Sema/SemaOverload.cpp", 12618, __extension__ __PRETTY_FUNCTION__
))
;
12619
12620 DeclAccessPair DAP;
12621 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12622 if (!Found || Found->isCPUDispatchMultiVersion() ||
12623 Found->isCPUSpecificMultiVersion())
12624 return false;
12625
12626 // Emitting multiple diagnostics for a function that is both inaccessible and
12627 // unavailable is consistent with our behavior elsewhere. So, always check
12628 // for both.
12629 DiagnoseUseOfDecl(Found, E->getExprLoc());
12630 CheckAddressOfMemberAccess(E, DAP);
12631 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12632 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
12633 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12634 else
12635 SrcExpr = Fixed;
12636 return true;
12637}
12638
12639/// Given an expression that refers to an overloaded function, try to
12640/// resolve that overloaded function expression down to a single function.
12641///
12642/// This routine can only resolve template-ids that refer to a single function
12643/// template, where that template-id refers to a single template whose template
12644/// arguments are either provided by the template-id or have defaults,
12645/// as described in C++0x [temp.arg.explicit]p3.
12646///
12647/// If no template-ids are found, no diagnostics are emitted and NULL is
12648/// returned.
12649FunctionDecl *
12650Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12651 bool Complain,
12652 DeclAccessPair *FoundResult) {
12653 // C++ [over.over]p1:
12654 // [...] [Note: any redundant set of parentheses surrounding the
12655 // overloaded function name is ignored (5.1). ]
12656 // C++ [over.over]p1:
12657 // [...] The overloaded function name can be preceded by the &
12658 // operator.
12659
12660 // If we didn't actually find any template-ids, we're done.
12661 if (!ovl->hasExplicitTemplateArgs())
12662 return nullptr;
12663
12664 TemplateArgumentListInfo ExplicitTemplateArgs;
12665 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12666 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12667
12668 // Look through all of the overloaded functions, searching for one
12669 // whose type matches exactly.
12670 FunctionDecl *Matched = nullptr;
12671 for (UnresolvedSetIterator I = ovl->decls_begin(),
12672 E = ovl->decls_end(); I != E; ++I) {
12673 // C++0x [temp.arg.explicit]p3:
12674 // [...] In contexts where deduction is done and fails, or in contexts
12675 // where deduction is not done, if a template argument list is
12676 // specified and it, along with any default template arguments,
12677 // identifies a single function template specialization, then the
12678 // template-id is an lvalue for the function template specialization.
12679 FunctionTemplateDecl *FunctionTemplate
12680 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12681
12682 // C++ [over.over]p2:
12683 // If the name is a function template, template argument deduction is
12684 // done (14.8.2.2), and if the argument deduction succeeds, the
12685 // resulting template argument list is used to generate a single
12686 // function template specialization, which is added to the set of
12687 // overloaded functions considered.
12688 FunctionDecl *Specialization = nullptr;
12689 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12690 if (TemplateDeductionResult Result
12691 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12692 Specialization, Info,
12693 /*IsAddressOfFunction*/true)) {
12694 // Make a note of the failed deduction for diagnostics.
12695 // TODO: Actually use the failed-deduction info?
12696 FailedCandidates.addCandidate()
12697 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12698 MakeDeductionFailureInfo(Context, Result, Info));
12699 continue;
12700 }
12701
12702 assert(Specialization && "no specialization and no error?")(static_cast <bool> (Specialization && "no specialization and no error?"
) ? void (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "clang/lib/Sema/SemaOverload.cpp", 12702, __extension__ __PRETTY_FUNCTION__
))
;
12703
12704 // Multiple matches; we can't resolve to a single declaration.
12705 if (Matched) {
12706 if (Complain) {
12707 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12708 << ovl->getName();
12709 NoteAllOverloadCandidates(ovl);
12710 }
12711 return nullptr;
12712 }
12713
12714 Matched = Specialization;
12715 if (FoundResult) *FoundResult = I.getPair();
12716 }
12717
12718 if (Matched &&
12719 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12720 return nullptr;
12721
12722 return Matched;
12723}
12724
12725// Resolve and fix an overloaded expression that can be resolved
12726// because it identifies a single function template specialization.
12727//
12728// Last three arguments should only be supplied if Complain = true
12729//
12730// Return true if it was logically possible to so resolve the
12731// expression, regardless of whether or not it succeeded. Always
12732// returns true if 'complain' is set.
12733bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12734 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
12735 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
12736 unsigned DiagIDForComplaining) {
12737 assert(SrcExpr.get()->getType() == Context.OverloadTy)(static_cast <bool> (SrcExpr.get()->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 12737, __extension__ __PRETTY_FUNCTION__
))
;
12738
12739 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12740
12741 DeclAccessPair found;
12742 ExprResult SingleFunctionExpression;
12743 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12744 ovl.Expression, /*complain*/ false, &found)) {
12745 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12746 SrcExpr = ExprError();
12747 return true;
12748 }
12749
12750 // It is only correct to resolve to an instance method if we're
12751 // resolving a form that's permitted to be a pointer to member.
12752 // Otherwise we'll end up making a bound member expression, which
12753 // is illegal in all the contexts we resolve like this.
12754 if (!ovl.HasFormOfMemberPointer &&
12755 isa<CXXMethodDecl>(fn) &&
12756 cast<CXXMethodDecl>(fn)->isInstance()) {
12757 if (!complain) return false;
12758
12759 Diag(ovl.Expression->getExprLoc(),
12760 diag::err_bound_member_function)
12761 << 0 << ovl.Expression->getSourceRange();
12762
12763 // TODO: I believe we only end up here if there's a mix of
12764 // static and non-static candidates (otherwise the expression
12765 // would have 'bound member' type, not 'overload' type).
12766 // Ideally we would note which candidate was chosen and why
12767 // the static candidates were rejected.
12768 SrcExpr = ExprError();
12769 return true;
12770 }
12771
12772 // Fix the expression to refer to 'fn'.
12773 SingleFunctionExpression =
12774 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12775
12776 // If desired, do function-to-pointer decay.
12777 if (doFunctionPointerConversion) {
12778 SingleFunctionExpression =
12779 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12780 if (SingleFunctionExpression.isInvalid()) {
12781 SrcExpr = ExprError();
12782 return true;
12783 }
12784 }
12785 }
12786
12787 if (!SingleFunctionExpression.isUsable()) {
12788 if (complain) {
12789 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12790 << ovl.Expression->getName()
12791 << DestTypeForComplaining
12792 << OpRangeForComplaining
12793 << ovl.Expression->getQualifierLoc().getSourceRange();
12794 NoteAllOverloadCandidates(SrcExpr.get());
12795
12796 SrcExpr = ExprError();
12797 return true;
12798 }
12799
12800 return false;
12801 }
12802
12803 SrcExpr = SingleFunctionExpression;
12804 return true;
12805}
12806
12807/// Add a single candidate to the overload set.
12808static void AddOverloadedCallCandidate(Sema &S,
12809 DeclAccessPair FoundDecl,
12810 TemplateArgumentListInfo *ExplicitTemplateArgs,
12811 ArrayRef<Expr *> Args,
12812 OverloadCandidateSet &CandidateSet,
12813 bool PartialOverloading,
12814 bool KnownValid) {
12815 NamedDecl *Callee = FoundDecl.getDecl();
12816 if (isa<UsingShadowDecl>(Callee))
12817 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12818
12819 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12820 if (ExplicitTemplateArgs) {
12821 assert(!KnownValid && "Explicit template arguments?")(static_cast <bool> (!KnownValid && "Explicit template arguments?"
) ? void (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "clang/lib/Sema/SemaOverload.cpp", 12821, __extension__ __PRETTY_FUNCTION__
))
;
12822 return;
12823 }
12824 // Prevent ill-formed function decls to be added as overload candidates.
12825 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12826 return;
12827
12828 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12829 /*SuppressUserConversions=*/false,
12830 PartialOverloading);
12831 return;
12832 }
12833
12834 if (FunctionTemplateDecl *FuncTemplate
12835 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12836 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12837 ExplicitTemplateArgs, Args, CandidateSet,
12838 /*SuppressUserConversions=*/false,
12839 PartialOverloading);
12840 return;
12841 }
12842
12843 assert(!KnownValid && "unhandled case in overloaded call candidate")(static_cast <bool> (!KnownValid && "unhandled case in overloaded call candidate"
) ? void (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "clang/lib/Sema/SemaOverload.cpp", 12843, __extension__ __PRETTY_FUNCTION__
))
;
12844}
12845
12846/// Add the overload candidates named by callee and/or found by argument
12847/// dependent lookup to the given overload set.
12848void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12849 ArrayRef<Expr *> Args,
12850 OverloadCandidateSet &CandidateSet,
12851 bool PartialOverloading) {
12852
12853#ifndef NDEBUG
12854 // Verify that ArgumentDependentLookup is consistent with the rules
12855 // in C++0x [basic.lookup.argdep]p3:
12856 //
12857 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12858 // and let Y be the lookup set produced by argument dependent
12859 // lookup (defined as follows). If X contains
12860 //
12861 // -- a declaration of a class member, or
12862 //
12863 // -- a block-scope function declaration that is not a
12864 // using-declaration, or
12865 //
12866 // -- a declaration that is neither a function or a function
12867 // template
12868 //
12869 // then Y is empty.
12870
12871 if (ULE->requiresADL()) {
12872 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12873 E = ULE->decls_end(); I != E; ++I) {
12874 assert(!(*I)->getDeclContext()->isRecord())(static_cast <bool> (!(*I)->getDeclContext()->isRecord
()) ? void (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "clang/lib/Sema/SemaOverload.cpp", 12874, __extension__ __PRETTY_FUNCTION__
))
;
12875 assert(isa<UsingShadowDecl>(*I) ||(static_cast <bool> (isa<UsingShadowDecl>(*I) || !
(*I)->getDeclContext()->isFunctionOrMethod()) ? void (0
) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "clang/lib/Sema/SemaOverload.cpp", 12876, __extension__ __PRETTY_FUNCTION__
))
12876 !(*I)->getDeclContext()->isFunctionOrMethod())(static_cast <bool> (isa<UsingShadowDecl>(*I) || !
(*I)->getDeclContext()->isFunctionOrMethod()) ? void (0
) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "clang/lib/Sema/SemaOverload.cpp", 12876, __extension__ __PRETTY_FUNCTION__
))
;
12877 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(static_cast <bool> ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? void (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "clang/lib/Sema/SemaOverload.cpp", 12877, __extension__ __PRETTY_FUNCTION__
))
;
12878 }
12879 }
12880#endif
12881
12882 // It would be nice to avoid this copy.
12883 TemplateArgumentListInfo TABuffer;
12884 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12885 if (ULE->hasExplicitTemplateArgs()) {
12886 ULE->copyTemplateArgumentsInto(TABuffer);
12887 ExplicitTemplateArgs = &TABuffer;
12888 }
12889
12890 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12891 E = ULE->decls_end(); I != E; ++I)
12892 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12893 CandidateSet, PartialOverloading,
12894 /*KnownValid*/ true);
12895
12896 if (ULE->requiresADL())
12897 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12898 Args, ExplicitTemplateArgs,
12899 CandidateSet, PartialOverloading);
12900}
12901
12902/// Add the call candidates from the given set of lookup results to the given
12903/// overload set. Non-function lookup results are ignored.
12904void Sema::AddOverloadedCallCandidates(
12905 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12906 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12907 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12908 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12909 CandidateSet, false, /*KnownValid*/ false);
12910}
12911
12912/// Determine whether a declaration with the specified name could be moved into
12913/// a different namespace.
12914static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12915 switch (Name.getCXXOverloadedOperator()) {
12916 case OO_New: case OO_Array_New:
12917 case OO_Delete: case OO_Array_Delete:
12918 return false;
12919
12920 default:
12921 return true;
12922 }
12923}
12924
12925/// Attempt to recover from an ill-formed use of a non-dependent name in a
12926/// template, where the non-dependent name was declared after the template
12927/// was defined. This is common in code written for a compilers which do not
12928/// correctly implement two-stage name lookup.
12929///
12930/// Returns true if a viable candidate was found and a diagnostic was issued.
12931static bool DiagnoseTwoPhaseLookup(
12932 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12933 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12934 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12935 CXXRecordDecl **FoundInClass = nullptr) {
12936 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12937 return false;
12938
12939 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12940 if (DC->isTransparentContext())
12941 continue;
12942
12943 SemaRef.LookupQualifiedName(R, DC);
12944
12945 if (!R.empty()) {
12946 R.suppressDiagnostics();
12947
12948 OverloadCandidateSet Candidates(FnLoc, CSK);
12949 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12950 Candidates);
12951
12952 OverloadCandidateSet::iterator Best;
12953 OverloadingResult OR =
12954 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12955
12956 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12957 // We either found non-function declarations or a best viable function
12958 // at class scope. A class-scope lookup result disables ADL. Don't
12959 // look past this, but let the caller know that we found something that
12960 // either is, or might be, usable in this class.
12961 if (FoundInClass) {
12962 *FoundInClass = RD;
12963 if (OR == OR_Success) {
12964 R.clear();
12965 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12966 R.resolveKind();
12967 }
12968 }
12969 return false;
12970 }
12971
12972 if (OR != OR_Success) {
12973 // There wasn't a unique best function or function template.
12974 return false;
12975 }
12976
12977 // Find the namespaces where ADL would have looked, and suggest
12978 // declaring the function there instead.
12979 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12980 Sema::AssociatedClassSet AssociatedClasses;
12981 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12982 AssociatedNamespaces,
12983 AssociatedClasses);
12984 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12985 if (canBeDeclaredInNamespace(R.getLookupName())) {
12986 DeclContext *Std = SemaRef.getStdNamespace();
12987 for (Sema::AssociatedNamespaceSet::iterator
12988 it = AssociatedNamespaces.begin(),
12989 end = AssociatedNamespaces.end(); it != end; ++it) {
12990 // Never suggest declaring a function within namespace 'std'.
12991 if (Std && Std->Encloses(*it))
12992 continue;
12993
12994 // Never suggest declaring a function within a namespace with a
12995 // reserved name, like __gnu_cxx.
12996 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12997 if (NS &&
12998 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12999 continue;
13000
13001 SuggestedNamespaces.insert(*it);
13002 }
13003 }
13004
13005 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13006 << R.getLookupName();
13007 if (SuggestedNamespaces.empty()) {
13008 SemaRef.Diag(Best->Function->getLocation(),
13009 diag::note_not_found_by_two_phase_lookup)
13010 << R.getLookupName() << 0;
13011 } else if (SuggestedNamespaces.size() == 1) {
13012 SemaRef.Diag(Best->Function->getLocation(),
13013 diag::note_not_found_by_two_phase_lookup)
13014 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13015 } else {
13016 // FIXME: It would be useful to list the associated namespaces here,
13017 // but the diagnostics infrastructure doesn't provide a way to produce
13018 // a localized representation of a list of items.
13019 SemaRef.Diag(Best->Function->getLocation(),
13020 diag::note_not_found_by_two_phase_lookup)
13021 << R.getLookupName() << 2;
13022 }
13023
13024 // Try to recover by calling this function.
13025 return true;
13026 }
13027
13028 R.clear();
13029 }
13030
13031 return false;
13032}
13033
13034/// Attempt to recover from ill-formed use of a non-dependent operator in a
13035/// template, where the non-dependent operator was declared after the template
13036/// was defined.
13037///
13038/// Returns true if a viable candidate was found and a diagnostic was issued.
13039static bool
13040DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13041 SourceLocation OpLoc,
13042 ArrayRef<Expr *> Args) {
13043 DeclarationName OpName =
13044 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13045 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13046 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13047 OverloadCandidateSet::CSK_Operator,
13048 /*ExplicitTemplateArgs=*/nullptr, Args);
13049}
13050
13051namespace {
13052class BuildRecoveryCallExprRAII {
13053 Sema &SemaRef;
13054public:
13055 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
13056 assert(SemaRef.IsBuildingRecoveryCallExpr == false)(static_cast <bool> (SemaRef.IsBuildingRecoveryCallExpr
== false) ? void (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "clang/lib/Sema/SemaOverload.cpp", 13056, __extension__ __PRETTY_FUNCTION__
))
;
13057 SemaRef.IsBuildingRecoveryCallExpr = true;
13058 }
13059
13060 ~BuildRecoveryCallExprRAII() {
13061 SemaRef.IsBuildingRecoveryCallExpr = false;
13062 }
13063};
13064
13065}
13066
13067/// Attempts to recover from a call where no functions were found.
13068///
13069/// This function will do one of three things:
13070/// * Diagnose, recover, and return a recovery expression.
13071/// * Diagnose, fail to recover, and return ExprError().
13072/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13073/// expected to diagnose as appropriate.
13074static ExprResult
13075BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13076 UnresolvedLookupExpr *ULE,
13077 SourceLocation LParenLoc,
13078 MutableArrayRef<Expr *> Args,
13079 SourceLocation RParenLoc,
13080 bool EmptyLookup, bool AllowTypoCorrection) {
13081 // Do not try to recover if it is already building a recovery call.
13082 // This stops infinite loops for template instantiations like
13083 //
13084 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13085 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13086 if (SemaRef.IsBuildingRecoveryCallExpr)
13087 return ExprResult();
13088 BuildRecoveryCallExprRAII RCE(SemaRef);
13089
13090 CXXScopeSpec SS;
13091 SS.Adopt(ULE->getQualifierLoc());
13092 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13093
13094 TemplateArgumentListInfo TABuffer;
13095 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13096 if (ULE->hasExplicitTemplateArgs()) {
13097 ULE->copyTemplateArgumentsInto(TABuffer);
13098 ExplicitTemplateArgs = &TABuffer;
13099 }
13100
13101 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13102 Sema::LookupOrdinaryName);
13103 CXXRecordDecl *FoundInClass = nullptr;
13104 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13105 OverloadCandidateSet::CSK_Normal,
13106 ExplicitTemplateArgs, Args, &FoundInClass)) {
13107 // OK, diagnosed a two-phase lookup issue.
13108 } else if (EmptyLookup) {
13109 // Try to recover from an empty lookup with typo correction.
13110 R.clear();
13111 NoTypoCorrectionCCC NoTypoValidator{};
13112 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13113 ExplicitTemplateArgs != nullptr,
13114 dyn_cast<MemberExpr>(Fn));
13115 CorrectionCandidateCallback &Validator =
13116 AllowTypoCorrection
13117 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13118 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13119 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13120 Args))
13121 return ExprError();
13122 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13123 // We found a usable declaration of the name in a dependent base of some
13124 // enclosing class.
13125 // FIXME: We should also explain why the candidates found by name lookup
13126 // were not viable.
13127 if (SemaRef.DiagnoseDependentMemberLookup(R))
13128 return ExprError();
13129 } else {
13130 // We had viable candidates and couldn't recover; let the caller diagnose
13131 // this.
13132 return ExprResult();
13133 }
13134
13135 // If we get here, we should have issued a diagnostic and formed a recovery
13136 // lookup result.
13137 assert(!R.empty() && "lookup results empty despite recovery")(static_cast <bool> (!R.empty() && "lookup results empty despite recovery"
) ? void (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "clang/lib/Sema/SemaOverload.cpp", 13137, __extension__ __PRETTY_FUNCTION__
))
;
13138
13139 // If recovery created an ambiguity, just bail out.
13140 if (R.isAmbiguous()) {
13141 R.suppressDiagnostics();
13142 return ExprError();
13143 }
13144
13145 // Build an implicit member call if appropriate. Just drop the
13146 // casts and such from the call, we don't really care.
13147 ExprResult NewFn = ExprError();
13148 if ((*R.begin())->isCXXClassMember())
13149 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13150 ExplicitTemplateArgs, S);
13151 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13152 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13153 ExplicitTemplateArgs);
13154 else
13155 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13156
13157 if (NewFn.isInvalid())
13158 return ExprError();
13159
13160 // This shouldn't cause an infinite loop because we're giving it
13161 // an expression with viable lookup results, which should never
13162 // end up here.
13163 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13164 MultiExprArg(Args.data(), Args.size()),
13165 RParenLoc);
13166}
13167
13168/// Constructs and populates an OverloadedCandidateSet from
13169/// the given function.
13170/// \returns true when an the ExprResult output parameter has been set.
13171bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13172 UnresolvedLookupExpr *ULE,
13173 MultiExprArg Args,
13174 SourceLocation RParenLoc,
13175 OverloadCandidateSet *CandidateSet,
13176 ExprResult *Result) {
13177#ifndef NDEBUG
13178 if (ULE->requiresADL()) {
13179 // To do ADL, we must have found an unqualified name.
13180 assert(!ULE->getQualifier() && "qualified name with ADL")(static_cast <bool> (!ULE->getQualifier() &&
"qualified name with ADL") ? void (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "clang/lib/Sema/SemaOverload.cpp", 13180, __extension__ __PRETTY_FUNCTION__
))
;
13181
13182 // We don't perform ADL for implicit declarations of builtins.
13183 // Verify that this was correctly set up.
13184 FunctionDecl *F;
13185 if (ULE->decls_begin() != ULE->decls_end() &&
13186 ULE->decls_begin() + 1 == ULE->decls_end() &&
13187 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13188 F->getBuiltinID() && F->isImplicit())
13189 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "clang/lib/Sema/SemaOverload.cpp", 13189)
;
13190
13191 // We don't perform ADL in C.
13192 assert(getLangOpts().CPlusPlus && "ADL enabled in C")(static_cast <bool> (getLangOpts().CPlusPlus &&
"ADL enabled in C") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "clang/lib/Sema/SemaOverload.cpp", 13192, __extension__ __PRETTY_FUNCTION__
))
;
13193 }
13194#endif
13195
13196 UnbridgedCastsSet UnbridgedCasts;
13197 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13198 *Result = ExprError();
13199 return true;
13200 }
13201
13202 // Add the functions denoted by the callee to the set of candidate
13203 // functions, including those from argument-dependent lookup.
13204 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13205
13206 if (getLangOpts().MSVCCompat &&
13207 CurContext->isDependentContext() && !isSFINAEContext() &&
13208 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13209
13210 OverloadCandidateSet::iterator Best;
13211 if (CandidateSet->empty() ||
13212 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13213 OR_No_Viable_Function) {
13214 // In Microsoft mode, if we are inside a template class member function
13215 // then create a type dependent CallExpr. The goal is to postpone name
13216 // lookup to instantiation time to be able to search into type dependent
13217 // base classes.
13218 CallExpr *CE =
13219 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13220 RParenLoc, CurFPFeatureOverrides());
13221 CE->markDependentForPostponedNameLookup();
13222 *Result = CE;
13223 return true;
13224 }
13225 }
13226
13227 if (CandidateSet->empty())
13228 return false;
13229
13230 UnbridgedCasts.restore();
13231 return false;
13232}
13233
13234// Guess at what the return type for an unresolvable overload should be.
13235static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13236 OverloadCandidateSet::iterator *Best) {
13237 llvm::Optional<QualType> Result;
13238 // Adjust Type after seeing a candidate.
13239 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13240 if (!Candidate.Function)
13241 return;
13242 if (Candidate.Function->isInvalidDecl())
13243 return;
13244 QualType T = Candidate.Function->getReturnType();
13245 if (T.isNull())
13246 return;
13247 if (!Result)
13248 Result = T;
13249 else if (Result != T)
13250 Result = QualType();
13251 };
13252
13253 // Look for an unambiguous type from a progressively larger subset.
13254 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13255 //
13256 // First, consider only the best candidate.
13257 if (Best && *Best != CS.end())
13258 ConsiderCandidate(**Best);
13259 // Next, consider only viable candidates.
13260 if (!Result)
13261 for (const auto &C : CS)
13262 if (C.Viable)
13263 ConsiderCandidate(C);
13264 // Finally, consider all candidates.
13265 if (!Result)
13266 for (const auto &C : CS)
13267 ConsiderCandidate(C);
13268
13269 if (!Result)
13270 return QualType();
13271 auto Value = *Result;
13272 if (Value.isNull() || Value->isUndeducedType())
13273 return QualType();
13274 return Value;
13275}
13276
13277/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13278/// the completed call expression. If overload resolution fails, emits
13279/// diagnostics and returns ExprError()
13280static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13281 UnresolvedLookupExpr *ULE,
13282 SourceLocation LParenLoc,
13283 MultiExprArg Args,
13284 SourceLocation RParenLoc,
13285 Expr *ExecConfig,
13286 OverloadCandidateSet *CandidateSet,
13287 OverloadCandidateSet::iterator *Best,
13288 OverloadingResult OverloadResult,
13289 bool AllowTypoCorrection) {
13290 switch (OverloadResult) {
13291 case OR_Success: {
13292 FunctionDecl *FDecl = (*Best)->Function;
13293 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13294 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13295 return ExprError();
13296 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13297 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13298 ExecConfig, /*IsExecConfig=*/false,
13299 (*Best)->IsADLCandidate);
13300 }
13301
13302 case OR_No_Viable_Function: {
13303 // Try to recover by looking for viable functions which the user might
13304 // have meant to call.
13305 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13306 Args, RParenLoc,
13307 CandidateSet->empty(),
13308 AllowTypoCorrection);
13309 if (Recovery.isInvalid() || Recovery.isUsable())
13310 return Recovery;
13311
13312 // If the user passes in a function that we can't take the address of, we
13313 // generally end up emitting really bad error messages. Here, we attempt to
13314 // emit better ones.
13315 for (const Expr *Arg : Args) {
13316 if (!Arg->getType()->isFunctionType())
13317 continue;
13318 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13319 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13320 if (FD &&
13321 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13322 Arg->getExprLoc()))
13323 return ExprError();
13324 }
13325 }
13326
13327 CandidateSet->NoteCandidates(
13328 PartialDiagnosticAt(
13329 Fn->getBeginLoc(),
13330 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13331 << ULE->getName() << Fn->getSourceRange()),
13332 SemaRef, OCD_AllCandidates, Args);
13333 break;
13334 }
13335
13336 case OR_Ambiguous:
13337 CandidateSet->NoteCandidates(
13338 PartialDiagnosticAt(Fn->getBeginLoc(),
13339 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13340 << ULE->getName() << Fn->getSourceRange()),
13341 SemaRef, OCD_AmbiguousCandidates, Args);
13342 break;
13343
13344 case OR_Deleted: {
13345 CandidateSet->NoteCandidates(
13346 PartialDiagnosticAt(Fn->getBeginLoc(),
13347 SemaRef.PDiag(diag::err_ovl_deleted_call)
13348 << ULE->getName() << Fn->getSourceRange()),
13349 SemaRef, OCD_AllCandidates, Args);
13350
13351 // We emitted an error for the unavailable/deleted function call but keep
13352 // the call in the AST.
13353 FunctionDecl *FDecl = (*Best)->Function;
13354 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13355 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13356 ExecConfig, /*IsExecConfig=*/false,
13357 (*Best)->IsADLCandidate);
13358 }
13359 }
13360
13361 // Overload resolution failed, try to recover.
13362 SmallVector<Expr *, 8> SubExprs = {Fn};
13363 SubExprs.append(Args.begin(), Args.end());
13364 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13365 chooseRecoveryType(*CandidateSet, Best));
13366}
13367
13368static void markUnaddressableCandidatesUnviable(Sema &S,
13369 OverloadCandidateSet &CS) {
13370 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13371 if (I->Viable &&
13372 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13373 I->Viable = false;
13374 I->FailureKind = ovl_fail_addr_not_available;
13375 }
13376 }
13377}
13378
13379/// BuildOverloadedCallExpr - Given the call expression that calls Fn
13380/// (which eventually refers to the declaration Func) and the call
13381/// arguments Args/NumArgs, attempt to resolve the function call down
13382/// to a specific function. If overload resolution succeeds, returns
13383/// the call expression produced by overload resolution.
13384/// Otherwise, emits diagnostics and returns ExprError.
13385ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13386 UnresolvedLookupExpr *ULE,
13387 SourceLocation LParenLoc,
13388 MultiExprArg Args,
13389 SourceLocation RParenLoc,
13390 Expr *ExecConfig,
13391 bool AllowTypoCorrection,
13392 bool CalleesAddressIsTaken) {
13393 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13394 OverloadCandidateSet::CSK_Normal);
13395 ExprResult result;
13396
13397 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13398 &result))
13399 return result;
13400
13401 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13402 // functions that aren't addressible are considered unviable.
13403 if (CalleesAddressIsTaken)
13404 markUnaddressableCandidatesUnviable(*this, CandidateSet);
13405
13406 OverloadCandidateSet::iterator Best;
13407 OverloadingResult OverloadResult =
13408 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13409
13410 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13411 ExecConfig, &CandidateSet, &Best,
13412 OverloadResult, AllowTypoCorrection);
13413}
13414
13415static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13416 return Functions.size() > 1 ||
13417 (Functions.size() == 1 &&
13418 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13419}
13420
13421ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13422 NestedNameSpecifierLoc NNSLoc,
13423 DeclarationNameInfo DNI,
13424 const UnresolvedSetImpl &Fns,
13425 bool PerformADL) {
13426 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13427 PerformADL, IsOverloaded(Fns),
13428 Fns.begin(), Fns.end());
13429}
13430
13431/// Create a unary operation that may resolve to an overloaded
13432/// operator.
13433///
13434/// \param OpLoc The location of the operator itself (e.g., '*').
13435///
13436/// \param Opc The UnaryOperatorKind that describes this operator.
13437///
13438/// \param Fns The set of non-member functions that will be
13439/// considered by overload resolution. The caller needs to build this
13440/// set based on the context using, e.g.,
13441/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13442/// set should not contain any member functions; those will be added
13443/// by CreateOverloadedUnaryOp().
13444///
13445/// \param Input The input argument.
13446ExprResult
13447Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13448 const UnresolvedSetImpl &Fns,
13449 Expr *Input, bool PerformADL) {
13450 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13451 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")(static_cast <bool> (Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? void (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "clang/lib/Sema/SemaOverload.cpp", 13451, __extension__ __PRETTY_FUNCTION__
))
;
13452 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13453 // TODO: provide better source location info.
13454 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13455
13456 if (checkPlaceholderForOverload(*this, Input))
13457 return ExprError();
13458
13459 Expr *Args[2] = { Input, nullptr };
13460 unsigned NumArgs = 1;
13461
13462 // For post-increment and post-decrement, add the implicit '0' as
13463 // the second argument, so that we know this is a post-increment or
13464 // post-decrement.
13465 if (Opc == UO_PostInc || Opc == UO_PostDec) {
13466 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13467 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13468 SourceLocation());
13469 NumArgs = 2;
13470 }
13471
13472 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13473
13474 if (Input->isTypeDependent()) {
13475 if (Fns.empty())
13476 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13477 VK_PRValue, OK_Ordinary, OpLoc, false,
13478 CurFPFeatureOverrides());
13479
13480 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13481 ExprResult Fn = CreateUnresolvedLookupExpr(
13482 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13483 if (Fn.isInvalid())
13484 return ExprError();
13485 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13486 Context.DependentTy, VK_PRValue, OpLoc,
13487 CurFPFeatureOverrides());
13488 }
13489
13490 // Build an empty overload set.
13491 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13492
13493 // Add the candidates from the given function set.
13494 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13495
13496 // Add operator candidates that are member functions.
13497 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13498
13499 // Add candidates from ADL.
13500 if (PerformADL) {
13501 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13502 /*ExplicitTemplateArgs*/nullptr,
13503 CandidateSet);
13504 }
13505
13506 // Add builtin operator candidates.
13507 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13508
13509 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13510
13511 // Perform overload resolution.
13512 OverloadCandidateSet::iterator Best;
13513 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13514 case OR_Success: {
13515 // We found a built-in operator or an overloaded operator.
13516 FunctionDecl *FnDecl = Best->Function;
13517
13518 if (FnDecl) {
13519 Expr *Base = nullptr;
13520 // We matched an overloaded operator. Build a call to that
13521 // operator.
13522
13523 // Convert the arguments.
13524 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13525 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13526
13527 ExprResult InputRes =
13528 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13529 Best->FoundDecl, Method);
13530 if (InputRes.isInvalid())
13531 return ExprError();
13532 Base = Input = InputRes.get();
13533 } else {
13534 // Convert the arguments.
13535 ExprResult InputInit
13536 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13537 Context,
13538 FnDecl->getParamDecl(0)),
13539 SourceLocation(),
13540 Input);
13541 if (InputInit.isInvalid())
13542 return ExprError();
13543 Input = InputInit.get();
13544 }
13545
13546 // Build the actual expression node.
13547 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13548 Base, HadMultipleCandidates,
13549 OpLoc);
13550 if (FnExpr.isInvalid())
13551 return ExprError();
13552
13553 // Determine the result type.
13554 QualType ResultTy = FnDecl->getReturnType();
13555 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13556 ResultTy = ResultTy.getNonLValueExprType(Context);
13557
13558 Args[0] = Input;
13559 CallExpr *TheCall = CXXOperatorCallExpr::Create(
13560 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13561 CurFPFeatureOverrides(), Best->IsADLCandidate);
13562
13563 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13564 return ExprError();
13565
13566 if (CheckFunctionCall(FnDecl, TheCall,
13567 FnDecl->getType()->castAs<FunctionProtoType>()))
13568 return ExprError();
13569 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13570 } else {
13571 // We matched a built-in operator. Convert the arguments, then
13572 // break out so that we will build the appropriate built-in
13573 // operator node.
13574 ExprResult InputRes = PerformImplicitConversion(
13575 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13576 CCK_ForBuiltinOverloadedOp);
13577 if (InputRes.isInvalid())
13578 return ExprError();
13579 Input = InputRes.get();
13580 break;
13581 }
13582 }
13583
13584 case OR_No_Viable_Function:
13585 // This is an erroneous use of an operator which can be overloaded by
13586 // a non-member function. Check for non-member operators which were
13587 // defined too late to be candidates.
13588 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13589 // FIXME: Recover by calling the found function.
13590 return ExprError();
13591
13592 // No viable function; fall through to handling this as a
13593 // built-in operator, which will produce an error message for us.
13594 break;
13595
13596 case OR_Ambiguous:
13597 CandidateSet.NoteCandidates(
13598 PartialDiagnosticAt(OpLoc,
13599 PDiag(diag::err_ovl_ambiguous_oper_unary)
13600 << UnaryOperator::getOpcodeStr(Opc)
13601 << Input->getType() << Input->getSourceRange()),
13602 *this, OCD_AmbiguousCandidates, ArgsArray,
13603 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13604 return ExprError();
13605
13606 case OR_Deleted:
13607 CandidateSet.NoteCandidates(
13608 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13609 << UnaryOperator::getOpcodeStr(Opc)
13610 << Input->getSourceRange()),
13611 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13612 OpLoc);
13613 return ExprError();
13614 }
13615
13616 // Either we found no viable overloaded operator or we matched a
13617 // built-in operator. In either case, fall through to trying to
13618 // build a built-in operation.
13619 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13620}
13621
13622/// Perform lookup for an overloaded binary operator.
13623void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13624 OverloadedOperatorKind Op,
13625 const UnresolvedSetImpl &Fns,
13626 ArrayRef<Expr *> Args, bool PerformADL) {
13627 SourceLocation OpLoc = CandidateSet.getLocation();
13628
13629 OverloadedOperatorKind ExtraOp =
13630 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13631 ? getRewrittenOverloadedOperator(Op)
13632 : OO_None;
13633
13634 // Add the candidates from the given function set. This also adds the
13635 // rewritten candidates using these functions if necessary.
13636 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13637
13638 // Add operator candidates that are member functions.
13639 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13640 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13641 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13642 OverloadCandidateParamOrder::Reversed);
13643
13644 // In C++20, also add any rewritten member candidates.
13645 if (ExtraOp) {
13646 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13647 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13648 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13649 CandidateSet,
13650 OverloadCandidateParamOrder::Reversed);
13651 }
13652
13653 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13654 // performed for an assignment operator (nor for operator[] nor operator->,
13655 // which don't get here).
13656 if (Op != OO_Equal && PerformADL) {
13657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13658 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13659 /*ExplicitTemplateArgs*/ nullptr,
13660 CandidateSet);
13661 if (ExtraOp) {
13662 DeclarationName ExtraOpName =
13663 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13664 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13665 /*ExplicitTemplateArgs*/ nullptr,
13666 CandidateSet);
13667 }
13668 }
13669
13670 // Add builtin operator candidates.
13671 //
13672 // FIXME: We don't add any rewritten candidates here. This is strictly
13673 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13674 // resulting in our selecting a rewritten builtin candidate. For example:
13675 //
13676 // enum class E { e };
13677 // bool operator!=(E, E) requires false;
13678 // bool k = E::e != E::e;
13679 //
13680 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13681 // it seems unreasonable to consider rewritten builtin candidates. A core
13682 // issue has been filed proposing to removed this requirement.
13683 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13684}
13685
13686/// Create a binary operation that may resolve to an overloaded
13687/// operator.
13688///
13689/// \param OpLoc The location of the operator itself (e.g., '+').
13690///
13691/// \param Opc The BinaryOperatorKind that describes this operator.
13692///
13693/// \param Fns The set of non-member functions that will be
13694/// considered by overload resolution. The caller needs to build this
13695/// set based on the context using, e.g.,
13696/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13697/// set should not contain any member functions; those will be added
13698/// by CreateOverloadedBinOp().
13699///
13700/// \param LHS Left-hand argument.
13701/// \param RHS Right-hand argument.
13702/// \param PerformADL Whether to consider operator candidates found by ADL.
13703/// \param AllowRewrittenCandidates Whether to consider candidates found by
13704/// C++20 operator rewrites.
13705/// \param DefaultedFn If we are synthesizing a defaulted operator function,
13706/// the function in question. Such a function is never a candidate in
13707/// our overload resolution. This also enables synthesizing a three-way
13708/// comparison from < and == as described in C++20 [class.spaceship]p1.
13709ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13710 BinaryOperatorKind Opc,
13711 const UnresolvedSetImpl &Fns, Expr *LHS,
13712 Expr *RHS, bool PerformADL,
13713 bool AllowRewrittenCandidates,
13714 FunctionDecl *DefaultedFn) {
13715 Expr *Args[2] = { LHS, RHS };
13716 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13717
13718 if (!getLangOpts().CPlusPlus20)
13719 AllowRewrittenCandidates = false;
13720
13721 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13722
13723 // If either side is type-dependent, create an appropriate dependent
13724 // expression.
13725 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13726 if (Fns.empty()) {
13727 // If there are no functions to store, just build a dependent
13728 // BinaryOperator or CompoundAssignment.
13729 if (BinaryOperator::isCompoundAssignmentOp(Opc))
13730 return CompoundAssignOperator::Create(
13731 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13732 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13733 Context.DependentTy);
13734 return BinaryOperator::Create(
13735 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13736 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13737 }
13738
13739 // FIXME: save results of ADL from here?
13740 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13741 // TODO: provide better source location info in DNLoc component.
13742 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13743 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13744 ExprResult Fn = CreateUnresolvedLookupExpr(
13745 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13746 if (Fn.isInvalid())
13747 return ExprError();
13748 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13749 Context.DependentTy, VK_PRValue, OpLoc,
13750 CurFPFeatureOverrides());
13751 }
13752
13753 // Always do placeholder-like conversions on the RHS.
13754 if (checkPlaceholderForOverload(*this, Args[1]))
13755 return ExprError();
13756
13757 // Do placeholder-like conversion on the LHS; note that we should
13758 // not get here with a PseudoObject LHS.
13759 assert(Args[0]->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (Args[0]->getObjectKind() != OK_ObjCProperty
) ? void (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "clang/lib/Sema/SemaOverload.cpp", 13759, __extension__ __PRETTY_FUNCTION__
))
;
13760 if (checkPlaceholderForOverload(*this, Args[0]))
13761 return ExprError();
13762
13763 // If this is the assignment operator, we only perform overload resolution
13764 // if the left-hand side is a class or enumeration type. This is actually
13765 // a hack. The standard requires that we do overload resolution between the
13766 // various built-in candidates, but as DR507 points out, this can lead to
13767 // problems. So we do it this way, which pretty much follows what GCC does.
13768 // Note that we go the traditional code path for compound assignment forms.
13769 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13770 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13771
13772 // If this is the .* operator, which is not overloadable, just
13773 // create a built-in binary operator.
13774 if (Opc == BO_PtrMemD)
13775 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13776
13777 // Build the overload set.
13778 OverloadCandidateSet CandidateSet(
13779 OpLoc, OverloadCandidateSet::CSK_Operator,
13780 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13781 if (DefaultedFn)
13782 CandidateSet.exclude(DefaultedFn);
13783 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13784
13785 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13786
13787 // Perform overload resolution.
13788 OverloadCandidateSet::iterator Best;
13789 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13790 case OR_Success: {
13791 // We found a built-in operator or an overloaded operator.
13792 FunctionDecl *FnDecl = Best->Function;
13793
13794 bool IsReversed = Best->isReversed();
13795 if (IsReversed)
13796 std::swap(Args[0], Args[1]);
13797
13798 if (FnDecl) {
13799 Expr *Base = nullptr;
13800 // We matched an overloaded operator. Build a call to that
13801 // operator.
13802
13803 OverloadedOperatorKind ChosenOp =
13804 FnDecl->getDeclName().getCXXOverloadedOperator();
13805
13806 // C++2a [over.match.oper]p9:
13807 // If a rewritten operator== candidate is selected by overload
13808 // resolution for an operator@, its return type shall be cv bool
13809 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13810 !FnDecl->getReturnType()->isBooleanType()) {
13811 bool IsExtension =
13812 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13813 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13814 : diag::err_ovl_rewrite_equalequal_not_bool)
13815 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13816 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13817 Diag(FnDecl->getLocation(), diag::note_declared_at);
13818 if (!IsExtension)
13819 return ExprError();
13820 }
13821
13822 if (AllowRewrittenCandidates && !IsReversed &&
13823 CandidateSet.getRewriteInfo().isReversible()) {
13824 // We could have reversed this operator, but didn't. Check if some
13825 // reversed form was a viable candidate, and if so, if it had a
13826 // better conversion for either parameter. If so, this call is
13827 // formally ambiguous, and allowing it is an extension.
13828 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13829 for (OverloadCandidate &Cand : CandidateSet) {
13830 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13831 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13832 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13833 if (CompareImplicitConversionSequences(
13834 *this, OpLoc, Cand.Conversions[ArgIdx],
13835 Best->Conversions[ArgIdx]) ==
13836 ImplicitConversionSequence::Better) {
13837 AmbiguousWith.push_back(Cand.Function);
13838 break;
13839 }
13840 }
13841 }
13842 }
13843
13844 if (!AmbiguousWith.empty()) {
13845 bool AmbiguousWithSelf =
13846 AmbiguousWith.size() == 1 &&
13847 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13848 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13849 << BinaryOperator::getOpcodeStr(Opc)
13850 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13851 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13852 if (AmbiguousWithSelf) {
13853 Diag(FnDecl->getLocation(),
13854 diag::note_ovl_ambiguous_oper_binary_reversed_self);
13855 } else {
13856 Diag(FnDecl->getLocation(),
13857 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13858 for (auto *F : AmbiguousWith)
13859 Diag(F->getLocation(),
13860 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13861 }
13862 }
13863 }
13864
13865 // Convert the arguments.
13866 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13867 // Best->Access is only meaningful for class members.
13868 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13869
13870 ExprResult Arg1 =
13871 PerformCopyInitialization(
13872 InitializedEntity::InitializeParameter(Context,
13873 FnDecl->getParamDecl(0)),
13874 SourceLocation(), Args[1]);
13875 if (Arg1.isInvalid())
13876 return ExprError();
13877
13878 ExprResult Arg0 =
13879 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13880 Best->FoundDecl, Method);
13881 if (Arg0.isInvalid())
13882 return ExprError();
13883 Base = Args[0] = Arg0.getAs<Expr>();
13884 Args[1] = RHS = Arg1.getAs<Expr>();
Although the value stored to 'RHS' is used in the enclosing expression, the value is never actually read from 'RHS'
13885 } else {
13886 // Convert the arguments.
13887 ExprResult Arg0 = PerformCopyInitialization(
13888 InitializedEntity::InitializeParameter(Context,
13889 FnDecl->getParamDecl(0)),
13890 SourceLocation(), Args[0]);
13891 if (Arg0.isInvalid())
13892 return ExprError();
13893
13894 ExprResult Arg1 =
13895 PerformCopyInitialization(
13896 InitializedEntity::InitializeParameter(Context,
13897 FnDecl->getParamDecl(1)),
13898 SourceLocation(), Args[1]);
13899 if (Arg1.isInvalid())
13900 return ExprError();
13901 Args[0] = LHS = Arg0.getAs<Expr>();
13902 Args[1] = RHS = Arg1.getAs<Expr>();
13903 }
13904
13905 // Build the actual expression node.
13906 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13907 Best->FoundDecl, Base,
13908 HadMultipleCandidates, OpLoc);
13909 if (FnExpr.isInvalid())
13910 return ExprError();
13911
13912 // Determine the result type.
13913 QualType ResultTy = FnDecl->getReturnType();
13914 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13915 ResultTy = ResultTy.getNonLValueExprType(Context);
13916
13917 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13918 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13919 CurFPFeatureOverrides(), Best->IsADLCandidate);
13920
13921 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13922 FnDecl))
13923 return ExprError();
13924
13925 ArrayRef<const Expr *> ArgsArray(Args, 2);
13926 const Expr *ImplicitThis = nullptr;
13927 // Cut off the implicit 'this'.
13928 if (isa<CXXMethodDecl>(FnDecl)) {
13929 ImplicitThis = ArgsArray[0];
13930 ArgsArray = ArgsArray.slice(1);
13931 }
13932
13933 // Check for a self move.
13934 if (Op == OO_Equal)
13935 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13936
13937 if (ImplicitThis) {
13938 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13939 QualType ThisTypeFromDecl = Context.getPointerType(
13940 cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13941
13942 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13943 ThisTypeFromDecl);
13944 }
13945
13946 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13947 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13948 VariadicDoesNotApply);
13949
13950 ExprResult R = MaybeBindToTemporary(TheCall);
13951 if (R.isInvalid())
13952 return ExprError();
13953
13954 R = CheckForImmediateInvocation(R, FnDecl);
13955 if (R.isInvalid())
13956 return ExprError();
13957
13958 // For a rewritten candidate, we've already reversed the arguments
13959 // if needed. Perform the rest of the rewrite now.
13960 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13961 (Op == OO_Spaceship && IsReversed)) {
13962 if (Op == OO_ExclaimEqual) {
13963 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_EqualEqual &&
"unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\""
, "clang/lib/Sema/SemaOverload.cpp", 13963, __extension__ __PRETTY_FUNCTION__
))
;
13964 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13965 } else {
13966 assert(ChosenOp == OO_Spaceship && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_Spaceship &&
"unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\""
, "clang/lib/Sema/SemaOverload.cpp", 13966, __extension__ __PRETTY_FUNCTION__
))
;
13967 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13968 Expr *ZeroLiteral =
13969 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13970
13971 Sema::CodeSynthesisContext Ctx;
13972 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13973 Ctx.Entity = FnDecl;
13974 pushCodeSynthesisContext(Ctx);
13975
13976 R = CreateOverloadedBinOp(
13977 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13978 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
13979 /*AllowRewrittenCandidates=*/false);
13980
13981 popCodeSynthesisContext();
13982 }
13983 if (R.isInvalid())
13984 return ExprError();
13985 } else {
13986 assert(ChosenOp == Op && "unexpected operator name")(static_cast <bool> (ChosenOp == Op && "unexpected operator name"
) ? void (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\""
, "clang/lib/Sema/SemaOverload.cpp", 13986, __extension__ __PRETTY_FUNCTION__
))
;
13987 }
13988
13989 // Make a note in the AST if we did any rewriting.
13990 if (Best->RewriteKind != CRK_None)
13991 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13992
13993 return R;
13994 } else {
13995 // We matched a built-in operator. Convert the arguments, then
13996 // break out so that we will build the appropriate built-in
13997 // operator node.
13998 ExprResult ArgsRes0 = PerformImplicitConversion(
13999 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14000 AA_Passing, CCK_ForBuiltinOverloadedOp);
14001 if (ArgsRes0.isInvalid())
14002 return ExprError();
14003 Args[0] = ArgsRes0.get();
14004
14005 ExprResult ArgsRes1 = PerformImplicitConversion(
14006 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14007 AA_Passing, CCK_ForBuiltinOverloadedOp);
14008 if (ArgsRes1.isInvalid())
14009 return ExprError();
14010 Args[1] = ArgsRes1.get();
14011 break;
14012 }
14013 }
14014
14015 case OR_No_Viable_Function: {
14016 // C++ [over.match.oper]p9:
14017 // If the operator is the operator , [...] and there are no
14018 // viable functions, then the operator is assumed to be the
14019 // built-in operator and interpreted according to clause 5.
14020 if (Opc == BO_Comma)
14021 break;
14022
14023 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14024 // compare result using '==' and '<'.
14025 if (DefaultedFn && Opc == BO_Cmp) {
14026 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14027 Args[1], DefaultedFn);
14028 if (E.isInvalid() || E.isUsable())
14029 return E;
14030 }
14031
14032 // For class as left operand for assignment or compound assignment
14033 // operator do not fall through to handling in built-in, but report that
14034 // no overloaded assignment operator found
14035 ExprResult Result = ExprError();
14036 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14037 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14038 Args, OpLoc);
14039 DeferDiagsRAII DDR(*this,
14040 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14041 if (Args[0]->getType()->isRecordType() &&
14042 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14043 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14044 << BinaryOperator::getOpcodeStr(Opc)
14045 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14046 if (Args[0]->getType()->isIncompleteType()) {
14047 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14048 << Args[0]->getType()
14049 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14050 }
14051 } else {
14052 // This is an erroneous use of an operator which can be overloaded by
14053 // a non-member function. Check for non-member operators which were
14054 // defined too late to be candidates.
14055 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14056 // FIXME: Recover by calling the found function.
14057 return ExprError();
14058
14059 // No viable function; try to create a built-in operation, which will
14060 // produce an error. Then, show the non-viable candidates.
14061 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14062 }
14063 assert(Result.isInvalid() &&(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "clang/lib/Sema/SemaOverload.cpp", 14064, __extension__ __PRETTY_FUNCTION__
))
14064 "C++ binary operator overloading is missing candidates!")(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "clang/lib/Sema/SemaOverload.cpp", 14064, __extension__ __PRETTY_FUNCTION__
))
;
14065 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14066 return Result;
14067 }
14068
14069 case OR_Ambiguous:
14070 CandidateSet.NoteCandidates(
14071 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14072 << BinaryOperator::getOpcodeStr(Opc)
14073 << Args[0]->getType()
14074 << Args[1]->getType()
14075 << Args[0]->getSourceRange()
14076 << Args[1]->getSourceRange()),
14077 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14078 OpLoc);
14079 return ExprError();
14080
14081 case OR_Deleted:
14082 if (isImplicitlyDeleted(Best->Function)) {
14083 FunctionDecl *DeletedFD = Best->Function;
14084 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14085 if (DFK.isSpecialMember()) {
14086 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14087 << Args[0]->getType() << DFK.asSpecialMember();
14088 } else {
14089 assert(DFK.isComparison())(static_cast <bool> (DFK.isComparison()) ? void (0) : __assert_fail
("DFK.isComparison()", "clang/lib/Sema/SemaOverload.cpp", 14089
, __extension__ __PRETTY_FUNCTION__))
;
14090 Diag(OpLoc, diag::err_ovl_deleted_comparison)
14091 << Args[0]->getType() << DeletedFD;
14092 }
14093
14094 // The user probably meant to call this special member. Just
14095 // explain why it's deleted.
14096 NoteDeletedFunction(DeletedFD);
14097 return ExprError();
14098 }
14099 CandidateSet.NoteCandidates(
14100 PartialDiagnosticAt(
14101 OpLoc, PDiag(diag::err_ovl_deleted_oper)
14102 << getOperatorSpelling(Best->Function->getDeclName()
14103 .getCXXOverloadedOperator())
14104 << Args[0]->getSourceRange()
14105 << Args[1]->getSourceRange()),
14106 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14107 OpLoc);
14108 return ExprError();
14109 }
14110
14111 // We matched a built-in operator; build it.
14112 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14113}
14114
14115ExprResult Sema::BuildSynthesizedThreeWayComparison(
14116 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14117 FunctionDecl *DefaultedFn) {
14118 const ComparisonCategoryInfo *Info =
14119 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14120 // If we're not producing a known comparison category type, we can't
14121 // synthesize a three-way comparison. Let the caller diagnose this.
14122 if (!Info)
14123 return ExprResult((Expr*)nullptr);
14124
14125 // If we ever want to perform this synthesis more generally, we will need to
14126 // apply the temporary materialization conversion to the operands.
14127 assert(LHS->isGLValue() && RHS->isGLValue() &&(static_cast <bool> (LHS->isGLValue() && RHS
->isGLValue() && "cannot use prvalue expressions more than once"
) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "clang/lib/Sema/SemaOverload.cpp", 14128, __extension__ __PRETTY_FUNCTION__
))
14128 "cannot use prvalue expressions more than once")(static_cast <bool> (LHS->isGLValue() && RHS
->isGLValue() && "cannot use prvalue expressions more than once"
) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "clang/lib/Sema/SemaOverload.cpp", 14128, __extension__ __PRETTY_FUNCTION__
))
;
14129 Expr *OrigLHS = LHS;
14130 Expr *OrigRHS = RHS;
14131
14132 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14133 // each of them multiple times below.
14134 LHS = new (Context)
14135 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14136 LHS->getObjectKind(), LHS);
14137 RHS = new (Context)
14138 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14139 RHS->getObjectKind(), RHS);
14140
14141 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14142 DefaultedFn);
14143 if (Eq.isInvalid())
14144 return ExprError();
14145
14146 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14147 true, DefaultedFn);
14148 if (Less.isInvalid())
14149 return ExprError();
14150
14151 ExprResult Greater;
14152 if (Info->isPartial()) {
14153 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14154 DefaultedFn);
14155 if (Greater.isInvalid())
14156 return ExprError();
14157 }
14158
14159 // Form the list of comparisons we're going to perform.
14160 struct Comparison {
14161 ExprResult Cmp;
14162 ComparisonCategoryResult Result;
14163 } Comparisons[4] =
14164 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14165 : ComparisonCategoryResult::Equivalent},
14166 {Less, ComparisonCategoryResult::Less},
14167 {Greater, ComparisonCategoryResult::Greater},
14168 {ExprResult(), ComparisonCategoryResult::Unordered},
14169 };
14170
14171 int I = Info->isPartial() ? 3 : 2;
14172
14173 // Combine the comparisons with suitable conditional expressions.
14174 ExprResult Result;
14175 for (; I >= 0; --I) {
14176 // Build a reference to the comparison category constant.
14177 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14178 // FIXME: Missing a constant for a comparison category. Diagnose this?
14179 if (!VI)
14180 return ExprResult((Expr*)nullptr);
14181 ExprResult ThisResult =
14182 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14183 if (ThisResult.isInvalid())
14184 return ExprError();
14185
14186 // Build a conditional unless this is the final case.
14187 if (Result.get()) {
14188 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14189 ThisResult.get(), Result.get());
14190 if (Result.isInvalid())
14191 return ExprError();
14192 } else {
14193 Result = ThisResult;
14194 }
14195 }
14196
14197 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14198 // bind the OpaqueValueExprs before they're (repeatedly) used.
14199 Expr *SyntacticForm = BinaryOperator::Create(
14200 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14201 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14202 CurFPFeatureOverrides());
14203 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14204 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14205}
14206
14207static bool PrepareArgumentsForCallToObjectOfClassType(
14208 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14209 MultiExprArg Args, SourceLocation LParenLoc) {
14210
14211 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14212 unsigned NumParams = Proto->getNumParams();
14213 unsigned NumArgsSlots =
14214 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14215 // Build the full argument list for the method call (the implicit object
14216 // parameter is placed at the beginning of the list).
14217 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14218 bool IsError = false;
14219 // Initialize the implicit object parameter.
14220 // Check the argument types.
14221 for (unsigned i = 0; i != NumParams; i++) {
14222 Expr *Arg;
14223 if (i < Args.size()) {
14224 Arg = Args[i];
14225 ExprResult InputInit =
14226 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14227 S.Context, Method->getParamDecl(i)),
14228 SourceLocation(), Arg);
14229 IsError |= InputInit.isInvalid();
14230 Arg = InputInit.getAs<Expr>();
14231 } else {
14232 ExprResult DefArg =
14233 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14234 if (DefArg.isInvalid()) {
14235 IsError = true;
14236 break;
14237 }
14238 Arg = DefArg.getAs<Expr>();
14239 }
14240
14241 MethodArgs.push_back(Arg);
14242 }
14243 return IsError;
14244}
14245
14246ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14247 SourceLocation RLoc,
14248 Expr *Base,
14249 MultiExprArg ArgExpr) {
14250 SmallVector<Expr *, 2> Args;
14251 Args.push_back(Base);
14252 for (auto *e : ArgExpr) {
14253 Args.push_back(e);
14254 }
14255 DeclarationName OpName =
14256 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14257
14258 SourceRange Range = ArgExpr.empty()
14259 ? SourceRange{}
14260 : SourceRange(ArgExpr.front()->getBeginLoc(),
14261 ArgExpr.back()->getEndLoc());
14262
14263 // If either side is type-dependent, create an appropriate dependent
14264 // expression.
14265 if (Expr::hasAnyTypeDependentArguments(Args)) {
14266
14267 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14268 // CHECKME: no 'operator' keyword?
14269 DeclarationNameInfo OpNameInfo(OpName, LLoc);
14270 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14271 ExprResult Fn = CreateUnresolvedLookupExpr(
14272 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14273 if (Fn.isInvalid())
14274 return ExprError();
14275 // Can't add any actual overloads yet
14276
14277 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14278 Context.DependentTy, VK_PRValue, RLoc,
14279 CurFPFeatureOverrides());
14280 }
14281
14282 // Handle placeholders
14283 UnbridgedCastsSet UnbridgedCasts;
14284 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14285 return ExprError();
14286 }
14287 // Build an empty overload set.
14288 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14289
14290 // Subscript can only be overloaded as a member function.
14291
14292 // Add operator candidates that are member functions.
14293 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14294
14295 // Add builtin operator candidates.
14296 if (Args.size() == 2)
14297 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14298
14299 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14300
14301 // Perform overload resolution.
14302 OverloadCandidateSet::iterator Best;
14303 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14304 case OR_Success: {
14305 // We found a built-in operator or an overloaded operator.
14306 FunctionDecl *FnDecl = Best->Function;
14307
14308 if (FnDecl) {
14309 // We matched an overloaded operator. Build a call to that
14310 // operator.
14311
14312 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14313
14314 // Convert the arguments.
14315 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14316 SmallVector<Expr *, 2> MethodArgs;
14317 ExprResult Arg0 = PerformObjectArgumentInitialization(
14318 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14319 if (Arg0.isInvalid())
14320 return ExprError();
14321
14322 MethodArgs.push_back(Arg0.get());
14323 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14324 *this, MethodArgs, Method, ArgExpr, LLoc);
14325 if (IsError)
14326 return ExprError();
14327
14328 // Build the actual expression node.
14329 DeclarationNameInfo OpLocInfo(OpName, LLoc);
14330 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14331 ExprResult FnExpr = CreateFunctionRefExpr(
14332 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14333 OpLocInfo.getLoc(), OpLocInfo.getInfo());
14334 if (FnExpr.isInvalid())
14335 return ExprError();
14336
14337 // Determine the result type
14338 QualType ResultTy = FnDecl->getReturnType();
14339 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14340 ResultTy = ResultTy.getNonLValueExprType(Context);
14341
14342 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14343 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
14344 CurFPFeatureOverrides());
14345 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14346 return ExprError();
14347
14348 if (CheckFunctionCall(Method, TheCall,
14349 Method->getType()->castAs<FunctionProtoType>()))
14350 return ExprError();
14351
14352 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14353 FnDecl);
14354 } else {
14355 // We matched a built-in operator. Convert the arguments, then
14356 // break out so that we will build the appropriate built-in
14357 // operator node.
14358 ExprResult ArgsRes0 = PerformImplicitConversion(
14359 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14360 AA_Passing, CCK_ForBuiltinOverloadedOp);
14361 if (ArgsRes0.isInvalid())
14362 return ExprError();
14363 Args[0] = ArgsRes0.get();
14364
14365 ExprResult ArgsRes1 = PerformImplicitConversion(
14366 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14367 AA_Passing, CCK_ForBuiltinOverloadedOp);
14368 if (ArgsRes1.isInvalid())
14369 return ExprError();
14370 Args[1] = ArgsRes1.get();
14371
14372 break;
14373 }
14374 }
14375
14376 case OR_No_Viable_Function: {
14377 PartialDiagnostic PD =
14378 CandidateSet.empty()
14379 ? (PDiag(diag::err_ovl_no_oper)
14380 << Args[0]->getType() << /*subscript*/ 0
14381 << Args[0]->getSourceRange() << Range)
14382 : (PDiag(diag::err_ovl_no_viable_subscript)
14383 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14384 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14385 OCD_AllCandidates, ArgExpr, "[]", LLoc);
14386 return ExprError();
14387 }
14388
14389 case OR_Ambiguous:
14390 if (Args.size() == 2) {
14391 CandidateSet.NoteCandidates(
14392 PartialDiagnosticAt(
14393 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14394 << "[]" << Args[0]->getType() << Args[1]->getType()
14395 << Args[0]->getSourceRange() << Range),
14396 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14397 } else {
14398 CandidateSet.NoteCandidates(
14399 PartialDiagnosticAt(LLoc,
14400 PDiag(diag::err_ovl_ambiguous_subscript_call)
14401 << Args[0]->getType()
14402 << Args[0]->getSourceRange() << Range),
14403 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14404 }
14405 return ExprError();
14406
14407 case OR_Deleted:
14408 CandidateSet.NoteCandidates(
14409 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14410 << "[]" << Args[0]->getSourceRange()
14411 << Range),
14412 *this, OCD_AllCandidates, Args, "[]", LLoc);
14413 return ExprError();
14414 }
14415
14416 // We matched a built-in operator; build it.
14417 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14418}
14419
14420/// BuildCallToMemberFunction - Build a call to a member
14421/// function. MemExpr is the expression that refers to the member
14422/// function (and includes the object parameter), Args/NumArgs are the
14423/// arguments to the function call (not including the object
14424/// parameter). The caller needs to validate that the member
14425/// expression refers to a non-static member function or an overloaded
14426/// member function.
14427ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14428 SourceLocation LParenLoc,
14429 MultiExprArg Args,
14430 SourceLocation RParenLoc,
14431 Expr *ExecConfig, bool IsExecConfig,
14432 bool AllowRecovery) {
14433 assert(MemExprE->getType() == Context.BoundMemberTy ||(static_cast <bool> (MemExprE->getType() == Context.
BoundMemberTy || MemExprE->getType() == Context.OverloadTy
) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 14434, __extension__ __PRETTY_FUNCTION__
))
14434 MemExprE->getType() == Context.OverloadTy)(static_cast <bool> (MemExprE->getType() == Context.
BoundMemberTy || MemExprE->getType() == Context.OverloadTy
) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 14434, __extension__ __PRETTY_FUNCTION__
))
;
14435
14436 // Dig out the member expression. This holds both the object
14437 // argument and the member function we're referring to.
14438 Expr *NakedMemExpr = MemExprE->IgnoreParens();
14439
14440 // Determine whether this is a call to a pointer-to-member function.
14441 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14442 assert(op->getType() == Context.BoundMemberTy)(static_cast <bool> (op->getType() == Context.BoundMemberTy
) ? void (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "clang/lib/Sema/SemaOverload.cpp", 14442, __extension__ __PRETTY_FUNCTION__
))
;
14443 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)(static_cast <bool> (op->getOpcode() == BO_PtrMemD ||
op->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail
("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "clang/lib/Sema/SemaOverload.cpp", 14443, __extension__ __PRETTY_FUNCTION__
))
;
14444
14445 QualType fnType =
14446 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14447
14448 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14449 QualType resultType = proto->getCallResultType(Context);
14450 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14451
14452 // Check that the object type isn't more qualified than the
14453 // member function we're calling.
14454 Qualifiers funcQuals = proto->getMethodQuals();
14455
14456 QualType objectType = op->getLHS()->getType();
14457 if (op->getOpcode() == BO_PtrMemI)
14458 objectType = objectType->castAs<PointerType>()->getPointeeType();
14459 Qualifiers objectQuals = objectType.getQualifiers();
14460
14461 Qualifiers difference = objectQuals - funcQuals;
14462 difference.removeObjCGCAttr();
14463 difference.removeAddressSpace();
14464 if (difference) {
14465 std::string qualsString = difference.getAsString();
14466 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14467 << fnType.getUnqualifiedType()
14468 << qualsString
14469 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14470 }
14471
14472 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14473 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14474 CurFPFeatureOverrides(), proto->getNumParams());
14475
14476 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14477 call, nullptr))
14478 return ExprError();
14479
14480 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14481 return ExprError();
14482
14483 if (CheckOtherCall(call, proto))
14484 return ExprError();
14485
14486 return MaybeBindToTemporary(call);
14487 }
14488
14489 // We only try to build a recovery expr at this level if we can preserve
14490 // the return type, otherwise we return ExprError() and let the caller
14491 // recover.
14492 auto BuildRecoveryExpr = [&](QualType Type) {
14493 if (!AllowRecovery)
14494 return ExprError();
14495 std::vector<Expr *> SubExprs = {MemExprE};
14496 llvm::append_range(SubExprs, Args);
14497 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14498 Type);
14499 };
14500 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14501 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14502 RParenLoc, CurFPFeatureOverrides());
14503
14504 UnbridgedCastsSet UnbridgedCasts;
14505 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14506 return ExprError();
14507
14508 MemberExpr *MemExpr;
14509 CXXMethodDecl *Method = nullptr;
14510 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14511 NestedNameSpecifier *Qualifier = nullptr;
14512 if (isa<MemberExpr>(NakedMemExpr)) {
14513 MemExpr = cast<MemberExpr>(NakedMemExpr);
14514 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14515 FoundDecl = MemExpr->getFoundDecl();
14516 Qualifier = MemExpr->getQualifier();
14517 UnbridgedCasts.restore();
14518 } else {
14519 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14520 Qualifier = UnresExpr->getQualifier();
14521
14522 QualType ObjectType = UnresExpr->getBaseType();
14523 Expr::Classification ObjectClassification
14524 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14525 : UnresExpr->getBase()->Classify(Context);
14526
14527 // Add overload candidates
14528 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14529 OverloadCandidateSet::CSK_Normal);
14530
14531 // FIXME: avoid copy.
14532 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14533 if (UnresExpr->hasExplicitTemplateArgs()) {
14534 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14535 TemplateArgs = &TemplateArgsBuffer;
14536 }
14537
14538 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14539 E = UnresExpr->decls_end(); I != E; ++I) {
14540
14541 NamedDecl *Func = *I;
14542 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14543 if (isa<UsingShadowDecl>(Func))
14544 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14545
14546
14547 // Microsoft supports direct constructor calls.
14548 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14549 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14550 CandidateSet,
14551 /*SuppressUserConversions*/ false);
14552 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14553 // If explicit template arguments were provided, we can't call a
14554 // non-template member function.
14555 if (TemplateArgs)
14556 continue;
14557
14558 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14559 ObjectClassification, Args, CandidateSet,
14560 /*SuppressUserConversions=*/false);
14561 } else {
14562 AddMethodTemplateCandidate(
14563 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14564 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14565 /*SuppressUserConversions=*/false);
14566 }
14567 }
14568
14569 DeclarationName DeclName = UnresExpr->getMemberName();
14570
14571 UnbridgedCasts.restore();
14572
14573 OverloadCandidateSet::iterator Best;
14574 bool Succeeded = false;
14575 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14576 Best)) {
14577 case OR_Success:
14578 Method = cast<CXXMethodDecl>(Best->Function);
14579 FoundDecl = Best->FoundDecl;
14580 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14581 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14582 break;
14583 // If FoundDecl is different from Method (such as if one is a template
14584 // and the other a specialization), make sure DiagnoseUseOfDecl is
14585 // called on both.
14586 // FIXME: This would be more comprehensively addressed by modifying
14587 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14588 // being used.
14589 if (Method != FoundDecl.getDecl() &&
14590 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14591 break;
14592 Succeeded = true;
14593 break;
14594
14595 case OR_No_Viable_Function:
14596 CandidateSet.NoteCandidates(
14597 PartialDiagnosticAt(
14598 UnresExpr->getMemberLoc(),
14599 PDiag(diag::err_ovl_no_viable_member_function_in_call)
14600 << DeclName << MemExprE->getSourceRange()),
14601 *this, OCD_AllCandidates, Args);
14602 break;
14603 case OR_Ambiguous:
14604 CandidateSet.NoteCandidates(
14605 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14606 PDiag(diag::err_ovl_ambiguous_member_call)
14607 << DeclName << MemExprE->getSourceRange()),
14608 *this, OCD_AmbiguousCandidates, Args);
14609 break;
14610 case OR_Deleted:
14611 CandidateSet.NoteCandidates(
14612 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14613 PDiag(diag::err_ovl_deleted_member_call)
14614 << DeclName << MemExprE->getSourceRange()),
14615 *this, OCD_AllCandidates, Args);
14616 break;
14617 }
14618 // Overload resolution fails, try to recover.
14619 if (!Succeeded)
14620 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14621
14622 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14623
14624 // If overload resolution picked a static member, build a
14625 // non-member call based on that function.
14626 if (Method->isStatic()) {
14627 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14628 ExecConfig, IsExecConfig);
14629 }
14630
14631 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14632 }
14633
14634 QualType ResultType = Method->getReturnType();
14635 ExprValueKind VK = Expr::getValueKindForType(ResultType);
14636 ResultType = ResultType.getNonLValueExprType(Context);
14637
14638 assert(Method && "Member call to something that isn't a method?")(static_cast <bool> (Method && "Member call to something that isn't a method?"
) ? void (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "clang/lib/Sema/SemaOverload.cpp", 14638, __extension__ __PRETTY_FUNCTION__
))
;
14639 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14640 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14641 Context, MemExprE, Args, ResultType, VK, RParenLoc,
14642 CurFPFeatureOverrides(), Proto->getNumParams());
14643
14644 // Check for a valid return type.
14645 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14646 TheCall, Method))
14647 return BuildRecoveryExpr(ResultType);
14648
14649 // Convert the object argument (for a non-static member function call).
14650 // We only need to do this if there was actually an overload; otherwise
14651 // it was done at lookup.
14652 if (!Method->isStatic()) {
14653 ExprResult ObjectArg =
14654 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14655 FoundDecl, Method);
14656 if (ObjectArg.isInvalid())
14657 return ExprError();
14658 MemExpr->setBase(ObjectArg.get());
14659 }
14660
14661 // Convert the rest of the arguments
14662 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14663 RParenLoc))
14664 return BuildRecoveryExpr(ResultType);
14665
14666 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14667
14668 if (CheckFunctionCall(Method, TheCall, Proto))
14669 return ExprError();
14670
14671 // In the case the method to call was not selected by the overloading
14672 // resolution process, we still need to handle the enable_if attribute. Do
14673 // that here, so it will not hide previous -- and more relevant -- errors.
14674 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14675 if (const EnableIfAttr *Attr =
14676 CheckEnableIf(Method, LParenLoc, Args, true)) {
14677 Diag(MemE->getMemberLoc(),
14678 diag::err_ovl_no_viable_member_function_in_call)
14679 << Method << Method->getSourceRange();
14680 Diag(Method->getLocation(),
14681 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14682 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14683 return ExprError();
14684 }
14685 }
14686
14687 if ((isa<CXXConstructorDecl>(CurContext) ||
14688 isa<CXXDestructorDecl>(CurContext)) &&
14689 TheCall->getMethodDecl()->isPure()) {
14690 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14691
14692 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14693 MemExpr->performsVirtualDispatch(getLangOpts())) {
14694 Diag(MemExpr->getBeginLoc(),
14695 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14696 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14697 << MD->getParent();
14698
14699 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14700 if (getLangOpts().AppleKext)
14701 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14702 << MD->getParent() << MD->getDeclName();
14703 }
14704 }
14705
14706 if (CXXDestructorDecl *DD =
14707 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14708 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14709 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14710 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14711 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14712 MemExpr->getMemberLoc());
14713 }
14714
14715 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14716 TheCall->getMethodDecl());
14717}
14718
14719/// BuildCallToObjectOfClassType - Build a call to an object of class
14720/// type (C++ [over.call.object]), which can end up invoking an
14721/// overloaded function call operator (@c operator()) or performing a
14722/// user-defined conversion on the object argument.
14723ExprResult
14724Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14725 SourceLocation LParenLoc,
14726 MultiExprArg Args,
14727 SourceLocation RParenLoc) {
14728 if (checkPlaceholderForOverload(*this, Obj))
14729 return ExprError();
14730 ExprResult Object = Obj;
14731
14732 UnbridgedCastsSet UnbridgedCasts;
14733 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14734 return ExprError();
14735
14736 assert(Object.get()->getType()->isRecordType() &&(static_cast <bool> (Object.get()->getType()->isRecordType
() && "Requires object type argument") ? void (0) : __assert_fail
("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "clang/lib/Sema/SemaOverload.cpp", 14737, __extension__ __PRETTY_FUNCTION__
))
14737 "Requires object type argument")(static_cast <bool> (Object.get()->getType()->isRecordType
() && "Requires object type argument") ? void (0) : __assert_fail
("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "clang/lib/Sema/SemaOverload.cpp", 14737, __extension__ __PRETTY_FUNCTION__
))
;
14738
14739 // C++ [over.call.object]p1:
14740 // If the primary-expression E in the function call syntax
14741 // evaluates to a class object of type "cv T", then the set of
14742 // candidate functions includes at least the function call
14743 // operators of T. The function call operators of T are obtained by
14744 // ordinary lookup of the name operator() in the context of
14745 // (E).operator().
14746 OverloadCandidateSet CandidateSet(LParenLoc,
14747 OverloadCandidateSet::CSK_Operator);
14748 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14749
14750 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14751 diag::err_incomplete_object_call, Object.get()))
14752 return true;
14753
14754 const auto *Record = Object.get()->getType()->castAs<RecordType>();
14755 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14756 LookupQualifiedName(R, Record->getDecl());
14757 R.suppressDiagnostics();
14758
14759 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14760 Oper != OperEnd; ++Oper) {
14761 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14762 Object.get()->Classify(Context), Args, CandidateSet,
14763 /*SuppressUserConversion=*/false);
14764 }
14765
14766 // C++ [over.call.object]p2:
14767 // In addition, for each (non-explicit in C++0x) conversion function
14768 // declared in T of the form
14769 //
14770 // operator conversion-type-id () cv-qualifier;
14771 //
14772 // where cv-qualifier is the same cv-qualification as, or a
14773 // greater cv-qualification than, cv, and where conversion-type-id
14774 // denotes the type "pointer to function of (P1,...,Pn) returning
14775 // R", or the type "reference to pointer to function of
14776 // (P1,...,Pn) returning R", or the type "reference to function
14777 // of (P1,...,Pn) returning R", a surrogate call function [...]
14778 // is also considered as a candidate function. Similarly,
14779 // surrogate call functions are added to the set of candidate
14780 // functions for each conversion function declared in an
14781 // accessible base class provided the function is not hidden
14782 // within T by another intervening declaration.
14783 const auto &Conversions =
14784 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14785 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14786 NamedDecl *D = *I;
14787 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14788 if (isa<UsingShadowDecl>(D))
14789 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14790
14791 // Skip over templated conversion functions; they aren't
14792 // surrogates.
14793 if (isa<FunctionTemplateDecl>(D))
14794 continue;
14795
14796 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14797 if (!Conv->isExplicit()) {
14798 // Strip the reference type (if any) and then the pointer type (if
14799 // any) to get down to what might be a function type.
14800 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14801 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14802 ConvType = ConvPtrType->getPointeeType();
14803
14804 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14805 {
14806 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14807 Object.get(), Args, CandidateSet);
14808 }
14809 }
14810 }
14811
14812 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14813
14814 // Perform overload resolution.
14815 OverloadCandidateSet::iterator Best;
14816 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14817 Best)) {
14818 case OR_Success:
14819 // Overload resolution succeeded; we'll build the appropriate call
14820 // below.
14821 break;
14822
14823 case OR_No_Viable_Function: {
14824 PartialDiagnostic PD =
14825 CandidateSet.empty()
14826 ? (PDiag(diag::err_ovl_no_oper)
14827 << Object.get()->getType() << /*call*/ 1
14828 << Object.get()->getSourceRange())
14829 : (PDiag(diag::err_ovl_no_viable_object_call)
14830 << Object.get()->getType() << Object.get()->getSourceRange());
14831 CandidateSet.NoteCandidates(
14832 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14833 OCD_AllCandidates, Args);
14834 break;
14835 }
14836 case OR_Ambiguous:
14837 CandidateSet.NoteCandidates(
14838 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14839 PDiag(diag::err_ovl_ambiguous_object_call)
14840 << Object.get()->getType()
14841 << Object.get()->getSourceRange()),
14842 *this, OCD_AmbiguousCandidates, Args);
14843 break;
14844
14845 case OR_Deleted:
14846 CandidateSet.NoteCandidates(
14847 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14848 PDiag(diag::err_ovl_deleted_object_call)
14849 << Object.get()->getType()
14850 << Object.get()->getSourceRange()),
14851 *this, OCD_AllCandidates, Args);
14852 break;
14853 }
14854
14855 if (Best == CandidateSet.end())
14856 return true;
14857
14858 UnbridgedCasts.restore();
14859
14860 if (Best->Function == nullptr) {
14861 // Since there is no function declaration, this is one of the
14862 // surrogate candidates. Dig out the conversion function.
14863 CXXConversionDecl *Conv
14864 = cast<CXXConversionDecl>(
14865 Best->Conversions[0].UserDefined.ConversionFunction);
14866
14867 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14868 Best->FoundDecl);
14869 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14870 return ExprError();
14871 assert(Conv == Best->FoundDecl.getDecl() &&(static_cast <bool> (Conv == Best->FoundDecl.getDecl
() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "clang/lib/Sema/SemaOverload.cpp", 14872, __extension__ __PRETTY_FUNCTION__
))
14872 "Found Decl & conversion-to-functionptr should be same, right?!")(static_cast <bool> (Conv == Best->FoundDecl.getDecl
() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "clang/lib/Sema/SemaOverload.cpp", 14872, __extension__ __PRETTY_FUNCTION__
))
;
14873 // We selected one of the surrogate functions that converts the
14874 // object parameter to a function pointer. Perform the conversion
14875 // on the object argument, then let BuildCallExpr finish the job.
14876
14877 // Create an implicit member expr to refer to the conversion operator.
14878 // and then call it.
14879 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14880 Conv, HadMultipleCandidates);
14881 if (Call.isInvalid())
14882 return ExprError();
14883 // Record usage of conversion in an implicit cast.
14884 Call = ImplicitCastExpr::Create(
14885 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14886 nullptr, VK_PRValue, CurFPFeatureOverrides());
14887
14888 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14889 }
14890
14891 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14892
14893 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14894 // that calls this method, using Object for the implicit object
14895 // parameter and passing along the remaining arguments.
14896 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14897
14898 // An error diagnostic has already been printed when parsing the declaration.
14899 if (Method->isInvalidDecl())
14900 return ExprError();
14901
14902 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14903 unsigned NumParams = Proto->getNumParams();
14904
14905 DeclarationNameInfo OpLocInfo(
14906 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14907 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14908 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14909 Obj, HadMultipleCandidates,
14910 OpLocInfo.getLoc(),
14911 OpLocInfo.getInfo());
14912 if (NewFn.isInvalid())
14913 return true;
14914
14915 SmallVector<Expr *, 8> MethodArgs;
14916 MethodArgs.reserve(NumParams + 1);
14917
14918 bool IsError = false;
14919
14920 // Initialize the implicit object parameter if needed.
14921 // Since C++2b, this could also be a call to a static call operator
14922 // which we emit as a regular CallExpr.
14923 if (Method->isInstance()) {
14924 ExprResult ObjRes = PerformObjectArgumentInitialization(
14925 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14926 if (ObjRes.isInvalid())
14927 IsError = true;
14928 else
14929 Object = ObjRes;
14930 MethodArgs.push_back(Object.get());
14931 }
14932
14933 IsError |= PrepareArgumentsForCallToObjectOfClassType(
14934 *this, MethodArgs, Method, Args, LParenLoc);
14935
14936 // If this is a variadic call, handle args passed through "...".
14937 if (Proto->isVariadic()) {
14938 // Promote the arguments (C99 6.5.2.2p7).
14939 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14940 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14941 nullptr);
14942 IsError |= Arg.isInvalid();
14943 MethodArgs.push_back(Arg.get());
14944 }
14945 }
14946
14947 if (IsError)
14948 return true;
14949
14950 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14951
14952 // Once we've built TheCall, all of the expressions are properly owned.
14953 QualType ResultTy = Method->getReturnType();
14954 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14955 ResultTy = ResultTy.getNonLValueExprType(Context);
14956
14957 CallExpr *TheCall;
14958 if (Method->isInstance())
14959 TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(),
14960 MethodArgs, ResultTy, VK, RParenLoc,
14961 CurFPFeatureOverrides());
14962 else
14963 TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK,
14964 RParenLoc, CurFPFeatureOverrides());
14965
14966 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14967 return true;
14968
14969 if (CheckFunctionCall(Method, TheCall, Proto))
14970 return true;
14971
14972 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14973}
14974
14975/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14976/// (if one exists), where @c Base is an expression of class type and
14977/// @c Member is the name of the member we're trying to find.
14978ExprResult
14979Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14980 bool *NoArrowOperatorFound) {
14981 assert(Base->getType()->isRecordType() &&(static_cast <bool> (Base->getType()->isRecordType
() && "left-hand side must have class type") ? void (
0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "clang/lib/Sema/SemaOverload.cpp", 14982, __extension__ __PRETTY_FUNCTION__
))
14982 "left-hand side must have class type")(static_cast <bool> (Base->getType()->isRecordType
() && "left-hand side must have class type") ? void (
0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "clang/lib/Sema/SemaOverload.cpp", 14982, __extension__ __PRETTY_FUNCTION__
))
;
14983
14984 if (checkPlaceholderForOverload(*this, Base))
14985 return ExprError();
14986
14987 SourceLocation Loc = Base->getExprLoc();
14988
14989 // C++ [over.ref]p1:
14990 //
14991 // [...] An expression x->m is interpreted as (x.operator->())->m
14992 // for a class object x of type T if T::operator->() exists and if
14993 // the operator is selected as the best match function by the
14994 // overload resolution mechanism (13.3).
14995 DeclarationName OpName =
14996 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14997 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14998
14999 if (RequireCompleteType(Loc, Base->getType(),
15000 diag::err_typecheck_incomplete_tag, Base))
15001 return ExprError();
15002
15003 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15004 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15005 R.suppressDiagnostics();
15006
15007 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15008 Oper != OperEnd; ++Oper) {
15009 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15010 None, CandidateSet, /*SuppressUserConversion=*/false);
15011 }
15012
15013 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15014
15015 // Perform overload resolution.
15016 OverloadCandidateSet::iterator Best;
15017 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15018 case OR_Success:
15019 // Overload resolution succeeded; we'll build the call below.
15020 break;
15021
15022 case OR_No_Viable_Function: {
15023 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15024 if (CandidateSet.empty()) {
15025 QualType BaseType = Base->getType();
15026 if (NoArrowOperatorFound) {
15027 // Report this specific error to the caller instead of emitting a
15028 // diagnostic, as requested.
15029 *NoArrowOperatorFound = true;
15030 return ExprError();
15031 }
15032 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15033 << BaseType << Base->getSourceRange();
15034 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15035 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15036 << FixItHint::CreateReplacement(OpLoc, ".");
15037 }
15038 } else
15039 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15040 << "operator->" << Base->getSourceRange();
15041 CandidateSet.NoteCandidates(*this, Base, Cands);
15042 return ExprError();
15043 }
15044 case OR_Ambiguous:
15045 CandidateSet.NoteCandidates(
15046 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15047 << "->" << Base->getType()
15048 << Base->getSourceRange()),
15049 *this, OCD_AmbiguousCandidates, Base);
15050 return ExprError();
15051
15052 case OR_Deleted:
15053 CandidateSet.NoteCandidates(
15054 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15055 << "->" << Base->getSourceRange()),
15056 *this, OCD_AllCandidates, Base);
15057 return ExprError();
15058 }
15059
15060 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15061
15062 // Convert the object parameter.
15063 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15064 ExprResult BaseResult =
15065 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
15066 Best->FoundDecl, Method);
15067 if (BaseResult.isInvalid())
15068 return ExprError();
15069 Base = BaseResult.get();
15070
15071 // Build the operator call.
15072 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15073 Base, HadMultipleCandidates, OpLoc);
15074 if (FnExpr.isInvalid())
15075 return ExprError();
15076
15077 QualType ResultTy = Method->getReturnType();
15078 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15079 ResultTy = ResultTy.getNonLValueExprType(Context);
15080 CXXOperatorCallExpr *TheCall =
15081 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15082 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15083
15084 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15085 return ExprError();
15086
15087 if (CheckFunctionCall(Method, TheCall,
15088 Method->getType()->castAs<FunctionProtoType>()))
15089 return ExprError();
15090
15091 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15092}
15093
15094/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15095/// a literal operator described by the provided lookup results.
15096ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15097 DeclarationNameInfo &SuffixInfo,
15098 ArrayRef<Expr*> Args,
15099 SourceLocation LitEndLoc,
15100 TemplateArgumentListInfo *TemplateArgs) {
15101 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15102
15103 OverloadCandidateSet CandidateSet(UDSuffixLoc,
15104 OverloadCandidateSet::CSK_Normal);
15105 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15106 TemplateArgs);
15107
15108 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15109
15110 // Perform overload resolution. This will usually be trivial, but might need
15111 // to perform substitutions for a literal operator template.
15112 OverloadCandidateSet::iterator Best;
15113 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15114 case OR_Success:
15115 case OR_Deleted:
15116 break;
15117
15118 case OR_No_Viable_Function:
15119 CandidateSet.NoteCandidates(
15120 PartialDiagnosticAt(UDSuffixLoc,
15121 PDiag(diag::err_ovl_no_viable_function_in_call)
15122 << R.getLookupName()),
15123 *this, OCD_AllCandidates, Args);
15124 return ExprError();
15125
15126 case OR_Ambiguous:
15127 CandidateSet.NoteCandidates(
15128 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15129 << R.getLookupName()),
15130 *this, OCD_AmbiguousCandidates, Args);
15131 return ExprError();
15132 }
15133
15134 FunctionDecl *FD = Best->Function;
15135 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15136 nullptr, HadMultipleCandidates,
15137 SuffixInfo.getLoc(),
15138 SuffixInfo.getInfo());
15139 if (Fn.isInvalid())
15140 return true;
15141
15142 // Check the argument types. This should almost always be a no-op, except
15143 // that array-to-pointer decay is applied to string literals.
15144 Expr *ConvArgs[2];
15145 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15146 ExprResult InputInit = PerformCopyInitialization(
15147 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15148 SourceLocation(), Args[ArgIdx]);
15149 if (InputInit.isInvalid())
15150 return true;
15151 ConvArgs[ArgIdx] = InputInit.get();
15152 }
15153
15154 QualType ResultTy = FD->getReturnType();
15155 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15156 ResultTy = ResultTy.getNonLValueExprType(Context);
15157
15158 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15159 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
15160 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15161
15162 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15163 return ExprError();
15164
15165 if (CheckFunctionCall(FD, UDL, nullptr))
15166 return ExprError();
15167
15168 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15169}
15170
15171/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15172/// given LookupResult is non-empty, it is assumed to describe a member which
15173/// will be invoked. Otherwise, the function will be found via argument
15174/// dependent lookup.
15175/// CallExpr is set to a valid expression and FRS_Success returned on success,
15176/// otherwise CallExpr is set to ExprError() and some non-success value
15177/// is returned.
15178Sema::ForRangeStatus
15179Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15180 SourceLocation RangeLoc,
15181 const DeclarationNameInfo &NameInfo,
15182 LookupResult &MemberLookup,
15183 OverloadCandidateSet *CandidateSet,
15184 Expr *Range, ExprResult *CallExpr) {
15185 Scope *S = nullptr;
15186
15187 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15188 if (!MemberLookup.empty()) {
15189 ExprResult MemberRef =
15190 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15191 /*IsPtr=*/false, CXXScopeSpec(),
15192 /*TemplateKWLoc=*/SourceLocation(),
15193 /*FirstQualifierInScope=*/nullptr,
15194 MemberLookup,
15195 /*TemplateArgs=*/nullptr, S);
15196 if (MemberRef.isInvalid()) {
15197 *CallExpr = ExprError();
15198 return FRS_DiagnosticIssued;
15199 }
15200 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15201 if (CallExpr->isInvalid()) {
15202 *CallExpr = ExprError();
15203 return FRS_DiagnosticIssued;
15204 }
15205 } else {
15206 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15207 NestedNameSpecifierLoc(),
15208 NameInfo, UnresolvedSet<0>());
15209 if (FnR.isInvalid())
15210 return FRS_DiagnosticIssued;
15211 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15212
15213 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15214 CandidateSet, CallExpr);
15215 if (CandidateSet->empty() || CandidateSetError) {
15216 *CallExpr = ExprError();
15217 return FRS_NoViableFunction;
15218 }
15219 OverloadCandidateSet::iterator Best;
15220 OverloadingResult OverloadResult =
15221 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15222
15223 if (OverloadResult == OR_No_Viable_Function) {
15224 *CallExpr = ExprError();
15225 return FRS_NoViableFunction;
15226 }
15227 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15228 Loc, nullptr, CandidateSet, &Best,
15229 OverloadResult,
15230 /*AllowTypoCorrection=*/false);
15231 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15232 *CallExpr = ExprError();
15233 return FRS_DiagnosticIssued;
15234 }
15235 }
15236 return FRS_Success;
15237}
15238
15239
15240/// FixOverloadedFunctionReference - E is an expression that refers to
15241/// a C++ overloaded function (possibly with some parentheses and
15242/// perhaps a '&' around it). We have resolved the overloaded function
15243/// to the function declaration Fn, so patch up the expression E to
15244/// refer (possibly indirectly) to Fn. Returns the new expr.
15245Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15246 FunctionDecl *Fn) {
15247 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15248 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15249 Found, Fn);
15250 if (SubExpr == PE->getSubExpr())
15251 return PE;
15252
15253 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15254 }
15255
15256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15257 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15258 Found, Fn);
15259 assert(Context.hasSameType(ICE->getSubExpr()->getType(),(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "clang/lib/Sema/SemaOverload.cpp", 15261, __extension__ __PRETTY_FUNCTION__
))
15260 SubExpr->getType()) &&(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "clang/lib/Sema/SemaOverload.cpp", 15261, __extension__ __PRETTY_FUNCTION__
))
15261 "Implicit cast type cannot be determined from overload")(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "clang/lib/Sema/SemaOverload.cpp", 15261, __extension__ __PRETTY_FUNCTION__
))
;
15262 assert(ICE->path_empty() && "fixing up hierarchy conversion?")(static_cast <bool> (ICE->path_empty() && "fixing up hierarchy conversion?"
) ? void (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "clang/lib/Sema/SemaOverload.cpp", 15262, __extension__ __PRETTY_FUNCTION__
))
;
15263 if (SubExpr == ICE->getSubExpr())
15264 return ICE;
15265
15266 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15267 SubExpr, nullptr, ICE->getValueKind(),
15268 CurFPFeatureOverrides());
15269 }
15270
15271 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15272 if (!GSE->isResultDependent()) {
15273 Expr *SubExpr =
15274 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15275 if (SubExpr == GSE->getResultExpr())
15276 return GSE;
15277
15278 // Replace the resulting type information before rebuilding the generic
15279 // selection expression.
15280 ArrayRef<Expr *> A = GSE->getAssocExprs();
15281 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15282 unsigned ResultIdx = GSE->getResultIndex();
15283 AssocExprs[ResultIdx] = SubExpr;
15284
15285 return GenericSelectionExpr::Create(
15286 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15287 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15288 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15289 ResultIdx);
15290 }
15291 // Rather than fall through to the unreachable, return the original generic
15292 // selection expression.
15293 return GSE;
15294 }
15295
15296 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15297 assert(UnOp->getOpcode() == UO_AddrOf &&(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf &&
"Can only take the address of an overloaded function") ? void
(0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "clang/lib/Sema/SemaOverload.cpp", 15298, __extension__ __PRETTY_FUNCTION__
))
15298 "Can only take the address of an overloaded function")(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf &&
"Can only take the address of an overloaded function") ? void
(0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "clang/lib/Sema/SemaOverload.cpp", 15298, __extension__ __PRETTY_FUNCTION__
))
;
15299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15300 if (Method->isStatic()) {
15301 // Do nothing: static member functions aren't any different
15302 // from non-member functions.
15303 } else {
15304 // Fix the subexpression, which really has to be an
15305 // UnresolvedLookupExpr holding an overloaded member function
15306 // or template.
15307 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15308 Found, Fn);
15309 if (SubExpr == UnOp->getSubExpr())
15310 return UnOp;
15311
15312 assert(isa<DeclRefExpr>(SubExpr)(static_cast <bool> (isa<DeclRefExpr>(SubExpr) &&
"fixed to something other than a decl ref") ? void (0) : __assert_fail
("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "clang/lib/Sema/SemaOverload.cpp", 15313, __extension__ __PRETTY_FUNCTION__
))
15313 && "fixed to something other than a decl ref")(static_cast <bool> (isa<DeclRefExpr>(SubExpr) &&
"fixed to something other than a decl ref") ? void (0) : __assert_fail
("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "clang/lib/Sema/SemaOverload.cpp", 15313, __extension__ __PRETTY_FUNCTION__
))
;
15314 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()(static_cast <bool> (cast<DeclRefExpr>(SubExpr)->
getQualifier() && "fixed to a member ref with no nested name qualifier"
) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "clang/lib/Sema/SemaOverload.cpp", 15315, __extension__ __PRETTY_FUNCTION__
))
15315 && "fixed to a member ref with no nested name qualifier")(static_cast <bool> (cast<DeclRefExpr>(SubExpr)->
getQualifier() && "fixed to a member ref with no nested name qualifier"
) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "clang/lib/Sema/SemaOverload.cpp", 15315, __extension__ __PRETTY_FUNCTION__
))
;
15316
15317 // We have taken the address of a pointer to member
15318 // function. Perform the computation here so that we get the
15319 // appropriate pointer to member type.
15320 QualType ClassType
15321 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15322 QualType MemPtrType
15323 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15324 // Under the MS ABI, lock down the inheritance model now.
15325 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15326 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15327
15328 return UnaryOperator::Create(
15329 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15330 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15331 }
15332 }
15333 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15334 Found, Fn);
15335 if (SubExpr == UnOp->getSubExpr())
15336 return UnOp;
15337
15338 // FIXME: This can't currently fail, but in principle it could.
15339 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15340 .get();
15341 }
15342
15343 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15344 // FIXME: avoid copy.
15345 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15346 if (ULE->hasExplicitTemplateArgs()) {
15347 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15348 TemplateArgs = &TemplateArgsBuffer;
15349 }
15350
15351 QualType Type = Fn->getType();
15352 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15353
15354 // FIXME: Duplicated from BuildDeclarationNameExpr.
15355 if (unsigned BID = Fn->getBuiltinID()) {
15356 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15357 Type = Context.BuiltinFnTy;
15358 ValueKind = VK_PRValue;
15359 }
15360 }
15361
15362 DeclRefExpr *DRE = BuildDeclRefExpr(
15363 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15364 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15365 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15366 return DRE;
15367 }
15368
15369 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15370 // FIXME: avoid copy.
15371 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15372 if (MemExpr->hasExplicitTemplateArgs()) {
15373 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15374 TemplateArgs = &TemplateArgsBuffer;
15375 }
15376
15377 Expr *Base;
15378
15379 // If we're filling in a static method where we used to have an
15380 // implicit member access, rewrite to a simple decl ref.
15381 if (MemExpr->isImplicitAccess()) {
15382 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15383 DeclRefExpr *DRE = BuildDeclRefExpr(
15384 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15385 MemExpr->getQualifierLoc(), Found.getDecl(),
15386 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15387 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15388 return DRE;
15389 } else {
15390 SourceLocation Loc = MemExpr->getMemberLoc();
15391 if (MemExpr->getQualifier())
15392 Loc = MemExpr->getQualifierLoc().getBeginLoc();
15393 Base =
15394 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15395 }
15396 } else
15397 Base = MemExpr->getBase();
15398
15399 ExprValueKind valueKind;
15400 QualType type;
15401 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15402 valueKind = VK_LValue;
15403 type = Fn->getType();
15404 } else {
15405 valueKind = VK_PRValue;
15406 type = Context.BoundMemberTy;
15407 }
15408
15409 return BuildMemberExpr(
15410 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15411 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15412 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15413 type, valueKind, OK_Ordinary, TemplateArgs);
15414 }
15415
15416 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "clang/lib/Sema/SemaOverload.cpp", 15416)
;
15417}
15418
15419ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15420 DeclAccessPair Found,
15421 FunctionDecl *Fn) {
15422 return FixOverloadedFunctionReference(E.get(), Found, Fn);
15423}
15424
15425bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15426 FunctionDecl *Function) {
15427 if (!PartialOverloading || !Function)
15428 return true;
15429 if (Function->isVariadic())
15430 return false;
15431 if (const auto *Proto =
15432 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15433 if (Proto->isTemplateVariadic())
15434 return false;
15435 if (auto *Pattern = Function->getTemplateInstantiationPattern())
15436 if (const auto *Proto =
15437 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15438 if (Proto->isTemplateVariadic())
15439 return false;
15440 return true;
15441}