Debian Codegraph @

clang/lib/Sema/SemaOverload.cpp

raw
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 "CheckExprLifetime.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/EnterExpressionEvaluationContext.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Overload.h"
33 #include "clang/Sema/SemaARM.h"
34 #include "clang/Sema/SemaCUDA.h"
35 #include "clang/Sema/SemaObjC.h"
36 #include "clang/Sema/Template.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "llvm/ADT/DenseSet.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/STLForwardCompat.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include <algorithm>
45 #include <cassert>
46 #include <cstddef>
47 #include <cstdlib>
48 #include <optional>
49
50 using namespace clang;
51 using namespace sema;
52
53 using AllowedExplicit = Sema::AllowedExplicit;
54
55 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59 }
60
61 /// A convenience routine for creating a decayed reference to a function.
62 static ExprResult CreateFunctionRefExpr(
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
81 S.MarkDeclRefReferenced(DRE, Base);
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90 }
91
92 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
94 StandardConversionSequence &SCS,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
98 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
99 QualType &ToType,
100 bool InOverloadResolution,
101 StandardConversionSequence &SCS,
102 bool CStyle);
103 static OverloadingResult
104 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105 UserDefinedConversionSequence& User,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
110 static ImplicitConversionSequence::CompareKind
111 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
115 static ImplicitConversionSequence::CompareKind
116 CompareQualificationConversions(Sema &S,
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
120 static ImplicitConversionSequence::CompareKind
121 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125 /// GetConversionRank - Retrieve the implicit conversion rank
126 /// corresponding to the given implicit conversion kind.
127 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
128 static const ImplicitConversionRank Rank[] = {
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
133 ICR_Exact_Match,
134 ICR_Exact_Match,
135 ICR_Promotion,
136 ICR_Promotion,
137 ICR_Promotion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
150 ICR_OCL_Scalar_Widening,
151 ICR_Complex_Real_Conversion,
152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Writeback_Conversion,
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
161 ICR_C_Conversion,
162 ICR_C_Conversion_Extension,
163 ICR_Conversion,
164 ICR_HLSL_Dimension_Reduction,
165 ICR_HLSL_Dimension_Reduction,
166 ICR_Conversion,
167 ICR_HLSL_Scalar_Widening,
168 ICR_HLSL_Scalar_Widening,
169 };
170 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
171 return Rank[(int)Kind];
172 }
173
174 ImplicitConversionRank
175 clang::GetDimensionConversionRank(ImplicitConversionRank Base,
176 ImplicitConversionKind Dimension) {
177 ImplicitConversionRank Rank = GetConversionRank(Dimension);
178 if (Rank == ICR_HLSL_Scalar_Widening) {
179 if (Base == ICR_Promotion)
180 return ICR_HLSL_Scalar_Widening_Promotion;
181 if (Base == ICR_Conversion)
182 return ICR_HLSL_Scalar_Widening_Conversion;
183 }
184 if (Rank == ICR_HLSL_Dimension_Reduction) {
185 if (Base == ICR_Promotion)
186 return ICR_HLSL_Dimension_Reduction_Promotion;
187 if (Base == ICR_Conversion)
188 return ICR_HLSL_Dimension_Reduction_Conversion;
189 }
190 return Rank;
191 }
192
193 /// GetImplicitConversionName - Return the name of this kind of
194 /// implicit conversion.
195 static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
196 static const char *const Name[] = {
197 "No conversion",
198 "Lvalue-to-rvalue",
199 "Array-to-pointer",
200 "Function-to-pointer",
201 "Function pointer conversion",
202 "Qualification",
203 "Integral promotion",
204 "Floating point promotion",
205 "Complex promotion",
206 "Integral conversion",
207 "Floating conversion",
208 "Complex conversion",
209 "Floating-integral conversion",
210 "Pointer conversion",
211 "Pointer-to-member conversion",
212 "Boolean conversion",
213 "Compatible-types conversion",
214 "Derived-to-base conversion",
215 "Vector conversion",
216 "SVE Vector conversion",
217 "RVV Vector conversion",
218 "Vector splat",
219 "Complex-real conversion",
220 "Block Pointer conversion",
221 "Transparent Union Conversion",
222 "Writeback conversion",
223 "OpenCL Zero Event Conversion",
224 "OpenCL Zero Queue Conversion",
225 "C specific type conversion",
226 "Incompatible pointer conversion",
227 "Fixed point conversion",
228 "HLSL vector truncation",
229 "HLSL matrix truncation",
230 "Non-decaying array conversion",
231 "HLSL vector splat",
232 "HLSL matrix splat",
233 };
234 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
235 return Name[Kind];
236 }
237
238 /// StandardConversionSequence - Set the standard conversion
239 /// sequence to the identity conversion.
240 void StandardConversionSequence::setAsIdentityConversion() {
241 First = ICK_Identity;
242 Second = ICK_Identity;
243 Dimension = ICK_Identity;
244 Third = ICK_Identity;
245 DeprecatedStringLiteralToCharPtr = false;
246 QualificationIncludesObjCLifetime = false;
247 ReferenceBinding = false;
248 DirectBinding = false;
249 IsLvalueReference = true;
250 BindsToFunctionLvalue = false;
251 BindsToRvalue = false;
252 BindsImplicitObjectArgumentWithoutRefQualifier = false;
253 ObjCLifetimeConversionBinding = false;
254 FromBracedInitList = false;
255 CopyConstructor = nullptr;
256 }
257
258 /// getRank - Retrieve the rank of this standard conversion sequence
259 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
260 /// implicit conversions.
261 ImplicitConversionRank StandardConversionSequence::getRank() const {
262 ImplicitConversionRank Rank = ICR_Exact_Match;
263 if (GetConversionRank(First) > Rank)
264 Rank = GetConversionRank(First);
265 if (GetConversionRank(Second) > Rank)
266 Rank = GetConversionRank(Second);
267 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
268 Rank = GetDimensionConversionRank(Rank, Dimension);
269 if (GetConversionRank(Third) > Rank)
270 Rank = GetConversionRank(Third);
271 return Rank;
272 }
273
274 /// isPointerConversionToBool - Determines whether this conversion is
275 /// a conversion of a pointer or pointer-to-member to bool. This is
276 /// used as part of the ranking of standard conversion sequences
277 /// (C++ 13.3.3.2p4).
278 bool StandardConversionSequence::isPointerConversionToBool() const {
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer or function-to-pointer implicit conversions, so
281 // check for their presence as well as checking whether FromType is
282 // a pointer.
283 if (getToType(1)->isBooleanType() &&
284 (getFromType()->isPointerType() ||
285 getFromType()->isMemberPointerType() ||
286 getFromType()->isObjCObjectPointerType() ||
287 getFromType()->isBlockPointerType() ||
288 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
289 return true;
290
291 return false;
292 }
293
294 /// isPointerConversionToVoidPointer - Determines whether this
295 /// conversion is a conversion of a pointer to a void pointer. This is
296 /// used as part of the ranking of standard conversion sequences (C++
297 /// 13.3.3.2p4).
298 bool
299 StandardConversionSequence::
300 isPointerConversionToVoidPointer(ASTContext& Context) const {
301 QualType FromType = getFromType();
302 QualType ToType = getToType(1);
303
304 // Note that FromType has not necessarily been transformed by the
305 // array-to-pointer implicit conversion, so check for its presence
306 // and redo the conversion to get a pointer.
307 if (First == ICK_Array_To_Pointer)
308 FromType = Context.getArrayDecayedType(FromType);
309
310 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
311 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
312 return ToPtrType->getPointeeType()->isVoidType();
313
314 return false;
315 }
316
317 /// Skip any implicit casts which could be either part of a narrowing conversion
318 /// or after one in an implicit conversion.
319 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
320 const Expr *Converted) {
321 // We can have cleanups wrapping the converted expression; these need to be
322 // preserved so that destructors run if necessary.
323 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
324 Expr *Inner =
325 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
326 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
327 EWC->getObjects());
328 }
329
330 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
331 switch (ICE->getCastKind()) {
332 case CK_NoOp:
333 case CK_IntegralCast:
334 case CK_IntegralToBoolean:
335 case CK_IntegralToFloating:
336 case CK_BooleanToSignedIntegral:
337 case CK_FloatingToIntegral:
338 case CK_FloatingToBoolean:
339 case CK_FloatingCast:
340 Converted = ICE->getSubExpr();
341 continue;
342
343 default:
344 return Converted;
345 }
346 }
347
348 return Converted;
349 }
350
351 /// Check if this standard conversion sequence represents a narrowing
352 /// conversion, according to C++11 [dcl.init.list]p7.
353 ///
354 /// \param Ctx The AST context.
355 /// \param Converted The result of applying this standard conversion sequence.
356 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
357 /// value of the expression prior to the narrowing conversion.
358 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
359 /// type of the expression prior to the narrowing conversion.
360 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
361 /// from floating point types to integral types should be ignored.
362 NarrowingKind StandardConversionSequence::getNarrowingKind(
363 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
364 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
365 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
366 "narrowing check outside C++");
367
368 // C++11 [dcl.init.list]p7:
369 // A narrowing conversion is an implicit conversion ...
370 QualType FromType = getToType(0);
371 QualType ToType = getToType(1);
372
373 // A conversion to an enumeration type is narrowing if the conversion to
374 // the underlying type is narrowing. This only arises for expressions of
375 // the form 'Enum{init}'.
376 if (const auto *ED = ToType->getAsEnumDecl())
377 ToType = ED->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
381 case ICK_Boolean_Conversion:
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
384 if (FromType->isIntegralOrUnscopedEnumerationType())
385 goto IntegralConversion;
386 // -- from a pointer type or pointer-to-member type to bool, or
387 return NK_Type_Narrowing;
388
389 // -- from a floating-point type to an integer type, or
390 //
391 // -- from an integer type or unscoped enumeration type to a floating-point
392 // type, except where the source is a constant expression and the actual
393 // value after conversion will fit into the target type and will produce
394 // the original value when converted back to the original type, or
395 case ICK_Floating_Integral:
396 FloatingIntegralConversion:
397 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
398 return NK_Type_Narrowing;
399 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
400 ToType->isRealFloatingType()) {
401 if (IgnoreFloatToIntegralConversion)
402 return NK_Not_Narrowing;
403 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 assert(Initializer && "Unknown conversion expression");
405
406 // If it's value-dependent, we can't tell whether it's narrowing.
407 if (Initializer->isValueDependent())
408 return NK_Dependent_Narrowing;
409
410 if (std::optional<llvm::APSInt> IntConstantValue =
411 Initializer->getIntegerConstantExpr(Ctx)) {
412 // Convert the integer to the floating type.
413 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
414 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
415 llvm::APFloat::rmNearestTiesToEven);
416 // And back.
417 llvm::APSInt ConvertedValue = *IntConstantValue;
418 bool ignored;
419 llvm::APFloat::opStatus Status = Result.convertToInteger(
420 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
421 // If the converted-back integer has unspecified value, or if the
422 // resulting value is different, this was a narrowing conversion.
423 if (Status == llvm::APFloat::opInvalidOp ||
424 *IntConstantValue != ConvertedValue) {
425 ConstantValue = APValue(*IntConstantValue);
426 ConstantType = Initializer->getType();
427 return NK_Constant_Narrowing;
428 }
429 } else {
430 // Variables are always narrowings.
431 return NK_Variable_Narrowing;
432 }
433 }
434 return NK_Not_Narrowing;
435
436 // -- from long double to double or float, or from double to float, except
437 // where the source is a constant expression and the actual value after
438 // conversion is within the range of values that can be represented (even
439 // if it cannot be represented exactly), or
440 case ICK_Floating_Conversion:
441 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
442 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
443 // FromType is larger than ToType.
444 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
445
446 // If it's value-dependent, we can't tell whether it's narrowing.
447 if (Initializer->isValueDependent())
448 return NK_Dependent_Narrowing;
449
450 Expr::EvalResult R;
451 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
452 ((Ctx.getLangOpts().CPlusPlus &&
453 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
454 // Constant!
455 if (Ctx.getLangOpts().C23)
456 ConstantValue = R.Val;
457 assert(ConstantValue.isFloat());
458 llvm::APFloat FloatVal = ConstantValue.getFloat();
459 // Convert the source value into the target type.
460 bool ignored;
461 llvm::APFloat Converted = FloatVal;
462 llvm::APFloat::opStatus ConvertStatus =
463 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
464 llvm::APFloat::rmNearestTiesToEven, &ignored);
465 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
466 llvm::APFloat::rmNearestTiesToEven, &ignored);
467 if (Ctx.getLangOpts().C23) {
468 if (FloatVal.isNaN() && Converted.isNaN() &&
469 !FloatVal.isSignaling() && !Converted.isSignaling()) {
470 // Quiet NaNs are considered the same value, regardless of
471 // payloads.
472 return NK_Not_Narrowing;
473 }
474 // For normal values, check exact equality.
475 if (!Converted.bitwiseIsEqual(FloatVal)) {
476 ConstantType = Initializer->getType();
477 return NK_Constant_Narrowing;
478 }
479 } else {
480 // If there was no overflow, the source value is within the range of
481 // values that can be represented.
482 if (ConvertStatus & llvm::APFloat::opOverflow) {
483 ConstantType = Initializer->getType();
484 return NK_Constant_Narrowing;
485 }
486 }
487 } else {
488 return NK_Variable_Narrowing;
489 }
490 }
491 return NK_Not_Narrowing;
492
493 // -- from an integer type or unscoped enumeration type to an integer type
494 // that cannot represent all the values of the original type, except where
495 // (CWG2627) -- the source is a bit-field whose width w is less than that
496 // of its type (or, for an enumeration type, its underlying type) and the
497 // target type can represent all the values of a hypothetical extended
498 // integer type with width w and with the same signedness as the original
499 // type or
500 // -- the source is a constant expression and the actual value after
501 // conversion will fit into the target type and will produce the original
502 // value when converted back to the original type.
503 case ICK_Integral_Conversion:
504 IntegralConversion: {
505 assert(FromType->isIntegralOrUnscopedEnumerationType());
506 assert(ToType->isIntegralOrUnscopedEnumerationType());
507 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
508 unsigned FromWidth = Ctx.getIntWidth(FromType);
509 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
510 const unsigned ToWidth = Ctx.getIntWidth(ToType);
511
512 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
513 bool ToSigned, unsigned ToWidth) {
514 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
515 !(FromSigned && !ToSigned);
516 };
517
518 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
519 return NK_Not_Narrowing;
520
521 // Not all values of FromType can be represented in ToType.
522 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
523
524 bool DependentBitField = false;
525 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
526 if (BitField->getBitWidth()->isValueDependent())
527 DependentBitField = true;
528 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
529 BitFieldWidth < FromWidth) {
530 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
531 return NK_Not_Narrowing;
532
533 // The initializer will be truncated to the bit-field width
534 FromWidth = BitFieldWidth;
535 }
536 }
537
538 // If it's value-dependent, we can't tell whether it's narrowing.
539 if (Initializer->isValueDependent())
540 return NK_Dependent_Narrowing;
541
542 std::optional<llvm::APSInt> OptInitializerValue =
543 Initializer->getIntegerConstantExpr(Ctx);
544 if (!OptInitializerValue) {
545 // If the bit-field width was dependent, it might end up being small
546 // enough to fit in the target type (unless the target type is unsigned
547 // and the source type is signed, in which case it will never fit)
548 if (DependentBitField && !(FromSigned && !ToSigned))
549 return NK_Dependent_Narrowing;
550
551 // Otherwise, such a conversion is always narrowing
552 return NK_Variable_Narrowing;
553 }
554 llvm::APSInt &InitializerValue = *OptInitializerValue;
555 bool Narrowing = false;
556 if (FromWidth < ToWidth) {
557 // Negative -> unsigned is narrowing. Otherwise, more bits is never
558 // narrowing.
559 if (InitializerValue.isSigned() && InitializerValue.isNegative())
560 Narrowing = true;
561 } else {
562 // Add a bit to the InitializerValue so we don't have to worry about
563 // signed vs. unsigned comparisons.
564 InitializerValue =
565 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
566 // Convert the initializer to and from the target width and signed-ness.
567 llvm::APSInt ConvertedValue = InitializerValue;
568 ConvertedValue = ConvertedValue.trunc(ToWidth);
569 ConvertedValue.setIsSigned(ToSigned);
570 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
571 ConvertedValue.setIsSigned(InitializerValue.isSigned());
572 // If the result is different, this was a narrowing conversion.
573 if (ConvertedValue != InitializerValue)
574 Narrowing = true;
575 }
576 if (Narrowing) {
577 ConstantType = Initializer->getType();
578 ConstantValue = APValue(InitializerValue);
579 return NK_Constant_Narrowing;
580 }
581
582 return NK_Not_Narrowing;
583 }
584 case ICK_Complex_Real:
585 if (FromType->isComplexType() && !ToType->isComplexType())
586 return NK_Type_Narrowing;
587 return NK_Not_Narrowing;
588
589 case ICK_Floating_Promotion:
590 if (Ctx.getLangOpts().C23) {
591 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
592 Expr::EvalResult R;
593 if (Initializer->EvaluateAsRValue(R, Ctx)) {
594 ConstantValue = R.Val;
595 assert(ConstantValue.isFloat());
596 llvm::APFloat FloatVal = ConstantValue.getFloat();
597 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
598 // value, the unqualified versions of the type of the initializer and
599 // the corresponding real type of the object declared shall be
600 // compatible.
601 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
602 ConstantType = Initializer->getType();
603 return NK_Constant_Narrowing;
604 }
605 }
606 }
607 return NK_Not_Narrowing;
608 default:
609 // Other kinds of conversions are not narrowings.
610 return NK_Not_Narrowing;
611 }
612 }
613
614 /// dump - Print this standard conversion sequence to standard
615 /// error. Useful for debugging overloading issues.
616 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
617 raw_ostream &OS = llvm::errs();
618 bool PrintedSomething = false;
619 if (First != ICK_Identity) {
620 OS << GetImplicitConversionName(First);
621 PrintedSomething = true;
622 }
623
624 if (Second != ICK_Identity) {
625 if (PrintedSomething) {
626 OS << " -> ";
627 }
628 OS << GetImplicitConversionName(Second);
629
630 if (CopyConstructor) {
631 OS << " (by copy constructor)";
632 } else if (DirectBinding) {
633 OS << " (direct reference binding)";
634 } else if (ReferenceBinding) {
635 OS << " (reference binding)";
636 }
637 PrintedSomething = true;
638 }
639
640 if (Third != ICK_Identity) {
641 if (PrintedSomething) {
642 OS << " -> ";
643 }
644 OS << GetImplicitConversionName(Third);
645 PrintedSomething = true;
646 }
647
648 if (!PrintedSomething) {
649 OS << "No conversions required";
650 }
651 }
652
653 /// dump - Print this user-defined conversion sequence to standard
654 /// error. Useful for debugging overloading issues.
655 void UserDefinedConversionSequence::dump() const {
656 raw_ostream &OS = llvm::errs();
657 if (Before.First || Before.Second || Before.Third) {
658 Before.dump();
659 OS << " -> ";
660 }
661 if (ConversionFunction)
662 OS << '\'' << *ConversionFunction << '\'';
663 else
664 OS << "aggregate initialization";
665 if (After.First || After.Second || After.Third) {
666 OS << " -> ";
667 After.dump();
668 }
669 }
670
671 /// dump - Print this implicit conversion sequence to standard
672 /// error. Useful for debugging overloading issues.
673 void ImplicitConversionSequence::dump() const {
674 raw_ostream &OS = llvm::errs();
675 if (hasInitializerListContainerType())
676 OS << "Worst list element conversion: ";
677 switch (ConversionKind) {
678 case StandardConversion:
679 OS << "Standard conversion: ";
680 Standard.dump();
681 break;
682 case UserDefinedConversion:
683 OS << "User-defined conversion: ";
684 UserDefined.dump();
685 break;
686 case EllipsisConversion:
687 OS << "Ellipsis conversion";
688 break;
689 case AmbiguousConversion:
690 OS << "Ambiguous conversion";
691 break;
692 case BadConversion:
693 OS << "Bad conversion";
694 break;
695 }
696
697 OS << "\n";
698 }
699
700 void AmbiguousConversionSequence::construct() {
701 new (&conversions()) ConversionSet();
702 }
703
704 void AmbiguousConversionSequence::destruct() {
705 conversions().~ConversionSet();
706 }
707
708 void
709 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
710 FromTypePtr = O.FromTypePtr;
711 ToTypePtr = O.ToTypePtr;
712 new (&conversions()) ConversionSet(O.conversions());
713 }
714
715 namespace {
716 // Structure used by DeductionFailureInfo to store
717 // template argument information.
718 struct DFIArguments {
719 TemplateArgument FirstArg;
720 TemplateArgument SecondArg;
721 };
722 // Structure used by DeductionFailureInfo to store
723 // template parameter and template argument information.
724 struct DFIParamWithArguments : DFIArguments {
725 TemplateParameter Param;
726 };
727 // Structure used by DeductionFailureInfo to store template argument
728 // information and the index of the problematic call argument.
729 struct DFIDeducedMismatchArgs : DFIArguments {
730 TemplateArgumentList *TemplateArgs;
731 unsigned CallArgIndex;
732 };
733 // Structure used by DeductionFailureInfo to store information about
734 // unsatisfied constraints.
735 struct CNSInfo {
736 TemplateArgumentList *TemplateArgs;
737 ConstraintSatisfaction Satisfaction;
738 };
739 }
740
741 /// Convert from Sema's representation of template deduction information
742 /// to the form used in overload-candidate information.
743 DeductionFailureInfo
744 clang::MakeDeductionFailureInfo(ASTContext &Context,
745 TemplateDeductionResult TDK,
746 TemplateDeductionInfo &Info) {
747 DeductionFailureInfo Result;
748 Result.Result = static_cast<unsigned>(TDK);
749 Result.HasDiagnostic = false;
750 switch (TDK) {
751 case TemplateDeductionResult::Invalid:
752 case TemplateDeductionResult::InstantiationDepth:
753 case TemplateDeductionResult::TooManyArguments:
754 case TemplateDeductionResult::TooFewArguments:
755 case TemplateDeductionResult::MiscellaneousDeductionFailure:
756 case TemplateDeductionResult::CUDATargetMismatch:
757 Result.Data = nullptr;
758 break;
759
760 case TemplateDeductionResult::Incomplete:
761 case TemplateDeductionResult::InvalidExplicitArguments:
762 Result.Data = Info.Param.getOpaqueValue();
763 break;
764
765 case TemplateDeductionResult::DeducedMismatch:
766 case TemplateDeductionResult::DeducedMismatchNested: {
767 // FIXME: Should allocate from normal heap so that we can free this later.
768 auto *Saved = new (Context) DFIDeducedMismatchArgs;
769 Saved->FirstArg = Info.FirstArg;
770 Saved->SecondArg = Info.SecondArg;
771 Saved->TemplateArgs = Info.takeSugared();
772 Saved->CallArgIndex = Info.CallArgIndex;
773 Result.Data = Saved;
774 break;
775 }
776
777 case TemplateDeductionResult::NonDeducedMismatch: {
778 // FIXME: Should allocate from normal heap so that we can free this later.
779 DFIArguments *Saved = new (Context) DFIArguments;
780 Saved->FirstArg = Info.FirstArg;
781 Saved->SecondArg = Info.SecondArg;
782 Result.Data = Saved;
783 break;
784 }
785
786 case TemplateDeductionResult::IncompletePack:
787 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
788 case TemplateDeductionResult::Inconsistent:
789 case TemplateDeductionResult::Underqualified: {
790 // FIXME: Should allocate from normal heap so that we can free this later.
791 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
792 Saved->Param = Info.Param;
793 Saved->FirstArg = Info.FirstArg;
794 Saved->SecondArg = Info.SecondArg;
795 Result.Data = Saved;
796 break;
797 }
798
799 case TemplateDeductionResult::SubstitutionFailure:
800 Result.Data = Info.takeSugared();
801 if (Info.hasSFINAEDiagnostic()) {
802 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
803 SourceLocation(), PartialDiagnostic::NullDiagnostic());
804 Info.takeSFINAEDiagnostic(*Diag);
805 Result.HasDiagnostic = true;
806 }
807 break;
808
809 case TemplateDeductionResult::ConstraintsNotSatisfied: {
810 CNSInfo *Saved = new (Context) CNSInfo;
811 Saved->TemplateArgs = Info.takeSugared();
812 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
813 Result.Data = Saved;
814 break;
815 }
816
817 case TemplateDeductionResult::Success:
818 case TemplateDeductionResult::NonDependentConversionFailure:
819 case TemplateDeductionResult::AlreadyDiagnosed:
820 llvm_unreachable("not a deduction failure");
821 }
822
823 return Result;
824 }
825
826 void DeductionFailureInfo::Destroy() {
827 switch (static_cast<TemplateDeductionResult>(Result)) {
828 case TemplateDeductionResult::Success:
829 case TemplateDeductionResult::Invalid:
830 case TemplateDeductionResult::InstantiationDepth:
831 case TemplateDeductionResult::Incomplete:
832 case TemplateDeductionResult::TooManyArguments:
833 case TemplateDeductionResult::TooFewArguments:
834 case TemplateDeductionResult::InvalidExplicitArguments:
835 case TemplateDeductionResult::CUDATargetMismatch:
836 case TemplateDeductionResult::NonDependentConversionFailure:
837 break;
838
839 case TemplateDeductionResult::IncompletePack:
840 case TemplateDeductionResult::Inconsistent:
841 case TemplateDeductionResult::Underqualified:
842 case TemplateDeductionResult::DeducedMismatch:
843 case TemplateDeductionResult::DeducedMismatchNested:
844 case TemplateDeductionResult::NonDeducedMismatch:
845 // FIXME: Destroy the data?
846 Data = nullptr;
847 break;
848
849 case TemplateDeductionResult::SubstitutionFailure:
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
852 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
858 case TemplateDeductionResult::ConstraintsNotSatisfied:
859 // FIXME: Destroy the template argument list?
860 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
861 Data = nullptr;
862 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
863 Diag->~PartialDiagnosticAt();
864 HasDiagnostic = false;
865 }
866 break;
867
868 // Unhandled
869 case TemplateDeductionResult::MiscellaneousDeductionFailure:
870 case TemplateDeductionResult::AlreadyDiagnosed:
871 break;
872 }
873 }
874
875 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
876 if (HasDiagnostic)
877 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
878 return nullptr;
879 }
880
881 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
882 switch (static_cast<TemplateDeductionResult>(Result)) {
883 case TemplateDeductionResult::Success:
884 case TemplateDeductionResult::Invalid:
885 case TemplateDeductionResult::InstantiationDepth:
886 case TemplateDeductionResult::TooManyArguments:
887 case TemplateDeductionResult::TooFewArguments:
888 case TemplateDeductionResult::SubstitutionFailure:
889 case TemplateDeductionResult::DeducedMismatch:
890 case TemplateDeductionResult::DeducedMismatchNested:
891 case TemplateDeductionResult::NonDeducedMismatch:
892 case TemplateDeductionResult::CUDATargetMismatch:
893 case TemplateDeductionResult::NonDependentConversionFailure:
894 case TemplateDeductionResult::ConstraintsNotSatisfied:
895 return TemplateParameter();
896
897 case TemplateDeductionResult::Incomplete:
898 case TemplateDeductionResult::InvalidExplicitArguments:
899 return TemplateParameter::getFromOpaqueValue(Data);
900
901 case TemplateDeductionResult::IncompletePack:
902 case TemplateDeductionResult::Inconsistent:
903 case TemplateDeductionResult::Underqualified:
904 return static_cast<DFIParamWithArguments*>(Data)->Param;
905
906 // Unhandled
907 case TemplateDeductionResult::MiscellaneousDeductionFailure:
908 case TemplateDeductionResult::AlreadyDiagnosed:
909 break;
910 }
911
912 return TemplateParameter();
913 }
914
915 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
916 switch (static_cast<TemplateDeductionResult>(Result)) {
917 case TemplateDeductionResult::Success:
918 case TemplateDeductionResult::Invalid:
919 case TemplateDeductionResult::InstantiationDepth:
920 case TemplateDeductionResult::TooManyArguments:
921 case TemplateDeductionResult::TooFewArguments:
922 case TemplateDeductionResult::Incomplete:
923 case TemplateDeductionResult::IncompletePack:
924 case TemplateDeductionResult::InvalidExplicitArguments:
925 case TemplateDeductionResult::Inconsistent:
926 case TemplateDeductionResult::Underqualified:
927 case TemplateDeductionResult::NonDeducedMismatch:
928 case TemplateDeductionResult::CUDATargetMismatch:
929 case TemplateDeductionResult::NonDependentConversionFailure:
930 return nullptr;
931
932 case TemplateDeductionResult::DeducedMismatch:
933 case TemplateDeductionResult::DeducedMismatchNested:
934 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
935
936 case TemplateDeductionResult::SubstitutionFailure:
937 return static_cast<TemplateArgumentList*>(Data);
938
939 case TemplateDeductionResult::ConstraintsNotSatisfied:
940 return static_cast<CNSInfo*>(Data)->TemplateArgs;
941
942 // Unhandled
943 case TemplateDeductionResult::MiscellaneousDeductionFailure:
944 case TemplateDeductionResult::AlreadyDiagnosed:
945 break;
946 }
947
948 return nullptr;
949 }
950
951 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
952 switch (static_cast<TemplateDeductionResult>(Result)) {
953 case TemplateDeductionResult::Success:
954 case TemplateDeductionResult::Invalid:
955 case TemplateDeductionResult::InstantiationDepth:
956 case TemplateDeductionResult::Incomplete:
957 case TemplateDeductionResult::TooManyArguments:
958 case TemplateDeductionResult::TooFewArguments:
959 case TemplateDeductionResult::InvalidExplicitArguments:
960 case TemplateDeductionResult::SubstitutionFailure:
961 case TemplateDeductionResult::CUDATargetMismatch:
962 case TemplateDeductionResult::NonDependentConversionFailure:
963 case TemplateDeductionResult::ConstraintsNotSatisfied:
964 return nullptr;
965
966 case TemplateDeductionResult::IncompletePack:
967 case TemplateDeductionResult::Inconsistent:
968 case TemplateDeductionResult::Underqualified:
969 case TemplateDeductionResult::DeducedMismatch:
970 case TemplateDeductionResult::DeducedMismatchNested:
971 case TemplateDeductionResult::NonDeducedMismatch:
972 return &static_cast<DFIArguments*>(Data)->FirstArg;
973
974 // Unhandled
975 case TemplateDeductionResult::MiscellaneousDeductionFailure:
976 case TemplateDeductionResult::AlreadyDiagnosed:
977 break;
978 }
979
980 return nullptr;
981 }
982
983 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
984 switch (static_cast<TemplateDeductionResult>(Result)) {
985 case TemplateDeductionResult::Success:
986 case TemplateDeductionResult::Invalid:
987 case TemplateDeductionResult::InstantiationDepth:
988 case TemplateDeductionResult::Incomplete:
989 case TemplateDeductionResult::IncompletePack:
990 case TemplateDeductionResult::TooManyArguments:
991 case TemplateDeductionResult::TooFewArguments:
992 case TemplateDeductionResult::InvalidExplicitArguments:
993 case TemplateDeductionResult::SubstitutionFailure:
994 case TemplateDeductionResult::CUDATargetMismatch:
995 case TemplateDeductionResult::NonDependentConversionFailure:
996 case TemplateDeductionResult::ConstraintsNotSatisfied:
997 return nullptr;
998
999 case TemplateDeductionResult::Inconsistent:
1000 case TemplateDeductionResult::Underqualified:
1001 case TemplateDeductionResult::DeducedMismatch:
1002 case TemplateDeductionResult::DeducedMismatchNested:
1003 case TemplateDeductionResult::NonDeducedMismatch:
1004 return &static_cast<DFIArguments*>(Data)->SecondArg;
1005
1006 // Unhandled
1007 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1008 case TemplateDeductionResult::AlreadyDiagnosed:
1009 break;
1010 }
1011
1012 return nullptr;
1013 }
1014
1015 UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1016 switch (static_cast<TemplateDeductionResult>(Result)) {
1017 case TemplateDeductionResult::DeducedMismatch:
1018 case TemplateDeductionResult::DeducedMismatchNested:
1019 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1020
1021 default:
1022 return std::nullopt;
1023 }
1024 }
1025
1026 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1027 const FunctionDecl *Y) {
1028 if (!X || !Y)
1029 return false;
1030 if (X->getNumParams() != Y->getNumParams())
1031 return false;
1032 // FIXME: when do rewritten comparison operators
1033 // with explicit object parameters correspond?
1034 // https://cplusplus.github.io/CWG/issues/2797.html
1035 for (unsigned I = 0; I < X->getNumParams(); ++I)
1036 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1037 Y->getParamDecl(I)->getType()))
1038 return false;
1039 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1040 auto *FTY = Y->getDescribedFunctionTemplate();
1041 if (!FTY)
1042 return false;
1043 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1044 FTY->getTemplateParameters()))
1045 return false;
1046 }
1047 return true;
1048 }
1049
1050 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1051 Expr *FirstOperand, FunctionDecl *EqFD) {
1052 assert(EqFD->getOverloadedOperator() ==
1053 OverloadedOperatorKind::OO_EqualEqual);
1054 // C++2a [over.match.oper]p4:
1055 // A non-template function or function template F named operator== is a
1056 // rewrite target with first operand o unless a search for the name operator!=
1057 // in the scope S from the instantiation context of the operator expression
1058 // finds a function or function template that would correspond
1059 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1060 // scope of the class type of o if F is a class member, and the namespace
1061 // scope of which F is a member otherwise. A function template specialization
1062 // named operator== is a rewrite target if its function template is a rewrite
1063 // target.
1064 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1065 OverloadedOperatorKind::OO_ExclaimEqual);
1066 if (isa<CXXMethodDecl>(EqFD)) {
1067 // If F is a class member, search scope is class type of first operand.
1068 QualType RHS = FirstOperand->getType();
1069 auto *RHSRec = RHS->getAsCXXRecordDecl();
1070 if (!RHSRec)
1071 return true;
1072 LookupResult Members(S, NotEqOp, OpLoc,
1073 Sema::LookupNameKind::LookupMemberName);
1074 S.LookupQualifiedName(Members, RHSRec);
1075 Members.suppressAccessDiagnostics();
1076 for (NamedDecl *Op : Members)
1077 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1078 return false;
1079 return true;
1080 }
1081 // Otherwise the search scope is the namespace scope of which F is a member.
1082 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1083 auto *NotEqFD = Op->getAsFunction();
1084 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1085 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1086 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1087 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
1088 cast<Decl>(Op->getLexicalDeclContext())))
1089 return false;
1090 }
1091 return true;
1092 }
1093
1094 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1095 OverloadedOperatorKind Op) const {
1096 if (!AllowRewrittenCandidates)
1097 return false;
1098 return Op == OO_EqualEqual || Op == OO_Spaceship;
1099 }
1100
1101 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1102 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1103 auto Op = FD->getOverloadedOperator();
1104 if (!allowsReversed(Op))
1105 return false;
1106 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1107 assert(OriginalArgs.size() == 2);
1108 if (!shouldAddReversedEqEq(
1109 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1110 return false;
1111 }
1112 // Don't bother adding a reversed candidate that can never be a better
1113 // match than the non-reversed version.
1114 return FD->getNumNonObjectParams() != 2 ||
1115 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
1116 FD->getParamDecl(1)->getType()) ||
1117 FD->hasAttr<EnableIfAttr>();
1118 }
1119
1120 void OverloadCandidateSet::destroyCandidates() {
1121 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1122 for (auto &C : i->Conversions)
1123 C.~ImplicitConversionSequence();
1124 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1125 i->DeductionFailure.Destroy();
1126 }
1127 }
1128
1129 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1130 destroyCandidates();
1131 SlabAllocator.Reset();
1132 NumInlineBytesUsed = 0;
1133 Candidates.clear();
1134 Functions.clear();
1135 Kind = CSK;
1136 FirstDeferredCandidate = nullptr;
1137 DeferredCandidatesCount = 0;
1138 HasDeferredTemplateConstructors = false;
1139 ResolutionByPerfectCandidateIsDisabled = false;
1140 }
1141
1142 namespace {
1143 class UnbridgedCastsSet {
1144 struct Entry {
1145 Expr **Addr;
1146 Expr *Saved;
1147 };
1148 SmallVector<Entry, 2> Entries;
1149
1150 public:
1151 void save(Sema &S, Expr *&E) {
1152 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1153 Entry entry = { &E, E };
1154 Entries.push_back(entry);
1155 E = S.ObjC().stripARCUnbridgedCast(E);
1156 }
1157
1158 void restore() {
1159 for (SmallVectorImpl<Entry>::iterator
1160 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1161 *i->Addr = i->Saved;
1162 }
1163 };
1164 }
1165
1166 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1167 /// preprocessing on the given expression.
1168 ///
1169 /// \param unbridgedCasts a collection to which to add unbridged casts;
1170 /// without this, they will be immediately diagnosed as errors
1171 ///
1172 /// Return true on unrecoverable error.
1173 static bool
1174 checkPlaceholderForOverload(Sema &S, Expr *&E,
1175 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1176 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1177 // We can't handle overloaded expressions here because overload
1178 // resolution might reasonably tweak them.
1179 if (placeholder->getKind() == BuiltinType::Overload) return false;
1180
1181 // If the context potentially accepts unbridged ARC casts, strip
1182 // the unbridged cast and add it to the collection for later restoration.
1183 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1184 unbridgedCasts) {
1185 unbridgedCasts->save(S, E);
1186 return false;
1187 }
1188
1189 // Go ahead and check everything else.
1190 ExprResult result = S.CheckPlaceholderExpr(E);
1191 if (result.isInvalid())
1192 return true;
1193
1194 E = result.get();
1195 return false;
1196 }
1197
1198 // Nothing to do.
1199 return false;
1200 }
1201
1202 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1203 /// placeholders.
1204 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1205 UnbridgedCastsSet &unbridged) {
1206 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1207 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1208 return true;
1209
1210 return false;
1211 }
1212
1213 OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1214 const LookupResult &Old, NamedDecl *&Match,
1215 bool NewIsUsingDecl) {
1216 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1217 I != E; ++I) {
1218 NamedDecl *OldD = *I;
1219
1220 bool OldIsUsingDecl = false;
1221 if (isa<UsingShadowDecl>(OldD)) {
1222 OldIsUsingDecl = true;
1223
1224 // We can always introduce two using declarations into the same
1225 // context, even if they have identical signatures.
1226 if (NewIsUsingDecl) continue;
1227
1228 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1229 }
1230
1231 // A using-declaration does not conflict with another declaration
1232 // if one of them is hidden.
1233 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1234 continue;
1235
1236 // If either declaration was introduced by a using declaration,
1237 // we'll need to use slightly different rules for matching.
1238 // Essentially, these rules are the normal rules, except that
1239 // function templates hide function templates with different
1240 // return types or template parameter lists.
1241 bool UseMemberUsingDeclRules =
1242 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1243 !New->getFriendObjectKind();
1244
1245 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1246 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1247 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1248 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1249 continue;
1250 }
1251
1252 if (!isa<FunctionTemplateDecl>(OldD) &&
1253 !shouldLinkPossiblyHiddenDecl(*I, New))
1254 continue;
1255
1256 Match = *I;
1257 return OverloadKind::Match;
1258 }
1259
1260 // Builtins that have custom typechecking or have a reference should
1261 // not be overloadable or redeclarable.
1262 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1263 Match = *I;
1264 return OverloadKind::NonFunction;
1265 }
1266 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1267 // We can overload with these, which can show up when doing
1268 // redeclaration checks for UsingDecls.
1269 assert(Old.getLookupKind() == LookupUsingDeclName);
1270 } else if (isa<TagDecl>(OldD)) {
1271 // We can always overload with tags by hiding them.
1272 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1273 // Optimistically assume that an unresolved using decl will
1274 // overload; if it doesn't, we'll have to diagnose during
1275 // template instantiation.
1276 //
1277 // Exception: if the scope is dependent and this is not a class
1278 // member, the using declaration can only introduce an enumerator.
1279 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1280 Match = *I;
1281 return OverloadKind::NonFunction;
1282 }
1283 } else {
1284 // (C++ 13p1):
1285 // Only function declarations can be overloaded; object and type
1286 // declarations cannot be overloaded.
1287 Match = *I;
1288 return OverloadKind::NonFunction;
1289 }
1290 }
1291
1292 // C++ [temp.friend]p1:
1293 // For a friend function declaration that is not a template declaration:
1294 // -- if the name of the friend is a qualified or unqualified template-id,
1295 // [...], otherwise
1296 // -- if the name of the friend is a qualified-id and a matching
1297 // non-template function is found in the specified class or namespace,
1298 // the friend declaration refers to that function, otherwise,
1299 // -- if the name of the friend is a qualified-id and a matching function
1300 // template is found in the specified class or namespace, the friend
1301 // declaration refers to the deduced specialization of that function
1302 // template, otherwise
1303 // -- the name shall be an unqualified-id [...]
1304 // If we get here for a qualified friend declaration, we've just reached the
1305 // third bullet. If the type of the friend is dependent, skip this lookup
1306 // until instantiation.
1307 if (New->getFriendObjectKind() && New->getQualifier() &&
1308 !New->getDescribedFunctionTemplate() &&
1309 !New->getDependentSpecializationInfo() &&
1310 !New->getType()->isDependentType()) {
1311 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1312 TemplateSpecResult.addAllDecls(Old);
1313 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1314 /*QualifiedFriend*/true)) {
1315 New->setInvalidDecl();
1316 return OverloadKind::Overload;
1317 }
1318
1319 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1320 return OverloadKind::Match;
1321 }
1322
1323 return OverloadKind::Overload;
1324 }
1325
1326 template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1327 assert(D && "function decl should not be null");
1328 if (auto *A = D->getAttr<AttrT>())
1329 return !A->isImplicit();
1330 return false;
1331 }
1332
1333 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1334 FunctionDecl *Old,
1335 bool UseMemberUsingDeclRules,
1336 bool ConsiderCudaAttrs,
1337 bool UseOverrideRules = false) {
1338 // C++ [basic.start.main]p2: This function shall not be overloaded.
1339 if (New->isMain())
1340 return false;
1341
1342 // MSVCRT user defined entry points cannot be overloaded.
1343 if (New->isMSVCRTEntryPoint())
1344 return false;
1345
1346 NamedDecl *OldDecl = Old;
1347 NamedDecl *NewDecl = New;
1348 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1349 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1350
1351 // C++ [temp.fct]p2:
1352 // A function template can be overloaded with other function templates
1353 // and with normal (non-template) functions.
1354 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1355 return true;
1356
1357 // Is the function New an overload of the function Old?
1358 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1359 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1360
1361 // Compare the signatures (C++ 1.3.10) of the two functions to
1362 // determine whether they are overloads. If we find any mismatch
1363 // in the signature, they are overloads.
1364
1365 // If either of these functions is a K&R-style function (no
1366 // prototype), then we consider them to have matching signatures.
1367 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1368 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1369 return false;
1370
1371 const auto *OldType = cast<FunctionProtoType>(OldQType);
1372 const auto *NewType = cast<FunctionProtoType>(NewQType);
1373
1374 // The signature of a function includes the types of its
1375 // parameters (C++ 1.3.10), which includes the presence or absence
1376 // of the ellipsis; see C++ DR 357).
1377 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1378 return true;
1379
1380 // For member-like friends, the enclosing class is part of the signature.
1381 if ((New->isMemberLikeConstrainedFriend() ||
1382 Old->isMemberLikeConstrainedFriend()) &&
1383 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1384 return true;
1385
1386 // Compare the parameter lists.
1387 // This can only be done once we have establish that friend functions
1388 // inhabit the same context, otherwise we might tried to instantiate
1389 // references to non-instantiated entities during constraint substitution.
1390 // GH78101.
1391 if (NewTemplate) {
1392 OldDecl = OldTemplate;
1393 NewDecl = NewTemplate;
1394 // C++ [temp.over.link]p4:
1395 // The signature of a function template consists of its function
1396 // signature, its return type and its template parameter list. The names
1397 // of the template parameters are significant only for establishing the
1398 // relationship between the template parameters and the rest of the
1399 // signature.
1400 //
1401 // We check the return type and template parameter lists for function
1402 // templates first; the remaining checks follow.
1403 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1404 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1405 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1406 bool SameReturnType = SemaRef.Context.hasSameType(
1407 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1408 // FIXME(GH58571): Match template parameter list even for non-constrained
1409 // template heads. This currently ensures that the code prior to C++20 is
1410 // not newly broken.
1411 bool ConstraintsInTemplateHead =
1412 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1413 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1414 // C++ [namespace.udecl]p11:
1415 // The set of declarations named by a using-declarator that inhabits a
1416 // class C does not include member functions and member function
1417 // templates of a base class that "correspond" to (and thus would
1418 // conflict with) a declaration of a function or function template in
1419 // C.
1420 // Comparing return types is not required for the "correspond" check to
1421 // decide whether a member introduced by a shadow declaration is hidden.
1422 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1423 !SameTemplateParameterList)
1424 return true;
1425 if (!UseMemberUsingDeclRules &&
1426 (!SameTemplateParameterList || !SameReturnType))
1427 return true;
1428 }
1429
1430 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1431 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1432
1433 int OldParamsOffset = 0;
1434 int NewParamsOffset = 0;
1435
1436 // When determining if a method is an overload from a base class, act as if
1437 // the implicit object parameter are of the same type.
1438
1439 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1440 if (M->isExplicitObjectMemberFunction()) {
1441 auto ThisType = M->getFunctionObjectParameterReferenceType();
1442 if (ThisType.isConstQualified())
1443 Q.removeConst();
1444 return Q;
1445 }
1446
1447 // We do not allow overloading based off of '__restrict'.
1448 Q.removeRestrict();
1449
1450 // We may not have applied the implicit const for a constexpr member
1451 // function yet (because we haven't yet resolved whether this is a static
1452 // or non-static member function). Add it now, on the assumption that this
1453 // is a redeclaration of OldMethod.
1454 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1455 (M->isConstexpr() || M->isConsteval()) &&
1456 !isa<CXXConstructorDecl>(NewMethod))
1457 Q.addConst();
1458 return Q;
1459 };
1460
1461 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1462 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1463 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1464
1465 if (OldMethod->isExplicitObjectMemberFunction()) {
1466 BS.Quals.removeVolatile();
1467 DS.Quals.removeVolatile();
1468 }
1469
1470 return BS.Quals == DS.Quals;
1471 };
1472
1473 auto CompareType = [&](QualType Base, QualType D) {
1474 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1475 auto DS = D.getNonReferenceType().getCanonicalType().split();
1476
1477 if (!AreQualifiersEqual(BS, DS))
1478 return false;
1479
1480 if (OldMethod->isImplicitObjectMemberFunction() &&
1481 OldMethod->getParent() != NewMethod->getParent()) {
1482 CanQualType ParentType =
1483 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1484 if (ParentType.getTypePtr() != BS.Ty)
1485 return false;
1486 BS.Ty = DS.Ty;
1487 }
1488
1489 // FIXME: should we ignore some type attributes here?
1490 if (BS.Ty != DS.Ty)
1491 return false;
1492
1493 if (Base->isLValueReferenceType())
1494 return D->isLValueReferenceType();
1495 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1496 };
1497
1498 // If the function is a class member, its signature includes the
1499 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1500 auto DiagnoseInconsistentRefQualifiers = [&]() {
1501 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1502 return false;
1503 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1504 return false;
1505 if (OldMethod->isExplicitObjectMemberFunction() ||
1506 NewMethod->isExplicitObjectMemberFunction())
1507 return false;
1508 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1509 NewMethod->getRefQualifier() == RQ_None)) {
1510 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1511 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1512 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1513 return true;
1514 }
1515 return false;
1516 };
1517
1518 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1519 OldParamsOffset++;
1520 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1521 NewParamsOffset++;
1522
1523 if (OldType->getNumParams() - OldParamsOffset !=
1524 NewType->getNumParams() - NewParamsOffset ||
1525 !SemaRef.FunctionParamTypesAreEqual(
1526 {OldType->param_type_begin() + OldParamsOffset,
1527 OldType->param_type_end()},
1528 {NewType->param_type_begin() + NewParamsOffset,
1529 NewType->param_type_end()},
1530 nullptr)) {
1531 return true;
1532 }
1533
1534 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1535 !NewMethod->isStatic()) {
1536 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1537 const CXXMethodDecl *New) {
1538 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1539 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1540
1541 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1542 return F->getRefQualifier() == RQ_None &&
1543 !F->isExplicitObjectMemberFunction();
1544 };
1545
1546 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1547 CompareType(OldObjectType.getNonReferenceType(),
1548 NewObjectType.getNonReferenceType()))
1549 return true;
1550 return CompareType(OldObjectType, NewObjectType);
1551 }(OldMethod, NewMethod);
1552
1553 if (!HaveCorrespondingObjectParameters) {
1554 if (DiagnoseInconsistentRefQualifiers())
1555 return true;
1556 // CWG2554
1557 // and, if at least one is an explicit object member function, ignoring
1558 // object parameters
1559 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1560 !OldMethod->isExplicitObjectMemberFunction()))
1561 return true;
1562 }
1563 }
1564
1565 if (!UseOverrideRules &&
1566 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1567 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1568 OldRC = Old->getTrailingRequiresClause();
1569 if (!NewRC != !OldRC)
1570 return true;
1571 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1572 return true;
1573 if (NewRC &&
1574 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1575 NewDecl, NewRC.ConstraintExpr))
1576 return true;
1577 }
1578
1579 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1580 NewMethod->isImplicitObjectMemberFunction()) {
1581 if (DiagnoseInconsistentRefQualifiers())
1582 return true;
1583 }
1584
1585 // Though pass_object_size is placed on parameters and takes an argument, we
1586 // consider it to be a function-level modifier for the sake of function
1587 // identity. Either the function has one or more parameters with
1588 // pass_object_size or it doesn't.
1589 if (functionHasPassObjectSizeParams(New) !=
1590 functionHasPassObjectSizeParams(Old))
1591 return true;
1592
1593 // enable_if attributes are an order-sensitive part of the signature.
1594 for (specific_attr_iterator<EnableIfAttr>
1595 NewI = New->specific_attr_begin<EnableIfAttr>(),
1596 NewE = New->specific_attr_end<EnableIfAttr>(),
1597 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1598 OldE = Old->specific_attr_end<EnableIfAttr>();
1599 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1600 if (NewI == NewE || OldI == OldE)
1601 return true;
1602 llvm::FoldingSetNodeID NewID, OldID;
1603 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1604 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1605 if (NewID != OldID)
1606 return true;
1607 }
1608
1609 // At this point, it is known that the two functions have the same signature.
1610 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1611 // Don't allow overloading of destructors. (In theory we could, but it
1612 // would be a giant change to clang.)
1613 if (!isa<CXXDestructorDecl>(New)) {
1614 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1615 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1616 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1617 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1618 "Unexpected invalid target.");
1619
1620 // Allow overloading of functions with same signature and different CUDA
1621 // target attributes.
1622 if (NewTarget != OldTarget) {
1623 // Special case: non-constexpr function is allowed to override
1624 // constexpr virtual function
1625 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1626 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1627 !hasExplicitAttr<CUDAHostAttr>(Old) &&
1628 !hasExplicitAttr<CUDADeviceAttr>(Old) &&
1629 !hasExplicitAttr<CUDAHostAttr>(New) &&
1630 !hasExplicitAttr<CUDADeviceAttr>(New)) {
1631 return false;
1632 }
1633 return true;
1634 }
1635 }
1636 }
1637 }
1638
1639 // The signatures match; this is not an overload.
1640 return false;
1641 }
1642
1643 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1644 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1645 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1646 ConsiderCudaAttrs);
1647 }
1648
1649 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1650 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1651 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1652 /*UseMemberUsingDeclRules=*/false,
1653 /*ConsiderCudaAttrs=*/true,
1654 /*UseOverrideRules=*/true);
1655 }
1656
1657 /// Tries a user-defined conversion from From to ToType.
1658 ///
1659 /// Produces an implicit conversion sequence for when a standard conversion
1660 /// is not an option. See TryImplicitConversion for more information.
1661 static ImplicitConversionSequence
1662 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1663 bool SuppressUserConversions,
1664 AllowedExplicit AllowExplicit,
1665 bool InOverloadResolution,
1666 bool CStyle,
1667 bool AllowObjCWritebackConversion,
1668 bool AllowObjCConversionOnExplicit) {
1669 ImplicitConversionSequence ICS;
1670
1671 if (SuppressUserConversions) {
1672 // We're not in the case above, so there is no conversion that
1673 // we can perform.
1674 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1675 return ICS;
1676 }
1677
1678 // Attempt user-defined conversion.
1679 OverloadCandidateSet Conversions(From->getExprLoc(),
1680 OverloadCandidateSet::CSK_Normal);
1681 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1682 Conversions, AllowExplicit,
1683 AllowObjCConversionOnExplicit)) {
1684 case OR_Success:
1685 case OR_Deleted:
1686 ICS.setUserDefined();
1687 // C++ [over.ics.user]p4:
1688 // A conversion of an expression of class type to the same class
1689 // type is given Exact Match rank, and a conversion of an
1690 // expression of class type to a base class of that type is
1691 // given Conversion rank, in spite of the fact that a copy
1692 // constructor (i.e., a user-defined conversion function) is
1693 // called for those cases.
1694 if (CXXConstructorDecl *Constructor
1695 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1696 QualType FromType;
1697 SourceLocation FromLoc;
1698 // C++11 [over.ics.list]p6, per DR2137:
1699 // C++17 [over.ics.list]p6:
1700 // If C is not an initializer-list constructor and the initializer list
1701 // has a single element of type cv U, where U is X or a class derived
1702 // from X, the implicit conversion sequence has Exact Match rank if U is
1703 // X, or Conversion rank if U is derived from X.
1704 bool FromListInit = false;
1705 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1706 InitList && InitList->getNumInits() == 1 &&
1707 !S.isInitListConstructor(Constructor)) {
1708 const Expr *SingleInit = InitList->getInit(0);
1709 FromType = SingleInit->getType();
1710 FromLoc = SingleInit->getBeginLoc();
1711 FromListInit = true;
1712 } else {
1713 FromType = From->getType();
1714 FromLoc = From->getBeginLoc();
1715 }
1716 QualType FromCanon =
1717 S.Context.getCanonicalType(FromType.getUnqualifiedType());
1718 QualType ToCanon
1719 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1720 if ((FromCanon == ToCanon ||
1721 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1722 // Turn this into a "standard" conversion sequence, so that it
1723 // gets ranked with standard conversion sequences.
1724 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1725 ICS.setStandard();
1726 ICS.Standard.setAsIdentityConversion();
1727 ICS.Standard.setFromType(FromType);
1728 ICS.Standard.setAllToTypes(ToType);
1729 ICS.Standard.FromBracedInitList = FromListInit;
1730 ICS.Standard.CopyConstructor = Constructor;
1731 ICS.Standard.FoundCopyConstructor = Found;
1732 if (ToCanon != FromCanon)
1733 ICS.Standard.Second = ICK_Derived_To_Base;
1734 }
1735 }
1736 break;
1737
1738 case OR_Ambiguous:
1739 ICS.setAmbiguous();
1740 ICS.Ambiguous.setFromType(From->getType());
1741 ICS.Ambiguous.setToType(ToType);
1742 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1743 Cand != Conversions.end(); ++Cand)
1744 if (Cand->Best)
1745 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1746 break;
1747
1748 // Fall through.
1749 case OR_No_Viable_Function:
1750 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1751 break;
1752 }
1753
1754 return ICS;
1755 }
1756
1757 /// TryImplicitConversion - Attempt to perform an implicit conversion
1758 /// from the given expression (Expr) to the given type (ToType). This
1759 /// function returns an implicit conversion sequence that can be used
1760 /// to perform the initialization. Given
1761 ///
1762 /// void f(float f);
1763 /// void g(int i) { f(i); }
1764 ///
1765 /// this routine would produce an implicit conversion sequence to
1766 /// describe the initialization of f from i, which will be a standard
1767 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1768 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1769 //
1770 /// Note that this routine only determines how the conversion can be
1771 /// performed; it does not actually perform the conversion. As such,
1772 /// it will not produce any diagnostics if no conversion is available,
1773 /// but will instead return an implicit conversion sequence of kind
1774 /// "BadConversion".
1775 ///
1776 /// If @p SuppressUserConversions, then user-defined conversions are
1777 /// not permitted.
1778 /// If @p AllowExplicit, then explicit user-defined conversions are
1779 /// permitted.
1780 ///
1781 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1782 /// writeback conversion, which allows __autoreleasing id* parameters to
1783 /// be initialized with __strong id* or __weak id* arguments.
1784 static ImplicitConversionSequence
1785 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1786 bool SuppressUserConversions,
1787 AllowedExplicit AllowExplicit,
1788 bool InOverloadResolution,
1789 bool CStyle,
1790 bool AllowObjCWritebackConversion,
1791 bool AllowObjCConversionOnExplicit) {
1792 ImplicitConversionSequence ICS;
1793 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1794 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1795 ICS.setStandard();
1796 return ICS;
1797 }
1798
1799 if (!S.getLangOpts().CPlusPlus) {
1800 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1801 return ICS;
1802 }
1803
1804 // C++ [over.ics.user]p4:
1805 // A conversion of an expression of class type to the same class
1806 // type is given Exact Match rank, and a conversion of an
1807 // expression of class type to a base class of that type is
1808 // given Conversion rank, in spite of the fact that a copy/move
1809 // constructor (i.e., a user-defined conversion function) is
1810 // called for those cases.
1811 QualType FromType = From->getType();
1812 if (ToType->isRecordType() &&
1813 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1814 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1815 ICS.setStandard();
1816 ICS.Standard.setAsIdentityConversion();
1817 ICS.Standard.setFromType(FromType);
1818 ICS.Standard.setAllToTypes(ToType);
1819
1820 // We don't actually check at this point whether there is a valid
1821 // copy/move constructor, since overloading just assumes that it
1822 // exists. When we actually perform initialization, we'll find the
1823 // appropriate constructor to copy the returned object, if needed.
1824 ICS.Standard.CopyConstructor = nullptr;
1825
1826 // Determine whether this is considered a derived-to-base conversion.
1827 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1828 ICS.Standard.Second = ICK_Derived_To_Base;
1829
1830 return ICS;
1831 }
1832
1833 if (S.getLangOpts().HLSL) {
1834 // Handle conversion of the HLSL resource types.
1835 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1836 if (FromTy->isHLSLAttributedResourceType()) {
1837 // Attributed resource types can convert to other attributed
1838 // resource types with the same attributes and contained types,
1839 // or to __hlsl_resource_t without any attributes.
1840 bool CanConvert = false;
1841 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1842 if (ToTy->isHLSLAttributedResourceType()) {
1843 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1844 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1845 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1846 FromResType->getWrappedType()) &&
1847 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1848 FromResType->getContainedType()) &&
1849 ToResType->getAttrs() == FromResType->getAttrs())
1850 CanConvert = true;
1851 } else if (ToTy->isHLSLResourceType()) {
1852 CanConvert = true;
1853 }
1854 if (CanConvert) {
1855 ICS.setStandard();
1856 ICS.Standard.setAsIdentityConversion();
1857 ICS.Standard.setFromType(FromType);
1858 ICS.Standard.setAllToTypes(ToType);
1859 return ICS;
1860 }
1861 }
1862 }
1863
1864 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1865 AllowExplicit, InOverloadResolution, CStyle,
1866 AllowObjCWritebackConversion,
1867 AllowObjCConversionOnExplicit);
1868 }
1869
1870 ImplicitConversionSequence
1871 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1872 bool SuppressUserConversions,
1873 AllowedExplicit AllowExplicit,
1874 bool InOverloadResolution,
1875 bool CStyle,
1876 bool AllowObjCWritebackConversion) {
1877 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1878 AllowExplicit, InOverloadResolution, CStyle,
1879 AllowObjCWritebackConversion,
1880 /*AllowObjCConversionOnExplicit=*/false);
1881 }
1882
1883 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1884 AssignmentAction Action,
1885 bool AllowExplicit) {
1886 if (checkPlaceholderForOverload(*this, From))
1887 return ExprError();
1888
1889 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1890 bool AllowObjCWritebackConversion =
1891 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1892 Action == AssignmentAction::Sending);
1893 if (getLangOpts().ObjC)
1894 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1895 From->getType(), From);
1896 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1897 *this, From, ToType,
1898 /*SuppressUserConversions=*/false,
1899 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1900 /*InOverloadResolution=*/false,
1901 /*CStyle=*/false, AllowObjCWritebackConversion,
1902 /*AllowObjCConversionOnExplicit=*/false);
1903 return PerformImplicitConversion(From, ToType, ICS, Action);
1904 }
1905
1906 bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1907 QualType &ResultTy) const {
1908 bool Changed = IsFunctionConversion(FromType, ToType);
1909 if (Changed)
1910 ResultTy = ToType;
1911 return Changed;
1912 }
1913
1914 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1915 if (Context.hasSameUnqualifiedType(FromType, ToType))
1916 return false;
1917
1918 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1919 // or F(t noexcept) -> F(t)
1920 // where F adds one of the following at most once:
1921 // - a pointer
1922 // - a member pointer
1923 // - a block pointer
1924 // Changes here need matching changes in FindCompositePointerType.
1925 CanQualType CanTo = Context.getCanonicalType(ToType);
1926 CanQualType CanFrom = Context.getCanonicalType(FromType);
1927 Type::TypeClass TyClass = CanTo->getTypeClass();
1928 if (TyClass != CanFrom->getTypeClass()) return false;
1929 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1930 if (TyClass == Type::Pointer) {
1931 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1932 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1933 } else if (TyClass == Type::BlockPointer) {
1934 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1935 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1936 } else if (TyClass == Type::MemberPointer) {
1937 auto ToMPT = CanTo.castAs<MemberPointerType>();
1938 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1939 // A function pointer conversion cannot change the class of the function.
1940 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1941 FromMPT->getMostRecentCXXRecordDecl()))
1942 return false;
1943 CanTo = ToMPT->getPointeeType();
1944 CanFrom = FromMPT->getPointeeType();
1945 } else {
1946 return false;
1947 }
1948
1949 TyClass = CanTo->getTypeClass();
1950 if (TyClass != CanFrom->getTypeClass()) return false;
1951 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1952 return false;
1953 }
1954
1955 const auto *FromFn = cast<FunctionType>(CanFrom);
1956 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1957
1958 const auto *ToFn = cast<FunctionType>(CanTo);
1959 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1960
1961 bool Changed = false;
1962
1963 // Drop 'noreturn' if not present in target type.
1964 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1965 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1966 Changed = true;
1967 }
1968
1969 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1970 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1971
1972 if (FromFPT && ToFPT) {
1973 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1974 QualType NewTy = Context.getFunctionType(
1975 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1976 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1977 ToFPT->hasCFIUncheckedCallee()));
1978 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1979 FromFn = FromFPT;
1980 Changed = true;
1981 }
1982 }
1983
1984 // Drop 'noexcept' if not present in target type.
1985 if (FromFPT && ToFPT) {
1986 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1987 FromFn = cast<FunctionType>(
1988 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1989 EST_None)
1990 .getTypePtr());
1991 Changed = true;
1992 }
1993
1994 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1995 // only if the ExtParameterInfo lists of the two function prototypes can be
1996 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1997 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1998 bool CanUseToFPT, CanUseFromFPT;
1999 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2000 CanUseFromFPT, NewParamInfos) &&
2001 CanUseToFPT && !CanUseFromFPT) {
2002 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2003 ExtInfo.ExtParameterInfos =
2004 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2005 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2006 FromFPT->getParamTypes(), ExtInfo);
2007 FromFn = QT->getAs<FunctionType>();
2008 Changed = true;
2009 }
2010
2011 if (Context.hasAnyFunctionEffects()) {
2012 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2013
2014 // Transparently add/drop effects; here we are concerned with
2015 // language rules/canonicalization. Adding/dropping effects is a warning.
2016 const auto FromFX = FromFPT->getFunctionEffects();
2017 const auto ToFX = ToFPT->getFunctionEffects();
2018 if (FromFX != ToFX) {
2019 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2020 ExtInfo.FunctionEffects = ToFX;
2021 QualType QT = Context.getFunctionType(
2022 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2023 FromFn = QT->getAs<FunctionType>();
2024 Changed = true;
2025 }
2026 }
2027 }
2028
2029 if (!Changed)
2030 return false;
2031
2032 assert(QualType(FromFn, 0).isCanonical());
2033 if (QualType(FromFn, 0) != CanTo) return false;
2034
2035 return true;
2036 }
2037
2038 /// Determine whether the conversion from FromType to ToType is a valid
2039 /// floating point conversion.
2040 ///
2041 static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2042 QualType ToType) {
2043 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2044 return false;
2045 // FIXME: disable conversions between long double, __ibm128 and __float128
2046 // if their representation is different until there is back end support
2047 // We of course allow this conversion if long double is really double.
2048
2049 // Conversions between bfloat16 and float16 are currently not supported.
2050 if ((FromType->isBFloat16Type() &&
2051 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2052 (ToType->isBFloat16Type() &&
2053 (FromType->isFloat16Type() || FromType->isHalfType())))
2054 return false;
2055
2056 // Conversions between IEEE-quad and IBM-extended semantics are not
2057 // permitted.
2058 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2059 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2060 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2061 &ToSem == &llvm::APFloat::IEEEquad()) ||
2062 (&FromSem == &llvm::APFloat::IEEEquad() &&
2063 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2064 return false;
2065 return true;
2066 }
2067
2068 static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2069 QualType ToType,
2070 ImplicitConversionKind &ICK,
2071 Expr *From) {
2072 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2073 return true;
2074
2075 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2076 ICK = ICK_Floating_Promotion;
2077 return true;
2078 }
2079
2080 if (IsFloatingPointConversion(S, FromType, ToType)) {
2081 ICK = ICK_Floating_Conversion;
2082 return true;
2083 }
2084
2085 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2086 ICK = ICK_Boolean_Conversion;
2087 return true;
2088 }
2089
2090 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2091 (FromType->isIntegralOrUnscopedEnumerationType() &&
2092 ToType->isRealFloatingType())) {
2093 ICK = ICK_Floating_Integral;
2094 return true;
2095 }
2096
2097 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2098 ICK = ICK_Integral_Promotion;
2099 return true;
2100 }
2101
2102 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2103 ToType->isIntegralType(S.Context)) {
2104 ICK = ICK_Integral_Conversion;
2105 return true;
2106 }
2107
2108 return false;
2109 }
2110
2111 /// Determine whether the conversion from FromType to ToType is a valid
2112 /// matrix conversion.
2113 ///
2114 /// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2115 /// conversion.
2116 static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2117 ImplicitConversionKind &ICK,
2118 ImplicitConversionKind &ElConv, Expr *From,
2119 bool InOverloadResolution, bool CStyle) {
2120 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2121 if (!S.getLangOpts().HLSL)
2122 return false;
2123
2124 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2125 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2126
2127 // If both arguments are matrix, handle possible matrix truncation and
2128 // element conversion.
2129 if (ToMatrixType && FromMatrixType) {
2130 unsigned FromCols = FromMatrixType->getNumColumns();
2131 unsigned ToCols = ToMatrixType->getNumColumns();
2132 if (FromCols < ToCols)
2133 return false;
2134
2135 unsigned FromRows = FromMatrixType->getNumRows();
2136 unsigned ToRows = ToMatrixType->getNumRows();
2137 if (FromRows < ToRows)
2138 return false;
2139
2140 if (FromRows == ToRows && FromCols == ToCols)
2141 ElConv = ICK_Identity;
2142 else
2143 ElConv = ICK_HLSL_Matrix_Truncation;
2144
2145 QualType FromElTy = FromMatrixType->getElementType();
2146 QualType ToElTy = ToMatrixType->getElementType();
2147 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2148 return true;
2149 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2150 }
2151
2152 // Matrix splat from any arithmetic type to a matrix.
2153 if (ToMatrixType && FromType->isArithmeticType()) {
2154 ElConv = ICK_HLSL_Matrix_Splat;
2155 QualType ToElTy = ToMatrixType->getElementType();
2156 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2157 ICK = ICK_HLSL_Matrix_Splat;
2158 return true;
2159 }
2160 if (FromMatrixType && !ToMatrixType) {
2161 ElConv = ICK_HLSL_Matrix_Truncation;
2162 QualType FromElTy = FromMatrixType->getElementType();
2163 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2164 return true;
2165 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2166 }
2167
2168 return false;
2169 }
2170
2171 /// Determine whether the conversion from FromType to ToType is a valid
2172 /// vector conversion.
2173 ///
2174 /// \param ICK Will be set to the vector conversion kind, if this is a vector
2175 /// conversion.
2176 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2177 ImplicitConversionKind &ICK,
2178 ImplicitConversionKind &ElConv, Expr *From,
2179 bool InOverloadResolution, bool CStyle) {
2180 // We need at least one of these types to be a vector type to have a vector
2181 // conversion.
2182 if (!ToType->isVectorType() && !FromType->isVectorType())
2183 return false;
2184
2185 // Identical types require no conversions.
2186 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2187 return false;
2188
2189 // HLSL allows implicit truncation of vector types.
2190 if (S.getLangOpts().HLSL) {
2191 auto *ToExtType = ToType->getAs<ExtVectorType>();
2192 auto *FromExtType = FromType->getAs<ExtVectorType>();
2193
2194 // If both arguments are vectors, handle possible vector truncation and
2195 // element conversion.
2196 if (ToExtType && FromExtType) {
2197 unsigned FromElts = FromExtType->getNumElements();
2198 unsigned ToElts = ToExtType->getNumElements();
2199 if (FromElts < ToElts)
2200 return false;
2201 if (FromElts == ToElts)
2202 ElConv = ICK_Identity;
2203 else
2204 ElConv = ICK_HLSL_Vector_Truncation;
2205
2206 QualType FromElTy = FromExtType->getElementType();
2207 QualType ToElTy = ToExtType->getElementType();
2208 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2209 return true;
2210 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2211 }
2212 if (FromExtType && !ToExtType) {
2213 ElConv = ICK_HLSL_Vector_Truncation;
2214 QualType FromElTy = FromExtType->getElementType();
2215 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2216 return true;
2217 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2218 }
2219 // Fallthrough for the case where ToType is a vector and FromType is not.
2220 }
2221
2222 // There are no conversions between extended vector types, only identity.
2223 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2224 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2225 // Implicit conversions require the same number of elements.
2226 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2227 return false;
2228
2229 // Permit implicit conversions from integral values to boolean vectors.
2230 if (ToType->isExtVectorBoolType() &&
2231 FromExtType->getElementType()->isIntegerType()) {
2232 ICK = ICK_Boolean_Conversion;
2233 return true;
2234 }
2235 // There are no other conversions between extended vector types.
2236 return false;
2237 }
2238
2239 // Vector splat from any arithmetic type to a vector.
2240 if (FromType->isArithmeticType()) {
2241 if (S.getLangOpts().HLSL) {
2242 ElConv = ICK_HLSL_Vector_Splat;
2243 QualType ToElTy = ToExtType->getElementType();
2244 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2245 From);
2246 }
2247 ICK = ICK_Vector_Splat;
2248 return true;
2249 }
2250 }
2251
2252 if (ToType->isSVESizelessBuiltinType() ||
2253 FromType->isSVESizelessBuiltinType())
2254 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2255 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2256 ICK = ICK_SVE_Vector_Conversion;
2257 return true;
2258 }
2259
2260 if (ToType->isRVVSizelessBuiltinType() ||
2261 FromType->isRVVSizelessBuiltinType())
2262 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2263 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2264 ICK = ICK_RVV_Vector_Conversion;
2265 return true;
2266 }
2267
2268 // We can perform the conversion between vector types in the following cases:
2269 // 1)vector types are equivalent AltiVec and GCC vector types
2270 // 2)lax vector conversions are permitted and the vector types are of the
2271 // same size
2272 // 3)the destination type does not have the ARM MVE strict-polymorphism
2273 // attribute, which inhibits lax vector conversion for overload resolution
2274 // only
2275 if (ToType->isVectorType() && FromType->isVectorType()) {
2276 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2277 (S.isLaxVectorConversion(FromType, ToType) &&
2278 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2279 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2280 S.isLaxVectorConversion(FromType, ToType) &&
2281 S.anyAltivecTypes(FromType, ToType) &&
2282 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2283 !InOverloadResolution && !CStyle) {
2284 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2285 << FromType << ToType;
2286 }
2287 ICK = ICK_Vector_Conversion;
2288 return true;
2289 }
2290 }
2291
2292 return false;
2293 }
2294
2295 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2296 bool InOverloadResolution,
2297 StandardConversionSequence &SCS,
2298 bool CStyle);
2299
2300 /// IsStandardConversion - Determines whether there is a standard
2301 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2302 /// expression From to the type ToType. Standard conversion sequences
2303 /// only consider non-class types; for conversions that involve class
2304 /// types, use TryImplicitConversion. If a conversion exists, SCS will
2305 /// contain the standard conversion sequence required to perform this
2306 /// conversion and this routine will return true. Otherwise, this
2307 /// routine will return false and the value of SCS is unspecified.
2308 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2309 bool InOverloadResolution,
2310 StandardConversionSequence &SCS,
2311 bool CStyle,
2312 bool AllowObjCWritebackConversion) {
2313 QualType FromType = From->getType();
2314
2315 // Standard conversions (C++ [conv])
2316 SCS.setAsIdentityConversion();
2317 SCS.IncompatibleObjC = false;
2318 SCS.setFromType(FromType);
2319 SCS.CopyConstructor = nullptr;
2320
2321 // There are no standard conversions for class types in C++, so
2322 // abort early. When overloading in C, however, we do permit them.
2323 if (S.getLangOpts().CPlusPlus &&
2324 (FromType->isRecordType() || ToType->isRecordType()))
2325 return false;
2326
2327 // The first conversion can be an lvalue-to-rvalue conversion,
2328 // array-to-pointer conversion, or function-to-pointer conversion
2329 // (C++ 4p1).
2330
2331 if (FromType == S.Context.OverloadTy) {
2332 DeclAccessPair AccessPair;
2333 if (FunctionDecl *Fn
2334 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2335 AccessPair)) {
2336 // We were able to resolve the address of the overloaded function,
2337 // so we can convert to the type of that function.
2338 FromType = Fn->getType();
2339 SCS.setFromType(FromType);
2340
2341 // we can sometimes resolve &foo<int> regardless of ToType, so check
2342 // if the type matches (identity) or we are converting to bool
2343 if (!S.Context.hasSameUnqualifiedType(
2344 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2345 // if the function type matches except for [[noreturn]], it's ok
2346 if (!S.IsFunctionConversion(FromType,
2347 S.ExtractUnqualifiedFunctionType(ToType)))
2348 // otherwise, only a boolean conversion is standard
2349 if (!ToType->isBooleanType())
2350 return false;
2351 }
2352
2353 // Check if the "from" expression is taking the address of an overloaded
2354 // function and recompute the FromType accordingly. Take advantage of the
2355 // fact that non-static member functions *must* have such an address-of
2356 // expression.
2357 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2358 if (Method && !Method->isStatic() &&
2359 !Method->isExplicitObjectMemberFunction()) {
2360 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2361 "Non-unary operator on non-static member address");
2362 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2363 == UO_AddrOf &&
2364 "Non-address-of operator on non-static member address");
2365 FromType = S.Context.getMemberPointerType(
2366 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2367 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2368 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2369 UO_AddrOf &&
2370 "Non-address-of operator for overloaded function expression");
2371 FromType = S.Context.getPointerType(FromType);
2372 }
2373 } else {
2374 return false;
2375 }
2376 }
2377
2378 bool argIsLValue = From->isGLValue();
2379 // To handle conversion from ArrayParameterType to ConstantArrayType
2380 // this block must be above the one below because Array parameters
2381 // do not decay and when handling HLSLOutArgExprs and
2382 // the From expression is an LValue.
2383 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2384 ToType->isConstantArrayType()) {
2385 // HLSL constant array parameters do not decay, so if the argument is a
2386 // constant array and the parameter is an ArrayParameterType we have special
2387 // handling here.
2388 if (ToType->isArrayParameterType()) {
2389 FromType = S.Context.getArrayParameterType(FromType);
2390 } else if (FromType->isArrayParameterType()) {
2391 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2392 FromType = APT->getConstantArrayType(S.Context);
2393 }
2394
2395 SCS.First = ICK_HLSL_Array_RValue;
2396
2397 // Don't consider qualifiers, which include things like address spaces
2398 if (FromType.getCanonicalType().getUnqualifiedType() !=
2399 ToType.getCanonicalType().getUnqualifiedType())
2400 return false;
2401
2402 SCS.setAllToTypes(ToType);
2403 return true;
2404 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2405 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2406 // Lvalue-to-rvalue conversion (C++11 4.1):
2407 // A glvalue (3.10) of a non-function, non-array type T can
2408 // be converted to a prvalue.
2409
2410 SCS.First = ICK_Lvalue_To_Rvalue;
2411
2412 // C11 6.3.2.1p2:
2413 // ... if the lvalue has atomic type, the value has the non-atomic version
2414 // of the type of the lvalue ...
2415 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2416 FromType = Atomic->getValueType();
2417
2418 // If T is a non-class type, the type of the rvalue is the
2419 // cv-unqualified version of T. Otherwise, the type of the rvalue
2420 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2421 // just strip the qualifiers because they don't matter.
2422 FromType = FromType.getUnqualifiedType();
2423 } else if (FromType->isArrayType()) {
2424 // Array-to-pointer conversion (C++ 4.2)
2425 SCS.First = ICK_Array_To_Pointer;
2426
2427 // An lvalue or rvalue of type "array of N T" or "array of unknown
2428 // bound of T" can be converted to an rvalue of type "pointer to
2429 // T" (C++ 4.2p1).
2430 FromType = S.Context.getArrayDecayedType(FromType);
2431
2432 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2433 // This conversion is deprecated in C++03 (D.4)
2434 SCS.DeprecatedStringLiteralToCharPtr = true;
2435
2436 // For the purpose of ranking in overload resolution
2437 // (13.3.3.1.1), this conversion is considered an
2438 // array-to-pointer conversion followed by a qualification
2439 // conversion (4.4). (C++ 4.2p2)
2440 SCS.Second = ICK_Identity;
2441 SCS.Third = ICK_Qualification;
2442 SCS.QualificationIncludesObjCLifetime = false;
2443 SCS.setAllToTypes(FromType);
2444 return true;
2445 }
2446 } else if (FromType->isFunctionType() && argIsLValue) {
2447 // Function-to-pointer conversion (C++ 4.3).
2448 SCS.First = ICK_Function_To_Pointer;
2449
2450 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2451 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2452 if (!S.checkAddressOfFunctionIsAvailable(FD))
2453 return false;
2454
2455 // An lvalue of function type T can be converted to an rvalue of
2456 // type "pointer to T." The result is a pointer to the
2457 // function. (C++ 4.3p1).
2458 FromType = S.Context.getPointerType(FromType);
2459 } else {
2460 // We don't require any conversions for the first step.
2461 SCS.First = ICK_Identity;
2462 }
2463 SCS.setToType(0, FromType);
2464
2465 // The second conversion can be an integral promotion, floating
2466 // point promotion, integral conversion, floating point conversion,
2467 // floating-integral conversion, pointer conversion,
2468 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2469 // For overloading in C, this can also be a "compatible-type"
2470 // conversion.
2471 bool IncompatibleObjC = false;
2472 ImplicitConversionKind SecondICK = ICK_Identity;
2473 ImplicitConversionKind DimensionICK = ICK_Identity;
2474 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2475 // The unqualified versions of the types are the same: there's no
2476 // conversion to do.
2477 SCS.Second = ICK_Identity;
2478 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2479 // Integral promotion (C++ 4.5).
2480 SCS.Second = ICK_Integral_Promotion;
2481 FromType = ToType.getUnqualifiedType();
2482 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2483 // Floating point promotion (C++ 4.6).
2484 SCS.Second = ICK_Floating_Promotion;
2485 FromType = ToType.getUnqualifiedType();
2486 } else if (S.IsComplexPromotion(FromType, ToType)) {
2487 // Complex promotion (Clang extension)
2488 SCS.Second = ICK_Complex_Promotion;
2489 FromType = ToType.getUnqualifiedType();
2490 } else if (ToType->isBooleanType() &&
2491 (FromType->isArithmeticType() ||
2492 FromType->isAnyPointerType() ||
2493 FromType->isBlockPointerType() ||
2494 FromType->isMemberPointerType())) {
2495 // Boolean conversions (C++ 4.12).
2496 SCS.Second = ICK_Boolean_Conversion;
2497 FromType = S.Context.BoolTy;
2498 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2499 ToType->isIntegralType(S.Context)) {
2500 // Integral conversions (C++ 4.7).
2501 SCS.Second = ICK_Integral_Conversion;
2502 FromType = ToType.getUnqualifiedType();
2503 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2504 // Complex conversions (C99 6.3.1.6)
2505 SCS.Second = ICK_Complex_Conversion;
2506 FromType = ToType.getUnqualifiedType();
2507 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2508 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2509 // Complex-real conversions (C99 6.3.1.7)
2510 SCS.Second = ICK_Complex_Real;
2511 FromType = ToType.getUnqualifiedType();
2512 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2513 // Floating point conversions (C++ 4.8).
2514 SCS.Second = ICK_Floating_Conversion;
2515 FromType = ToType.getUnqualifiedType();
2516 } else if ((FromType->isRealFloatingType() &&
2517 ToType->isIntegralType(S.Context)) ||
2518 (FromType->isIntegralOrUnscopedEnumerationType() &&
2519 ToType->isRealFloatingType())) {
2520
2521 // Floating-integral conversions (C++ 4.9).
2522 SCS.Second = ICK_Floating_Integral;
2523 FromType = ToType.getUnqualifiedType();
2524 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2525 SCS.Second = ICK_Block_Pointer_Conversion;
2526 } else if (AllowObjCWritebackConversion &&
2527 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2528 SCS.Second = ICK_Writeback_Conversion;
2529 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2530 FromType, IncompatibleObjC)) {
2531 // Pointer conversions (C++ 4.10).
2532 SCS.Second = ICK_Pointer_Conversion;
2533 SCS.IncompatibleObjC = IncompatibleObjC;
2534 FromType = FromType.getUnqualifiedType();
2535 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2536 InOverloadResolution, FromType)) {
2537 // Pointer to member conversions (4.11).
2538 SCS.Second = ICK_Pointer_Member;
2539 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2540 From, InOverloadResolution, CStyle)) {
2541 SCS.Second = SecondICK;
2542 SCS.Dimension = DimensionICK;
2543 FromType = ToType.getUnqualifiedType();
2544 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2545 From, InOverloadResolution, CStyle)) {
2546 SCS.Second = SecondICK;
2547 SCS.Dimension = DimensionICK;
2548 FromType = ToType.getUnqualifiedType();
2549 } else if (!S.getLangOpts().CPlusPlus &&
2550 S.Context.typesAreCompatible(ToType, FromType)) {
2551 // Compatible conversions (Clang extension for C function overloading)
2552 SCS.Second = ICK_Compatible_Conversion;
2553 FromType = ToType.getUnqualifiedType();
2554 } else if (IsTransparentUnionStandardConversion(
2555 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2556 SCS.Second = ICK_TransparentUnionConversion;
2557 FromType = ToType;
2558 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2559 CStyle)) {
2560 // tryAtomicConversion has updated the standard conversion sequence
2561 // appropriately.
2562 return true;
2563 } else if (ToType->isEventT() &&
2564 From->isIntegerConstantExpr(S.getASTContext()) &&
2565 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2566 SCS.Second = ICK_Zero_Event_Conversion;
2567 FromType = ToType;
2568 } else if (ToType->isQueueT() &&
2569 From->isIntegerConstantExpr(S.getASTContext()) &&
2570 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2571 SCS.Second = ICK_Zero_Queue_Conversion;
2572 FromType = ToType;
2573 } else if (ToType->isSamplerT() &&
2574 From->isIntegerConstantExpr(S.getASTContext())) {
2575 SCS.Second = ICK_Compatible_Conversion;
2576 FromType = ToType;
2577 } else if ((ToType->isFixedPointType() &&
2578 FromType->isConvertibleToFixedPointType()) ||
2579 (FromType->isFixedPointType() &&
2580 ToType->isConvertibleToFixedPointType())) {
2581 SCS.Second = ICK_Fixed_Point_Conversion;
2582 FromType = ToType;
2583 } else {
2584 // No second conversion required.
2585 SCS.Second = ICK_Identity;
2586 }
2587 SCS.setToType(1, FromType);
2588
2589 // The third conversion can be a function pointer conversion or a
2590 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2591 bool ObjCLifetimeConversion;
2592 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2593 // Function pointer conversions (removing 'noexcept') including removal of
2594 // 'noreturn' (Clang extension).
2595 SCS.Third = ICK_Function_Conversion;
2596 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2597 ObjCLifetimeConversion)) {
2598 SCS.Third = ICK_Qualification;
2599 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2600 FromType = ToType;
2601 } else {
2602 // No conversion required
2603 SCS.Third = ICK_Identity;
2604 }
2605
2606 // C++ [over.best.ics]p6:
2607 // [...] Any difference in top-level cv-qualification is
2608 // subsumed by the initialization itself and does not constitute
2609 // a conversion. [...]
2610 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2611 QualType CanonTo = S.Context.getCanonicalType(ToType);
2612 if (CanonFrom.getLocalUnqualifiedType()
2613 == CanonTo.getLocalUnqualifiedType() &&
2614 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2615 FromType = ToType;
2616 CanonFrom = CanonTo;
2617 }
2618
2619 SCS.setToType(2, FromType);
2620
2621 if (CanonFrom == CanonTo)
2622 return true;
2623
2624 // If we have not converted the argument type to the parameter type,
2625 // this is a bad conversion sequence, unless we're resolving an overload in C.
2626 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2627 return false;
2628
2629 ExprResult ER = ExprResult{From};
2630 AssignConvertType Conv =
2631 S.CheckSingleAssignmentConstraints(ToType, ER,
2632 /*Diagnose=*/false,
2633 /*DiagnoseCFAudited=*/false,
2634 /*ConvertRHS=*/false);
2635 ImplicitConversionKind SecondConv;
2636 switch (Conv) {
2637 case AssignConvertType::Compatible:
2638 case AssignConvertType::
2639 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2640 SecondConv = ICK_C_Only_Conversion;
2641 break;
2642 // For our purposes, discarding qualifiers is just as bad as using an
2643 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2644 // qualifiers, as well.
2645 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2646 case AssignConvertType::IncompatiblePointer:
2647 case AssignConvertType::IncompatiblePointerSign:
2648 SecondConv = ICK_Incompatible_Pointer_Conversion;
2649 break;
2650 default:
2651 return false;
2652 }
2653
2654 // First can only be an lvalue conversion, so we pretend that this was the
2655 // second conversion. First should already be valid from earlier in the
2656 // function.
2657 SCS.Second = SecondConv;
2658 SCS.setToType(1, ToType);
2659
2660 // Third is Identity, because Second should rank us worse than any other
2661 // conversion. This could also be ICK_Qualification, but it's simpler to just
2662 // lump everything in with the second conversion, and we don't gain anything
2663 // from making this ICK_Qualification.
2664 SCS.Third = ICK_Identity;
2665 SCS.setToType(2, ToType);
2666 return true;
2667 }
2668
2669 static bool
2670 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2671 QualType &ToType,
2672 bool InOverloadResolution,
2673 StandardConversionSequence &SCS,
2674 bool CStyle) {
2675
2676 const RecordType *UT = ToType->getAsUnionType();
2677 if (!UT)
2678 return false;
2679 // The field to initialize within the transparent union.
2680 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2681 if (!UD->hasAttr<TransparentUnionAttr>())
2682 return false;
2683 // It's compatible if the expression matches any of the fields.
2684 for (const auto *it : UD->fields()) {
2685 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2686 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2687 ToType = it->getType();
2688 return true;
2689 }
2690 }
2691 return false;
2692 }
2693
2694 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2695 const BuiltinType *To = ToType->getAs<BuiltinType>();
2696 // All integers are built-in.
2697 if (!To) {
2698 return false;
2699 }
2700
2701 // An rvalue of type char, signed char, unsigned char, short int, or
2702 // unsigned short int can be converted to an rvalue of type int if
2703 // int can represent all the values of the source type; otherwise,
2704 // the source rvalue can be converted to an rvalue of type unsigned
2705 // int (C++ 4.5p1).
2706 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2707 !FromType->isEnumeralType()) {
2708 if ( // We can promote any signed, promotable integer type to an int
2709 (FromType->isSignedIntegerType() ||
2710 // We can promote any unsigned integer type whose size is
2711 // less than int to an int.
2712 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2713 return To->getKind() == BuiltinType::Int;
2714 }
2715
2716 return To->getKind() == BuiltinType::UInt;
2717 }
2718
2719 // C++11 [conv.prom]p3:
2720 // A prvalue of an unscoped enumeration type whose underlying type is not
2721 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2722 // following types that can represent all the values of the enumeration
2723 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2724 // unsigned int, long int, unsigned long int, long long int, or unsigned
2725 // long long int. If none of the types in that list can represent all the
2726 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2727 // type can be converted to an rvalue a prvalue of the extended integer type
2728 // with lowest integer conversion rank (4.13) greater than the rank of long
2729 // long in which all the values of the enumeration can be represented. If
2730 // there are two such extended types, the signed one is chosen.
2731 // C++11 [conv.prom]p4:
2732 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2733 // can be converted to a prvalue of its underlying type. Moreover, if
2734 // integral promotion can be applied to its underlying type, a prvalue of an
2735 // unscoped enumeration type whose underlying type is fixed can also be
2736 // converted to a prvalue of the promoted underlying type.
2737 if (const auto *FromED = FromType->getAsEnumDecl()) {
2738 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2739 // provided for a scoped enumeration.
2740 if (FromED->isScoped())
2741 return false;
2742
2743 // We can perform an integral promotion to the underlying type of the enum,
2744 // even if that's not the promoted type. Note that the check for promoting
2745 // the underlying type is based on the type alone, and does not consider
2746 // the bitfield-ness of the actual source expression.
2747 if (FromED->isFixed()) {
2748 QualType Underlying = FromED->getIntegerType();
2749 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2750 IsIntegralPromotion(nullptr, Underlying, ToType);
2751 }
2752
2753 // We have already pre-calculated the promotion type, so this is trivial.
2754 if (ToType->isIntegerType() &&
2755 isCompleteType(From->getBeginLoc(), FromType))
2756 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2757
2758 // C++ [conv.prom]p5:
2759 // If the bit-field has an enumerated type, it is treated as any other
2760 // value of that type for promotion purposes.
2761 //
2762 // ... so do not fall through into the bit-field checks below in C++.
2763 if (getLangOpts().CPlusPlus)
2764 return false;
2765 }
2766
2767 // C++0x [conv.prom]p2:
2768 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2769 // to an rvalue a prvalue of the first of the following types that can
2770 // represent all the values of its underlying type: int, unsigned int,
2771 // long int, unsigned long int, long long int, or unsigned long long int.
2772 // If none of the types in that list can represent all the values of its
2773 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2774 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2775 // type.
2776 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2777 ToType->isIntegerType()) {
2778 // Determine whether the type we're converting from is signed or
2779 // unsigned.
2780 bool FromIsSigned = FromType->isSignedIntegerType();
2781 uint64_t FromSize = Context.getTypeSize(FromType);
2782
2783 // The types we'll try to promote to, in the appropriate
2784 // order. Try each of these types.
2785 QualType PromoteTypes[6] = {
2786 Context.IntTy, Context.UnsignedIntTy,
2787 Context.LongTy, Context.UnsignedLongTy ,
2788 Context.LongLongTy, Context.UnsignedLongLongTy
2789 };
2790 for (int Idx = 0; Idx < 6; ++Idx) {
2791 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2792 if (FromSize < ToSize ||
2793 (FromSize == ToSize &&
2794 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2795 // We found the type that we can promote to. If this is the
2796 // type we wanted, we have a promotion. Otherwise, no
2797 // promotion.
2798 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2799 }
2800 }
2801 }
2802
2803 // An rvalue for an integral bit-field (9.6) can be converted to an
2804 // rvalue of type int if int can represent all the values of the
2805 // bit-field; otherwise, it can be converted to unsigned int if
2806 // unsigned int can represent all the values of the bit-field. If
2807 // the bit-field is larger yet, no integral promotion applies to
2808 // it. If the bit-field has an enumerated type, it is treated as any
2809 // other value of that type for promotion purposes (C++ 4.5p3).
2810 // FIXME: We should delay checking of bit-fields until we actually perform the
2811 // conversion.
2812 //
2813 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2814 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2815 // bit-fields and those whose underlying type is larger than int) for GCC
2816 // compatibility.
2817 if (From) {
2818 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2819 std::optional<llvm::APSInt> BitWidth;
2820 if (FromType->isIntegralType(Context) &&
2821 (BitWidth =
2822 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2823 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2824 ToSize = Context.getTypeSize(ToType);
2825
2826 // Are we promoting to an int from a bitfield that fits in an int?
2827 if (*BitWidth < ToSize ||
2828 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2829 return To->getKind() == BuiltinType::Int;
2830 }
2831
2832 // Are we promoting to an unsigned int from an unsigned bitfield
2833 // that fits into an unsigned int?
2834 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2835 return To->getKind() == BuiltinType::UInt;
2836 }
2837
2838 return false;
2839 }
2840 }
2841 }
2842
2843 // An rvalue of type bool can be converted to an rvalue of type int,
2844 // with false becoming zero and true becoming one (C++ 4.5p4).
2845 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2846 return true;
2847 }
2848
2849 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2850 // integral type.
2851 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2852 ToType->isIntegerType())
2853 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2854
2855 return false;
2856 }
2857
2858 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2859 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2860 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2861 /// An rvalue of type float can be converted to an rvalue of type
2862 /// double. (C++ 4.6p1).
2863 if (FromBuiltin->getKind() == BuiltinType::Float &&
2864 ToBuiltin->getKind() == BuiltinType::Double)
2865 return true;
2866
2867 // C99 6.3.1.5p1:
2868 // When a float is promoted to double or long double, or a
2869 // double is promoted to long double [...].
2870 if (!getLangOpts().CPlusPlus &&
2871 (FromBuiltin->getKind() == BuiltinType::Float ||
2872 FromBuiltin->getKind() == BuiltinType::Double) &&
2873 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2874 ToBuiltin->getKind() == BuiltinType::Float128 ||
2875 ToBuiltin->getKind() == BuiltinType::Ibm128))
2876 return true;
2877
2878 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2879 // or not native half types are enabled.
2880 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2881 (ToBuiltin->getKind() == BuiltinType::Float ||
2882 ToBuiltin->getKind() == BuiltinType::Double))
2883 return true;
2884
2885 // Half can be promoted to float.
2886 if (!getLangOpts().NativeHalfType &&
2887 FromBuiltin->getKind() == BuiltinType::Half &&
2888 ToBuiltin->getKind() == BuiltinType::Float)
2889 return true;
2890 }
2891
2892 return false;
2893 }
2894
2895 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2896 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2897 if (!FromComplex)
2898 return false;
2899
2900 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2901 if (!ToComplex)
2902 return false;
2903
2904 return IsFloatingPointPromotion(FromComplex->getElementType(),
2905 ToComplex->getElementType()) ||
2906 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2907 ToComplex->getElementType());
2908 }
2909
2910 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2911 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2912 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2913 /// if non-empty, will be a pointer to ToType that may or may not have
2914 /// the right set of qualifiers on its pointee.
2915 ///
2916 static QualType
2917 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2918 QualType ToPointee, QualType ToType,
2919 ASTContext &Context,
2920 bool StripObjCLifetime = false) {
2921 assert((FromPtr->getTypeClass() == Type::Pointer ||
2922 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2923 "Invalid similarly-qualified pointer type");
2924
2925 /// Conversions to 'id' subsume cv-qualifier conversions.
2926 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2927 return ToType.getUnqualifiedType();
2928
2929 QualType CanonFromPointee
2930 = Context.getCanonicalType(FromPtr->getPointeeType());
2931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2932 Qualifiers Quals = CanonFromPointee.getQualifiers();
2933
2934 if (StripObjCLifetime)
2935 Quals.removeObjCLifetime();
2936
2937 // Exact qualifier match -> return the pointer type we're converting to.
2938 if (CanonToPointee.getLocalQualifiers() == Quals) {
2939 // ToType is exactly what we need. Return it.
2940 if (!ToType.isNull())
2941 return ToType.getUnqualifiedType();
2942
2943 // Build a pointer to ToPointee. It has the right qualifiers
2944 // already.
2945 if (isa<ObjCObjectPointerType>(ToType))
2946 return Context.getObjCObjectPointerType(ToPointee);
2947 return Context.getPointerType(ToPointee);
2948 }
2949
2950 // Just build a canonical type that has the right qualifiers.
2951 QualType QualifiedCanonToPointee
2952 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2953
2954 if (isa<ObjCObjectPointerType>(ToType))
2955 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2956 return Context.getPointerType(QualifiedCanonToPointee);
2957 }
2958
2959 static bool isNullPointerConstantForConversion(Expr *Expr,
2960 bool InOverloadResolution,
2961 ASTContext &Context) {
2962 // Handle value-dependent integral null pointer constants correctly.
2963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2964 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2965 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2966 return !InOverloadResolution;
2967
2968 return Expr->isNullPointerConstant(Context,
2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2970 : Expr::NPC_ValueDependentIsNull);
2971 }
2972
2973 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2974 bool InOverloadResolution,
2975 QualType& ConvertedType,
2976 bool &IncompatibleObjC) {
2977 IncompatibleObjC = false;
2978 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2979 IncompatibleObjC))
2980 return true;
2981
2982 // Conversion from a null pointer constant to any Objective-C pointer type.
2983 if (ToType->isObjCObjectPointerType() &&
2984 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2985 ConvertedType = ToType;
2986 return true;
2987 }
2988
2989 // Blocks: Block pointers can be converted to void*.
2990 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2991 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2992 ConvertedType = ToType;
2993 return true;
2994 }
2995 // Blocks: A null pointer constant can be converted to a block
2996 // pointer type.
2997 if (ToType->isBlockPointerType() &&
2998 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2999 ConvertedType = ToType;
3000 return true;
3001 }
3002
3003 // If the left-hand-side is nullptr_t, the right side can be a null
3004 // pointer constant.
3005 if (ToType->isNullPtrType() &&
3006 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3007 ConvertedType = ToType;
3008 return true;
3009 }
3010
3011 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3012 if (!ToTypePtr)
3013 return false;
3014
3015 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3016 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3017 ConvertedType = ToType;
3018 return true;
3019 }
3020
3021 // Beyond this point, both types need to be pointers
3022 // , including objective-c pointers.
3023 QualType ToPointeeType = ToTypePtr->getPointeeType();
3024 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3025 !getLangOpts().ObjCAutoRefCount) {
3026 ConvertedType = BuildSimilarlyQualifiedPointerType(
3027 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3028 Context);
3029 return true;
3030 }
3031 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3032 if (!FromTypePtr)
3033 return false;
3034
3035 QualType FromPointeeType = FromTypePtr->getPointeeType();
3036
3037 // If the unqualified pointee types are the same, this can't be a
3038 // pointer conversion, so don't do all of the work below.
3039 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3040 return false;
3041
3042 // An rvalue of type "pointer to cv T," where T is an object type,
3043 // can be converted to an rvalue of type "pointer to cv void" (C++
3044 // 4.10p2).
3045 if (FromPointeeType->isIncompleteOrObjectType() &&
3046 ToPointeeType->isVoidType()) {
3047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3048 ToPointeeType,
3049 ToType, Context,
3050 /*StripObjCLifetime=*/true);
3051 return true;
3052 }
3053
3054 // MSVC allows implicit function to void* type conversion.
3055 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3056 ToPointeeType->isVoidType()) {
3057 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3058 ToPointeeType,
3059 ToType, Context);
3060 return true;
3061 }
3062
3063 // When we're overloading in C, we allow a special kind of pointer
3064 // conversion for compatible-but-not-identical pointee types.
3065 if (!getLangOpts().CPlusPlus &&
3066 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3068 ToPointeeType,
3069 ToType, Context);
3070 return true;
3071 }
3072
3073 // C++ [conv.ptr]p3:
3074 //
3075 // An rvalue of type "pointer to cv D," where D is a class type,
3076 // can be converted to an rvalue of type "pointer to cv B," where
3077 // B is a base class (clause 10) of D. If B is an inaccessible
3078 // (clause 11) or ambiguous (10.2) base class of D, a program that
3079 // necessitates this conversion is ill-formed. The result of the
3080 // conversion is a pointer to the base class sub-object of the
3081 // derived class object. The null pointer value is converted to
3082 // the null pointer value of the destination type.
3083 //
3084 // Note that we do not check for ambiguity or inaccessibility
3085 // here. That is handled by CheckPointerConversion.
3086 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3087 ToPointeeType->isRecordType() &&
3088 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3089 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3091 ToPointeeType,
3092 ToType, Context);
3093 return true;
3094 }
3095
3096 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3097 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3098 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3099 ToPointeeType,
3100 ToType, Context);
3101 return true;
3102 }
3103
3104 return false;
3105 }
3106
3107 /// Adopt the given qualifiers for the given type.
3108 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3109 Qualifiers TQs = T.getQualifiers();
3110
3111 // Check whether qualifiers already match.
3112 if (TQs == Qs)
3113 return T;
3114
3115 if (Qs.compatiblyIncludes(TQs, Context))
3116 return Context.getQualifiedType(T, Qs);
3117
3118 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3119 }
3120
3121 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3122 QualType& ConvertedType,
3123 bool &IncompatibleObjC) {
3124 if (!getLangOpts().ObjC)
3125 return false;
3126
3127 // The set of qualifiers on the type we're converting from.
3128 Qualifiers FromQualifiers = FromType.getQualifiers();
3129
3130 // First, we handle all conversions on ObjC object pointer types.
3131 const ObjCObjectPointerType* ToObjCPtr =
3132 ToType->getAs<ObjCObjectPointerType>();
3133 const ObjCObjectPointerType *FromObjCPtr =
3134 FromType->getAs<ObjCObjectPointerType>();
3135
3136 if (ToObjCPtr && FromObjCPtr) {
3137 // If the pointee types are the same (ignoring qualifications),
3138 // then this is not a pointer conversion.
3139 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3140 FromObjCPtr->getPointeeType()))
3141 return false;
3142
3143 // Conversion between Objective-C pointers.
3144 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3145 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3146 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3147 if (getLangOpts().CPlusPlus && LHS && RHS &&
3148 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3149 FromObjCPtr->getPointeeType(), getASTContext()))
3150 return false;
3151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3152 ToObjCPtr->getPointeeType(),
3153 ToType, Context);
3154 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3155 return true;
3156 }
3157
3158 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3159 // Okay: this is some kind of implicit downcast of Objective-C
3160 // interfaces, which is permitted. However, we're going to
3161 // complain about it.
3162 IncompatibleObjC = true;
3163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3164 ToObjCPtr->getPointeeType(),
3165 ToType, Context);
3166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3167 return true;
3168 }
3169 }
3170 // Beyond this point, both types need to be C pointers or block pointers.
3171 QualType ToPointeeType;
3172 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3173 ToPointeeType = ToCPtr->getPointeeType();
3174 else if (const BlockPointerType *ToBlockPtr =
3175 ToType->getAs<BlockPointerType>()) {
3176 // Objective C++: We're able to convert from a pointer to any object
3177 // to a block pointer type.
3178 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3180 return true;
3181 }
3182 ToPointeeType = ToBlockPtr->getPointeeType();
3183 }
3184 else if (FromType->getAs<BlockPointerType>() &&
3185 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3186 // Objective C++: We're able to convert from a block pointer type to a
3187 // pointer to any object.
3188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3189 return true;
3190 }
3191 else
3192 return false;
3193
3194 QualType FromPointeeType;
3195 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3196 FromPointeeType = FromCPtr->getPointeeType();
3197 else if (const BlockPointerType *FromBlockPtr =
3198 FromType->getAs<BlockPointerType>())
3199 FromPointeeType = FromBlockPtr->getPointeeType();
3200 else
3201 return false;
3202
3203 // If we have pointers to pointers, recursively check whether this
3204 // is an Objective-C conversion.
3205 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3206 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3207 IncompatibleObjC)) {
3208 // We always complain about this conversion.
3209 IncompatibleObjC = true;
3210 ConvertedType = Context.getPointerType(ConvertedType);
3211 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3212 return true;
3213 }
3214 // Allow conversion of pointee being objective-c pointer to another one;
3215 // as in I* to id.
3216 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3217 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3219 IncompatibleObjC)) {
3220
3221 ConvertedType = Context.getPointerType(ConvertedType);
3222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3223 return true;
3224 }
3225
3226 // If we have pointers to functions or blocks, check whether the only
3227 // differences in the argument and result types are in Objective-C
3228 // pointer conversions. If so, we permit the conversion (but
3229 // complain about it).
3230 const FunctionProtoType *FromFunctionType
3231 = FromPointeeType->getAs<FunctionProtoType>();
3232 const FunctionProtoType *ToFunctionType
3233 = ToPointeeType->getAs<FunctionProtoType>();
3234 if (FromFunctionType && ToFunctionType) {
3235 // If the function types are exactly the same, this isn't an
3236 // Objective-C pointer conversion.
3237 if (Context.getCanonicalType(FromPointeeType)
3238 == Context.getCanonicalType(ToPointeeType))
3239 return false;
3240
3241 // Perform the quick checks that will tell us whether these
3242 // function types are obviously different.
3243 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3244 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3245 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3246 return false;
3247
3248 bool HasObjCConversion = false;
3249 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3250 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3251 // Okay, the types match exactly. Nothing to do.
3252 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3253 ToFunctionType->getReturnType(),
3254 ConvertedType, IncompatibleObjC)) {
3255 // Okay, we have an Objective-C pointer conversion.
3256 HasObjCConversion = true;
3257 } else {
3258 // Function types are too different. Abort.
3259 return false;
3260 }
3261
3262 // Check argument types.
3263 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3264 ArgIdx != NumArgs; ++ArgIdx) {
3265 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3266 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3267 if (Context.getCanonicalType(FromArgType)
3268 == Context.getCanonicalType(ToArgType)) {
3269 // Okay, the types match exactly. Nothing to do.
3270 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3271 ConvertedType, IncompatibleObjC)) {
3272 // Okay, we have an Objective-C pointer conversion.
3273 HasObjCConversion = true;
3274 } else {
3275 // Argument types are too different. Abort.
3276 return false;
3277 }
3278 }
3279
3280 if (HasObjCConversion) {
3281 // We had an Objective-C conversion. Allow this pointer
3282 // conversion, but complain about it.
3283 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3284 IncompatibleObjC = true;
3285 return true;
3286 }
3287 }
3288
3289 return false;
3290 }
3291
3292 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3293 QualType& ConvertedType) {
3294 QualType ToPointeeType;
3295 if (const BlockPointerType *ToBlockPtr =
3296 ToType->getAs<BlockPointerType>())
3297 ToPointeeType = ToBlockPtr->getPointeeType();
3298 else
3299 return false;
3300
3301 QualType FromPointeeType;
3302 if (const BlockPointerType *FromBlockPtr =
3303 FromType->getAs<BlockPointerType>())
3304 FromPointeeType = FromBlockPtr->getPointeeType();
3305 else
3306 return false;
3307 // We have pointer to blocks, check whether the only
3308 // differences in the argument and result types are in Objective-C
3309 // pointer conversions. If so, we permit the conversion.
3310
3311 const FunctionProtoType *FromFunctionType
3312 = FromPointeeType->getAs<FunctionProtoType>();
3313 const FunctionProtoType *ToFunctionType
3314 = ToPointeeType->getAs<FunctionProtoType>();
3315
3316 if (!FromFunctionType || !ToFunctionType)
3317 return false;
3318
3319 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3320 return true;
3321
3322 // Perform the quick checks that will tell us whether these
3323 // function types are obviously different.
3324 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3325 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3326 return false;
3327
3328 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3329 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3330 if (FromEInfo != ToEInfo)
3331 return false;
3332
3333 bool IncompatibleObjC = false;
3334 if (Context.hasSameType(FromFunctionType->getReturnType(),
3335 ToFunctionType->getReturnType())) {
3336 // Okay, the types match exactly. Nothing to do.
3337 } else {
3338 QualType RHS = FromFunctionType->getReturnType();
3339 QualType LHS = ToFunctionType->getReturnType();
3340 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3341 !RHS.hasQualifiers() && LHS.hasQualifiers())
3342 LHS = LHS.getUnqualifiedType();
3343
3344 if (Context.hasSameType(RHS,LHS)) {
3345 // OK exact match.
3346 } else if (isObjCPointerConversion(RHS, LHS,
3347 ConvertedType, IncompatibleObjC)) {
3348 if (IncompatibleObjC)
3349 return false;
3350 // Okay, we have an Objective-C pointer conversion.
3351 }
3352 else
3353 return false;
3354 }
3355
3356 // Check argument types.
3357 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3358 ArgIdx != NumArgs; ++ArgIdx) {
3359 IncompatibleObjC = false;
3360 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3361 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3362 if (Context.hasSameType(FromArgType, ToArgType)) {
3363 // Okay, the types match exactly. Nothing to do.
3364 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3365 ConvertedType, IncompatibleObjC)) {
3366 if (IncompatibleObjC)
3367 return false;
3368 // Okay, we have an Objective-C pointer conversion.
3369 } else
3370 // Argument types are too different. Abort.
3371 return false;
3372 }
3373
3374 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3375 bool CanUseToFPT, CanUseFromFPT;
3376 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3377 CanUseToFPT, CanUseFromFPT,
3378 NewParamInfos))
3379 return false;
3380
3381 ConvertedType = ToType;
3382 return true;
3383 }
3384
3385 enum {
3386 ft_default,
3387 ft_different_class,
3388 ft_parameter_arity,
3389 ft_parameter_mismatch,
3390 ft_return_type,
3391 ft_qualifer_mismatch,
3392 ft_noexcept
3393 };
3394
3395 /// Attempts to get the FunctionProtoType from a Type. Handles
3396 /// MemberFunctionPointers properly.
3397 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3398 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3399 return FPT;
3400
3401 if (auto *MPT = FromType->getAs<MemberPointerType>())
3402 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3403
3404 return nullptr;
3405 }
3406
3407 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3408 QualType FromType, QualType ToType) {
3409 // If either type is not valid, include no extra info.
3410 if (FromType.isNull() || ToType.isNull()) {
3411 PDiag << ft_default;
3412 return;
3413 }
3414
3415 // Get the function type from the pointers.
3416 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3417 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3418 *ToMember = ToType->castAs<MemberPointerType>();
3419 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3420 ToMember->getMostRecentCXXRecordDecl())) {
3421 PDiag << ft_different_class;
3422 if (ToMember->isSugared())
3423 PDiag << Context.getCanonicalTagType(
3424 ToMember->getMostRecentCXXRecordDecl());
3425 else
3426 PDiag << ToMember->getQualifier();
3427 if (FromMember->isSugared())
3428 PDiag << Context.getCanonicalTagType(
3429 FromMember->getMostRecentCXXRecordDecl());
3430 else
3431 PDiag << FromMember->getQualifier();
3432 return;
3433 }
3434 FromType = FromMember->getPointeeType();
3435 ToType = ToMember->getPointeeType();
3436 }
3437
3438 if (FromType->isPointerType())
3439 FromType = FromType->getPointeeType();
3440 if (ToType->isPointerType())
3441 ToType = ToType->getPointeeType();
3442
3443 // Remove references.
3444 FromType = FromType.getNonReferenceType();
3445 ToType = ToType.getNonReferenceType();
3446
3447 // Don't print extra info for non-specialized template functions.
3448 if (FromType->isInstantiationDependentType() &&
3449 !FromType->getAs<TemplateSpecializationType>()) {
3450 PDiag << ft_default;
3451 return;
3452 }
3453
3454 // No extra info for same types.
3455 if (Context.hasSameType(FromType, ToType)) {
3456 PDiag << ft_default;
3457 return;
3458 }
3459
3460 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3461 *ToFunction = tryGetFunctionProtoType(ToType);
3462
3463 // Both types need to be function types.
3464 if (!FromFunction || !ToFunction) {
3465 PDiag << ft_default;
3466 return;
3467 }
3468
3469 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3470 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3471 << FromFunction->getNumParams();
3472 return;
3473 }
3474
3475 // Handle different parameter types.
3476 unsigned ArgPos;
3477 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3478 PDiag << ft_parameter_mismatch << ArgPos + 1
3479 << ToFunction->getParamType(ArgPos)
3480 << FromFunction->getParamType(ArgPos);
3481 return;
3482 }
3483
3484 // Handle different return type.
3485 if (!Context.hasSameType(FromFunction->getReturnType(),
3486 ToFunction->getReturnType())) {
3487 PDiag << ft_return_type << ToFunction->getReturnType()
3488 << FromFunction->getReturnType();
3489 return;
3490 }
3491
3492 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3493 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3494 << FromFunction->getMethodQuals();
3495 return;
3496 }
3497
3498 // Handle exception specification differences on canonical type (in C++17
3499 // onwards).
3500 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3501 ->isNothrow() !=
3502 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3503 ->isNothrow()) {
3504 PDiag << ft_noexcept;
3505 return;
3506 }
3507
3508 // Unable to find a difference, so add no extra info.
3509 PDiag << ft_default;
3510 }
3511
3512 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3513 ArrayRef<QualType> New, unsigned *ArgPos,
3514 bool Reversed) {
3515 assert(llvm::size(Old) == llvm::size(New) &&
3516 "Can't compare parameters of functions with different number of "
3517 "parameters!");
3518
3519 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3520 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3521 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3522
3523 // Ignore address spaces in pointee type. This is to disallow overloading
3524 // on __ptr32/__ptr64 address spaces.
3525 QualType OldType =
3526 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3527 QualType NewType =
3528 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3529
3530 if (!Context.hasSameType(OldType, NewType)) {
3531 if (ArgPos)
3532 *ArgPos = Idx;
3533 return false;
3534 }
3535 }
3536 return true;
3537 }
3538
3539 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3540 const FunctionProtoType *NewType,
3541 unsigned *ArgPos, bool Reversed) {
3542 return FunctionParamTypesAreEqual(OldType->param_types(),
3543 NewType->param_types(), ArgPos, Reversed);
3544 }
3545
3546 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3547 const FunctionDecl *NewFunction,
3548 unsigned *ArgPos,
3549 bool Reversed) {
3550
3551 if (OldFunction->getNumNonObjectParams() !=
3552 NewFunction->getNumNonObjectParams())
3553 return false;
3554
3555 unsigned OldIgnore =
3556 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3557 unsigned NewIgnore =
3558 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3559
3560 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3561 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3562
3563 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3564 NewPT->param_types().slice(NewIgnore),
3565 ArgPos, Reversed);
3566 }
3567
3568 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3569 CastKind &Kind,
3570 CXXCastPath& BasePath,
3571 bool IgnoreBaseAccess,
3572 bool Diagnose) {
3573 QualType FromType = From->getType();
3574 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3575
3576 Kind = CK_BitCast;
3577
3578 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3579 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3580 Expr::NPCK_ZeroExpression) {
3581 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3582 DiagRuntimeBehavior(From->getExprLoc(), From,
3583 PDiag(diag::warn_impcast_bool_to_null_pointer)
3584 << ToType << From->getSourceRange());
3585 else if (!isUnevaluatedContext())
3586 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3587 << ToType << From->getSourceRange();
3588 }
3589 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3590 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3591 QualType FromPointeeType = FromPtrType->getPointeeType(),
3592 ToPointeeType = ToPtrType->getPointeeType();
3593
3594 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3595 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3596 // We must have a derived-to-base conversion. Check an
3597 // ambiguous or inaccessible conversion.
3598 unsigned InaccessibleID = 0;
3599 unsigned AmbiguousID = 0;
3600 if (Diagnose) {
3601 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3602 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3603 }
3604 if (CheckDerivedToBaseConversion(
3605 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3606 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3607 &BasePath, IgnoreBaseAccess))
3608 return true;
3609
3610 // The conversion was successful.
3611 Kind = CK_DerivedToBase;
3612 }
3613
3614 if (Diagnose && !IsCStyleOrFunctionalCast &&
3615 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3616 assert(getLangOpts().MSVCCompat &&
3617 "this should only be possible with MSVCCompat!");
3618 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3619 << From->getSourceRange();
3620 }
3621 }
3622 } else if (const ObjCObjectPointerType *ToPtrType =
3623 ToType->getAs<ObjCObjectPointerType>()) {
3624 if (const ObjCObjectPointerType *FromPtrType =
3625 FromType->getAs<ObjCObjectPointerType>()) {
3626 // Objective-C++ conversions are always okay.
3627 // FIXME: We should have a different class of conversions for the
3628 // Objective-C++ implicit conversions.
3629 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3630 return false;
3631 } else if (FromType->isBlockPointerType()) {
3632 Kind = CK_BlockPointerToObjCPointerCast;
3633 } else {
3634 Kind = CK_CPointerToObjCPointerCast;
3635 }
3636 } else if (ToType->isBlockPointerType()) {
3637 if (!FromType->isBlockPointerType())
3638 Kind = CK_AnyPointerToBlockPointerCast;
3639 }
3640
3641 // We shouldn't fall into this case unless it's valid for other
3642 // reasons.
3643 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3644 Kind = CK_NullToPointer;
3645
3646 return false;
3647 }
3648
3649 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3650 QualType ToType,
3651 bool InOverloadResolution,
3652 QualType &ConvertedType) {
3653 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3654 if (!ToTypePtr)
3655 return false;
3656
3657 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3658 if (From->isNullPointerConstant(Context,
3659 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3660 : Expr::NPC_ValueDependentIsNull)) {
3661 ConvertedType = ToType;
3662 return true;
3663 }
3664
3665 // Otherwise, both types have to be member pointers.
3666 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3667 if (!FromTypePtr)
3668 return false;
3669
3670 // A pointer to member of B can be converted to a pointer to member of D,
3671 // where D is derived from B (C++ 4.11p2).
3672 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3673 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3674
3675 if (!declaresSameEntity(FromClass, ToClass) &&
3676 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3677 ConvertedType = Context.getMemberPointerType(
3678 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3679 return true;
3680 }
3681
3682 return false;
3683 }
3684
3685 Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3686 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3687 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3688 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3689 // Lock down the inheritance model right now in MS ABI, whether or not the
3690 // pointee types are the same.
3691 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3692 (void)isCompleteType(CheckLoc, FromType);
3693 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3694 }
3695
3696 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3697 if (!FromPtrType) {
3698 // This must be a null pointer to member pointer conversion
3699 Kind = CK_NullToMemberPointer;
3700 return MemberPointerConversionResult::Success;
3701 }
3702
3703 // T == T, modulo cv
3704 if (Direction == MemberPointerConversionDirection::Upcast &&
3705 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3706 ToPtrType->getPointeeType()))
3707 return MemberPointerConversionResult::DifferentPointee;
3708
3709 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3710 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3711
3712 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3713 const CXXRecordDecl *Cls) {
3714 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3715 PD << Qual;
3716 else
3717 PD << Context.getCanonicalTagType(Cls);
3718 };
3719 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3720 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3721 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3722 return PD;
3723 };
3724
3725 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3726 if (Direction == MemberPointerConversionDirection::Upcast)
3727 std::swap(Base, Derived);
3728
3729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3730 /*DetectVirtual=*/true);
3731 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3732 return MemberPointerConversionResult::NotDerived;
3733
3734 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3735 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3736 PD << int(Direction);
3737 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3738 Diag(CheckLoc, PD);
3739 return MemberPointerConversionResult::Ambiguous;
3740 }
3741
3742 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3743 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3744 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3745 Diag(CheckLoc, PD);
3746 return MemberPointerConversionResult::Virtual;
3747 }
3748
3749 // Must be a base to derived member conversion.
3750 BuildBasePathArray(Paths, BasePath);
3751 Kind = Direction == MemberPointerConversionDirection::Upcast
3752 ? CK_DerivedToBaseMemberPointer
3753 : CK_BaseToDerivedMemberPointer;
3754
3755 if (!IgnoreBaseAccess)
3756 switch (CheckBaseClassAccess(
3757 CheckLoc, Base, Derived, Paths.front(),
3758 Direction == MemberPointerConversionDirection::Upcast
3759 ? diag::err_upcast_to_inaccessible_base
3760 : diag::err_downcast_from_inaccessible_base,
3761 [&](PartialDiagnostic &PD) {
3762 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3763 DerivedQual = ToPtrType->getQualifier();
3764 if (Direction == MemberPointerConversionDirection::Upcast)
3765 std::swap(BaseQual, DerivedQual);
3766 DiagCls(PD, DerivedQual, Derived);
3767 DiagCls(PD, BaseQual, Base);
3768 })) {
3769 case Sema::AR_accessible:
3770 case Sema::AR_delayed:
3771 case Sema::AR_dependent:
3772 // Optimistically assume that the delayed and dependent cases
3773 // will work out.
3774 break;
3775
3776 case Sema::AR_inaccessible:
3777 return MemberPointerConversionResult::Inaccessible;
3778 }
3779
3780 return MemberPointerConversionResult::Success;
3781 }
3782
3783 /// Determine whether the lifetime conversion between the two given
3784 /// qualifiers sets is nontrivial.
3785 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3786 Qualifiers ToQuals) {
3787 // Converting anything to const __unsafe_unretained is trivial.
3788 if (ToQuals.hasConst() &&
3789 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3790 return false;
3791
3792 return true;
3793 }
3794
3795 /// Perform a single iteration of the loop for checking if a qualification
3796 /// conversion is valid.
3797 ///
3798 /// Specifically, check whether any change between the qualifiers of \p
3799 /// FromType and \p ToType is permissible, given knowledge about whether every
3800 /// outer layer is const-qualified.
3801 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3802 bool CStyle, bool IsTopLevel,
3803 bool &PreviousToQualsIncludeConst,
3804 bool &ObjCLifetimeConversion,
3805 const ASTContext &Ctx) {
3806 Qualifiers FromQuals = FromType.getQualifiers();
3807 Qualifiers ToQuals = ToType.getQualifiers();
3808
3809 // Ignore __unaligned qualifier.
3810 FromQuals.removeUnaligned();
3811
3812 // Objective-C ARC:
3813 // Check Objective-C lifetime conversions.
3814 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3815 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3816 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3817 ObjCLifetimeConversion = true;
3818 FromQuals.removeObjCLifetime();
3819 ToQuals.removeObjCLifetime();
3820 } else {
3821 // Qualification conversions cannot cast between different
3822 // Objective-C lifetime qualifiers.
3823 return false;
3824 }
3825 }
3826
3827 // Allow addition/removal of GC attributes but not changing GC attributes.
3828 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3829 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3830 FromQuals.removeObjCGCAttr();
3831 ToQuals.removeObjCGCAttr();
3832 }
3833
3834 // __ptrauth qualifiers must match exactly.
3835 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3836 return false;
3837
3838 // -- for every j > 0, if const is in cv 1,j then const is in cv
3839 // 2,j, and similarly for volatile.
3840 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3841 return false;
3842
3843 // If address spaces mismatch:
3844 // - in top level it is only valid to convert to addr space that is a
3845 // superset in all cases apart from C-style casts where we allow
3846 // conversions between overlapping address spaces.
3847 // - in non-top levels it is not a valid conversion.
3848 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3849 (!IsTopLevel ||
3850 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3851 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3852 return false;
3853
3854 // -- if the cv 1,j and cv 2,j are different, then const is in
3855 // every cv for 0 < k < j.
3856 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3857 !PreviousToQualsIncludeConst)
3858 return false;
3859
3860 // The following wording is from C++20, where the result of the conversion
3861 // is T3, not T2.
3862 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3863 // "array of unknown bound of"
3864 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3865 return false;
3866
3867 // -- if the resulting P3,i is different from P1,i [...], then const is
3868 // added to every cv 3_k for 0 < k < i.
3869 if (!CStyle && FromType->isConstantArrayType() &&
3870 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3871 return false;
3872
3873 // Keep track of whether all prior cv-qualifiers in the "to" type
3874 // include const.
3875 PreviousToQualsIncludeConst =
3876 PreviousToQualsIncludeConst && ToQuals.hasConst();
3877 return true;
3878 }
3879
3880 bool
3881 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3882 bool CStyle, bool &ObjCLifetimeConversion) {
3883 FromType = Context.getCanonicalType(FromType);
3884 ToType = Context.getCanonicalType(ToType);
3885 ObjCLifetimeConversion = false;
3886
3887 // If FromType and ToType are the same type, this is not a
3888 // qualification conversion.
3889 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3890 return false;
3891
3892 // (C++ 4.4p4):
3893 // A conversion can add cv-qualifiers at levels other than the first
3894 // in multi-level pointers, subject to the following rules: [...]
3895 bool PreviousToQualsIncludeConst = true;
3896 bool UnwrappedAnyPointer = false;
3897 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3898 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3899 !UnwrappedAnyPointer,
3900 PreviousToQualsIncludeConst,
3901 ObjCLifetimeConversion, getASTContext()))
3902 return false;
3903 UnwrappedAnyPointer = true;
3904 }
3905
3906 // We are left with FromType and ToType being the pointee types
3907 // after unwrapping the original FromType and ToType the same number
3908 // of times. If we unwrapped any pointers, and if FromType and
3909 // ToType have the same unqualified type (since we checked
3910 // qualifiers above), then this is a qualification conversion.
3911 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3912 }
3913
3914 /// - Determine whether this is a conversion from a scalar type to an
3915 /// atomic type.
3916 ///
3917 /// If successful, updates \c SCS's second and third steps in the conversion
3918 /// sequence to finish the conversion.
3919 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3920 bool InOverloadResolution,
3921 StandardConversionSequence &SCS,
3922 bool CStyle) {
3923 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3924 if (!ToAtomic)
3925 return false;
3926
3927 StandardConversionSequence InnerSCS;
3928 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3929 InOverloadResolution, InnerSCS,
3930 CStyle, /*AllowObjCWritebackConversion=*/false))
3931 return false;
3932
3933 SCS.Second = InnerSCS.Second;
3934 SCS.setToType(1, InnerSCS.getToType(1));
3935 SCS.Third = InnerSCS.Third;
3936 SCS.QualificationIncludesObjCLifetime
3937 = InnerSCS.QualificationIncludesObjCLifetime;
3938 SCS.setToType(2, InnerSCS.getToType(2));
3939 return true;
3940 }
3941
3942 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3943 CXXConstructorDecl *Constructor,
3944 QualType Type) {
3945 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3946 if (CtorType->getNumParams() > 0) {
3947 QualType FirstArg = CtorType->getParamType(0);
3948 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3949 return true;
3950 }
3951 return false;
3952 }
3953
3954 static OverloadingResult
3955 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3956 CXXRecordDecl *To,
3957 UserDefinedConversionSequence &User,
3958 OverloadCandidateSet &CandidateSet,
3959 bool AllowExplicit) {
3960 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3961 for (auto *D : S.LookupConstructors(To)) {
3962 auto Info = getConstructorInfo(D);
3963 if (!Info)
3964 continue;
3965
3966 bool Usable = !Info.Constructor->isInvalidDecl() &&
3967 S.isInitListConstructor(Info.Constructor);
3968 if (Usable) {
3969 bool SuppressUserConversions = false;
3970 if (Info.ConstructorTmpl)
3971 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3972 /*ExplicitArgs*/ nullptr, From,
3973 CandidateSet, SuppressUserConversions,
3974 /*PartialOverloading*/ false,
3975 AllowExplicit);
3976 else
3977 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3978 CandidateSet, SuppressUserConversions,
3979 /*PartialOverloading*/ false, AllowExplicit);
3980 }
3981 }
3982
3983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3984
3985 OverloadCandidateSet::iterator Best;
3986 switch (auto Result =
3987 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3988 case OR_Deleted:
3989 case OR_Success: {
3990 // Record the standard conversion we used and the conversion function.
3991 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3992 QualType ThisType = Constructor->getFunctionObjectParameterType();
3993 // Initializer lists don't have conversions as such.
3994 User.Before.setAsIdentityConversion();
3995 User.HadMultipleCandidates = HadMultipleCandidates;
3996 User.ConversionFunction = Constructor;
3997 User.FoundConversionFunction = Best->FoundDecl;
3998 User.After.setAsIdentityConversion();
3999 User.After.setFromType(ThisType);
4000 User.After.setAllToTypes(ToType);
4001 return Result;
4002 }
4003
4004 case OR_No_Viable_Function:
4005 return OR_No_Viable_Function;
4006 case OR_Ambiguous:
4007 return OR_Ambiguous;
4008 }
4009
4010 llvm_unreachable("Invalid OverloadResult!");
4011 }
4012
4013 /// Determines whether there is a user-defined conversion sequence
4014 /// (C++ [over.ics.user]) that converts expression From to the type
4015 /// ToType. If such a conversion exists, User will contain the
4016 /// user-defined conversion sequence that performs such a conversion
4017 /// and this routine will return true. Otherwise, this routine returns
4018 /// false and User is unspecified.
4019 ///
4020 /// \param AllowExplicit true if the conversion should consider C++0x
4021 /// "explicit" conversion functions as well as non-explicit conversion
4022 /// functions (C++0x [class.conv.fct]p2).
4023 ///
4024 /// \param AllowObjCConversionOnExplicit true if the conversion should
4025 /// allow an extra Objective-C pointer conversion on uses of explicit
4026 /// constructors. Requires \c AllowExplicit to also be set.
4027 static OverloadingResult
4028 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4029 UserDefinedConversionSequence &User,
4030 OverloadCandidateSet &CandidateSet,
4031 AllowedExplicit AllowExplicit,
4032 bool AllowObjCConversionOnExplicit) {
4033 assert(AllowExplicit != AllowedExplicit::None ||
4034 !AllowObjCConversionOnExplicit);
4035 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4036
4037 // Whether we will only visit constructors.
4038 bool ConstructorsOnly = false;
4039
4040 // If the type we are conversion to is a class type, enumerate its
4041 // constructors.
4042 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4043 // C++ [over.match.ctor]p1:
4044 // When objects of class type are direct-initialized (8.5), or
4045 // copy-initialized from an expression of the same or a
4046 // derived class type (8.5), overload resolution selects the
4047 // constructor. [...] For copy-initialization, the candidate
4048 // functions are all the converting constructors (12.3.1) of
4049 // that class. The argument list is the expression-list within
4050 // the parentheses of the initializer.
4051 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4052 (From->getType()->isRecordType() &&
4053 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4054 ConstructorsOnly = true;
4055
4056 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4057 // We're not going to find any constructors.
4058 } else if (auto *ToRecordDecl =
4059 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4060 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4061
4062 Expr **Args = &From;
4063 unsigned NumArgs = 1;
4064 bool ListInitializing = false;
4065 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4066 // But first, see if there is an init-list-constructor that will work.
4067 OverloadingResult Result = IsInitializerListConstructorConversion(
4068 S, From, ToType, ToRecordDecl, User, CandidateSet,
4069 AllowExplicit == AllowedExplicit::All);
4070 if (Result != OR_No_Viable_Function)
4071 return Result;
4072 // Never mind.
4073 CandidateSet.clear(
4074 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4075
4076 // If we're list-initializing, we pass the individual elements as
4077 // arguments, not the entire list.
4078 Args = InitList->getInits();
4079 NumArgs = InitList->getNumInits();
4080 ListInitializing = true;
4081 }
4082
4083 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4084 auto Info = getConstructorInfo(D);
4085 if (!Info)
4086 continue;
4087
4088 bool Usable = !Info.Constructor->isInvalidDecl();
4089 if (!ListInitializing)
4090 Usable = Usable && Info.Constructor->isConvertingConstructor(
4091 /*AllowExplicit*/ true);
4092 if (Usable) {
4093 bool SuppressUserConversions = !ConstructorsOnly;
4094 // C++20 [over.best.ics.general]/4.5:
4095 // if the target is the first parameter of a constructor [of class
4096 // X] and the constructor [...] is a candidate by [...] the second
4097 // phase of [over.match.list] when the initializer list has exactly
4098 // one element that is itself an initializer list, [...] and the
4099 // conversion is to X or reference to cv X, user-defined conversion
4100 // sequences are not considered.
4101 if (SuppressUserConversions && ListInitializing) {
4102 SuppressUserConversions =
4103 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4104 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4105 ToType);
4106 }
4107 if (Info.ConstructorTmpl)
4108 S.AddTemplateOverloadCandidate(
4109 Info.ConstructorTmpl, Info.FoundDecl,
4110 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4111 CandidateSet, SuppressUserConversions,
4112 /*PartialOverloading*/ false,
4113 AllowExplicit == AllowedExplicit::All);
4114 else
4115 // Allow one user-defined conversion when user specifies a
4116 // From->ToType conversion via an static cast (c-style, etc).
4117 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4118 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4119 SuppressUserConversions,
4120 /*PartialOverloading*/ false,
4121 AllowExplicit == AllowedExplicit::All);
4122 }
4123 }
4124 }
4125 }
4126
4127 // Enumerate conversion functions, if we're allowed to.
4128 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4129 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4130 // No conversion functions from incomplete types.
4131 } else if (const RecordType *FromRecordType =
4132 From->getType()->getAsCanonical<RecordType>()) {
4133 if (auto *FromRecordDecl =
4134 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4135 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4136 // Add all of the conversion functions as candidates.
4137 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4138 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4139 DeclAccessPair FoundDecl = I.getPair();
4140 NamedDecl *D = FoundDecl.getDecl();
4141 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4142 if (isa<UsingShadowDecl>(D))
4143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4144
4145 CXXConversionDecl *Conv;
4146 FunctionTemplateDecl *ConvTemplate;
4147 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4148 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4149 else
4150 Conv = cast<CXXConversionDecl>(D);
4151
4152 if (ConvTemplate)
4153 S.AddTemplateConversionCandidate(
4154 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4155 CandidateSet, AllowObjCConversionOnExplicit,
4156 AllowExplicit != AllowedExplicit::None);
4157 else
4158 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4159 CandidateSet, AllowObjCConversionOnExplicit,
4160 AllowExplicit != AllowedExplicit::None);
4161 }
4162 }
4163 }
4164
4165 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4166
4167 OverloadCandidateSet::iterator Best;
4168 switch (auto Result =
4169 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4170 case OR_Success:
4171 case OR_Deleted:
4172 // Record the standard conversion we used and the conversion function.
4173 if (CXXConstructorDecl *Constructor
4174 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4175 // C++ [over.ics.user]p1:
4176 // If the user-defined conversion is specified by a
4177 // constructor (12.3.1), the initial standard conversion
4178 // sequence converts the source type to the type required by
4179 // the argument of the constructor.
4180 //
4181 if (isa<InitListExpr>(From)) {
4182 // Initializer lists don't have conversions as such.
4183 User.Before.setAsIdentityConversion();
4184 User.Before.FromBracedInitList = true;
4185 } else {
4186 if (Best->Conversions[0].isEllipsis())
4187 User.EllipsisConversion = true;
4188 else {
4189 User.Before = Best->Conversions[0].Standard;
4190 User.EllipsisConversion = false;
4191 }
4192 }
4193 User.HadMultipleCandidates = HadMultipleCandidates;
4194 User.ConversionFunction = Constructor;
4195 User.FoundConversionFunction = Best->FoundDecl;
4196 User.After.setAsIdentityConversion();
4197 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4198 User.After.setAllToTypes(ToType);
4199 return Result;
4200 }
4201 if (CXXConversionDecl *Conversion
4202 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4203
4204 assert(Best->HasFinalConversion);
4205
4206 // C++ [over.ics.user]p1:
4207 //
4208 // [...] If the user-defined conversion is specified by a
4209 // conversion function (12.3.2), the initial standard
4210 // conversion sequence converts the source type to the
4211 // implicit object parameter of the conversion function.
4212 User.Before = Best->Conversions[0].Standard;
4213 User.HadMultipleCandidates = HadMultipleCandidates;
4214 User.ConversionFunction = Conversion;
4215 User.FoundConversionFunction = Best->FoundDecl;
4216 User.EllipsisConversion = false;
4217
4218 // C++ [over.ics.user]p2:
4219 // The second standard conversion sequence converts the
4220 // result of the user-defined conversion to the target type
4221 // for the sequence. Since an implicit conversion sequence
4222 // is an initialization, the special rules for
4223 // initialization by user-defined conversion apply when
4224 // selecting the best user-defined conversion for a
4225 // user-defined conversion sequence (see 13.3.3 and
4226 // 13.3.3.1).
4227 User.After = Best->FinalConversion;
4228 return Result;
4229 }
4230 llvm_unreachable("Not a constructor or conversion function?");
4231
4232 case OR_No_Viable_Function:
4233 return OR_No_Viable_Function;
4234
4235 case OR_Ambiguous:
4236 return OR_Ambiguous;
4237 }
4238
4239 llvm_unreachable("Invalid OverloadResult!");
4240 }
4241
4242 bool
4243 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4244 ImplicitConversionSequence ICS;
4245 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4246 OverloadCandidateSet::CSK_Normal);
4247 OverloadingResult OvResult =
4248 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4249 CandidateSet, AllowedExplicit::None, false);
4250
4251 if (!(OvResult == OR_Ambiguous ||
4252 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4253 return false;
4254
4255 auto Cands = CandidateSet.CompleteCandidates(
4256 *this,
4257 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4258 From);
4259 if (OvResult == OR_Ambiguous)
4260 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4261 << From->getType() << ToType << From->getSourceRange();
4262 else { // OR_No_Viable_Function && !CandidateSet.empty()
4263 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4264 diag::err_typecheck_nonviable_condition_incomplete,
4265 From->getType(), From->getSourceRange()))
4266 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4267 << false << From->getType() << From->getSourceRange() << ToType;
4268 }
4269
4270 CandidateSet.NoteCandidates(
4271 *this, From, Cands);
4272 return true;
4273 }
4274
4275 // Helper for compareConversionFunctions that gets the FunctionType that the
4276 // conversion-operator return value 'points' to, or nullptr.
4277 static const FunctionType *
4278 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4279 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4280 const PointerType *RetPtrTy =
4281 ConvFuncTy->getReturnType()->getAs<PointerType>();
4282
4283 if (!RetPtrTy)
4284 return nullptr;
4285
4286 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4287 }
4288
4289 /// Compare the user-defined conversion functions or constructors
4290 /// of two user-defined conversion sequences to determine whether any ordering
4291 /// is possible.
4292 static ImplicitConversionSequence::CompareKind
4293 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4294 FunctionDecl *Function2) {
4295 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4296 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4297 if (!Conv1 || !Conv2)
4298 return ImplicitConversionSequence::Indistinguishable;
4299
4300 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4301 return ImplicitConversionSequence::Indistinguishable;
4302
4303 // Objective-C++:
4304 // If both conversion functions are implicitly-declared conversions from
4305 // a lambda closure type to a function pointer and a block pointer,
4306 // respectively, always prefer the conversion to a function pointer,
4307 // because the function pointer is more lightweight and is more likely
4308 // to keep code working.
4309 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4310 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4311 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4312 if (Block1 != Block2)
4313 return Block1 ? ImplicitConversionSequence::Worse
4314 : ImplicitConversionSequence::Better;
4315 }
4316
4317 // In order to support multiple calling conventions for the lambda conversion
4318 // operator (such as when the free and member function calling convention is
4319 // different), prefer the 'free' mechanism, followed by the calling-convention
4320 // of operator(). The latter is in place to support the MSVC-like solution of
4321 // defining ALL of the possible conversions in regards to calling-convention.
4322 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4323 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4324
4325 if (Conv1FuncRet && Conv2FuncRet &&
4326 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4327 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4328 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4329
4330 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4331 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4332
4333 CallingConv CallOpCC =
4334 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4335 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4336 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4337 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4338 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4339
4340 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4341 for (CallingConv CC : PrefOrder) {
4342 if (Conv1CC == CC)
4343 return ImplicitConversionSequence::Better;
4344 if (Conv2CC == CC)
4345 return ImplicitConversionSequence::Worse;
4346 }
4347 }
4348
4349 return ImplicitConversionSequence::Indistinguishable;
4350 }
4351
4352 static bool hasDeprecatedStringLiteralToCharPtrConversion(
4353 const ImplicitConversionSequence &ICS) {
4354 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4355 (ICS.isUserDefined() &&
4356 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4357 }
4358
4359 /// CompareImplicitConversionSequences - Compare two implicit
4360 /// conversion sequences to determine whether one is better than the
4361 /// other or if they are indistinguishable (C++ 13.3.3.2).
4362 static ImplicitConversionSequence::CompareKind
4363 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4364 const ImplicitConversionSequence& ICS1,
4365 const ImplicitConversionSequence& ICS2)
4366 {
4367 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4368 // conversion sequences (as defined in 13.3.3.1)
4369 // -- a standard conversion sequence (13.3.3.1.1) is a better
4370 // conversion sequence than a user-defined conversion sequence or
4371 // an ellipsis conversion sequence, and
4372 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4373 // conversion sequence than an ellipsis conversion sequence
4374 // (13.3.3.1.3).
4375 //
4376 // C++0x [over.best.ics]p10:
4377 // For the purpose of ranking implicit conversion sequences as
4378 // described in 13.3.3.2, the ambiguous conversion sequence is
4379 // treated as a user-defined sequence that is indistinguishable
4380 // from any other user-defined conversion sequence.
4381
4382 // String literal to 'char *' conversion has been deprecated in C++03. It has
4383 // been removed from C++11. We still accept this conversion, if it happens at
4384 // the best viable function. Otherwise, this conversion is considered worse
4385 // than ellipsis conversion. Consider this as an extension; this is not in the
4386 // standard. For example:
4387 //
4388 // int &f(...); // #1
4389 // void f(char*); // #2
4390 // void g() { int &r = f("foo"); }
4391 //
4392 // In C++03, we pick #2 as the best viable function.
4393 // In C++11, we pick #1 as the best viable function, because ellipsis
4394 // conversion is better than string-literal to char* conversion (since there
4395 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4396 // convert arguments, #2 would be the best viable function in C++11.
4397 // If the best viable function has this conversion, a warning will be issued
4398 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4399
4400 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4401 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
4402 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
4403 // Ill-formedness must not differ
4404 ICS1.isBad() == ICS2.isBad())
4405 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
4406 ? ImplicitConversionSequence::Worse
4407 : ImplicitConversionSequence::Better;
4408
4409 if (ICS1.getKindRank() < ICS2.getKindRank())
4410 return ImplicitConversionSequence::Better;
4411 if (ICS2.getKindRank() < ICS1.getKindRank())
4412 return ImplicitConversionSequence::Worse;
4413
4414 // The following checks require both conversion sequences to be of
4415 // the same kind.
4416 if (ICS1.getKind() != ICS2.getKind())
4417 return ImplicitConversionSequence::Indistinguishable;
4418
4419 ImplicitConversionSequence::CompareKind Result =
4420 ImplicitConversionSequence::Indistinguishable;
4421
4422 // Two implicit conversion sequences of the same form are
4423 // indistinguishable conversion sequences unless one of the
4424 // following rules apply: (C++ 13.3.3.2p3):
4425
4426 // List-initialization sequence L1 is a better conversion sequence than
4427 // list-initialization sequence L2 if:
4428 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4429 // if not that,
4430 // — L1 and L2 convert to arrays of the same element type, and either the
4431 // number of elements n_1 initialized by L1 is less than the number of
4432 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4433 // an array of unknown bound and L1 does not,
4434 // even if one of the other rules in this paragraph would otherwise apply.
4435 if (!ICS1.isBad()) {
4436 bool StdInit1 = false, StdInit2 = false;
4437 if (ICS1.hasInitializerListContainerType())
4438 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
4439 nullptr);
4440 if (ICS2.hasInitializerListContainerType())
4441 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
4442 nullptr);
4443 if (StdInit1 != StdInit2)
4444 return StdInit1 ? ImplicitConversionSequence::Better
4445 : ImplicitConversionSequence::Worse;
4446
4447 if (ICS1.hasInitializerListContainerType() &&
4448 ICS2.hasInitializerListContainerType())
4449 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4450 ICS1.getInitializerListContainerType()))
4451 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4452 ICS2.getInitializerListContainerType())) {
4453 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4454 CAT2->getElementType())) {
4455 // Both to arrays of the same element type
4456 if (CAT1->getSize() != CAT2->getSize())
4457 // Different sized, the smaller wins
4458 return CAT1->getSize().ult(CAT2->getSize())
4459 ? ImplicitConversionSequence::Better
4460 : ImplicitConversionSequence::Worse;
4461 if (ICS1.isInitializerListOfIncompleteArray() !=
4462 ICS2.isInitializerListOfIncompleteArray())
4463 // One is incomplete, it loses
4464 return ICS2.isInitializerListOfIncompleteArray()
4465 ? ImplicitConversionSequence::Better
4466 : ImplicitConversionSequence::Worse;
4467 }
4468 }
4469 }
4470
4471 if (ICS1.isStandard())
4472 // Standard conversion sequence S1 is a better conversion sequence than
4473 // standard conversion sequence S2 if [...]
4474 Result = CompareStandardConversionSequences(S, Loc,
4475 ICS1.Standard, ICS2.Standard);
4476 else if (ICS1.isUserDefined()) {
4477 // With lazy template loading, it is possible to find non-canonical
4478 // FunctionDecls, depending on when redecl chains are completed. Make sure
4479 // to compare the canonical decls of conversion functions. This avoids
4480 // ambiguity problems for templated conversion operators.
4481 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4482 if (ConvFunc1)
4483 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4484 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4485 if (ConvFunc2)
4486 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4487 // User-defined conversion sequence U1 is a better conversion
4488 // sequence than another user-defined conversion sequence U2 if
4489 // they contain the same user-defined conversion function or
4490 // constructor and if the second standard conversion sequence of
4491 // U1 is better than the second standard conversion sequence of
4492 // U2 (C++ 13.3.3.2p3).
4493 if (ConvFunc1 == ConvFunc2)
4494 Result = CompareStandardConversionSequences(S, Loc,
4495 ICS1.UserDefined.After,
4496 ICS2.UserDefined.After);
4497 else
4498 Result = compareConversionFunctions(S,
4499 ICS1.UserDefined.ConversionFunction,
4500 ICS2.UserDefined.ConversionFunction);
4501 }
4502
4503 return Result;
4504 }
4505
4506 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4507 // determine if one is a proper subset of the other.
4508 static ImplicitConversionSequence::CompareKind
4509 compareStandardConversionSubsets(ASTContext &Context,
4510 const StandardConversionSequence& SCS1,
4511 const StandardConversionSequence& SCS2) {
4512 ImplicitConversionSequence::CompareKind Result
4513 = ImplicitConversionSequence::Indistinguishable;
4514
4515 // the identity conversion sequence is considered to be a subsequence of
4516 // any non-identity conversion sequence
4517 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4518 return ImplicitConversionSequence::Better;
4519 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4520 return ImplicitConversionSequence::Worse;
4521
4522 if (SCS1.Second != SCS2.Second) {
4523 if (SCS1.Second == ICK_Identity)
4524 Result = ImplicitConversionSequence::Better;
4525 else if (SCS2.Second == ICK_Identity)
4526 Result = ImplicitConversionSequence::Worse;
4527 else
4528 return ImplicitConversionSequence::Indistinguishable;
4529 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4530 return ImplicitConversionSequence::Indistinguishable;
4531
4532 if (SCS1.Third == SCS2.Third) {
4533 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4534 : ImplicitConversionSequence::Indistinguishable;
4535 }
4536
4537 if (SCS1.Third == ICK_Identity)
4538 return Result == ImplicitConversionSequence::Worse
4539 ? ImplicitConversionSequence::Indistinguishable
4540 : ImplicitConversionSequence::Better;
4541
4542 if (SCS2.Third == ICK_Identity)
4543 return Result == ImplicitConversionSequence::Better
4544 ? ImplicitConversionSequence::Indistinguishable
4545 : ImplicitConversionSequence::Worse;
4546
4547 return ImplicitConversionSequence::Indistinguishable;
4548 }
4549
4550 /// Determine whether one of the given reference bindings is better
4551 /// than the other based on what kind of bindings they are.
4552 static bool
4553 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4554 const StandardConversionSequence &SCS2) {
4555 // C++0x [over.ics.rank]p3b4:
4556 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4557 // implicit object parameter of a non-static member function declared
4558 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4559 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4560 // lvalue reference to a function lvalue and S2 binds an rvalue
4561 // reference*.
4562 //
4563 // FIXME: Rvalue references. We're going rogue with the above edits,
4564 // because the semantics in the current C++0x working paper (N3225 at the
4565 // time of this writing) break the standard definition of std::forward
4566 // and std::reference_wrapper when dealing with references to functions.
4567 // Proposed wording changes submitted to CWG for consideration.
4568 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4569 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4570 return false;
4571
4572 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4573 SCS2.IsLvalueReference) ||
4574 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4575 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4576 }
4577
4578 enum class FixedEnumPromotion {
4579 None,
4580 ToUnderlyingType,
4581 ToPromotedUnderlyingType
4582 };
4583
4584 /// Returns kind of fixed enum promotion the \a SCS uses.
4585 static FixedEnumPromotion
4586 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4587
4588 if (SCS.Second != ICK_Integral_Promotion)
4589 return FixedEnumPromotion::None;
4590
4591 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4592 if (!Enum)
4593 return FixedEnumPromotion::None;
4594
4595 if (!Enum->isFixed())
4596 return FixedEnumPromotion::None;
4597
4598 QualType UnderlyingType = Enum->getIntegerType();
4599 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4600 return FixedEnumPromotion::ToUnderlyingType;
4601
4602 return FixedEnumPromotion::ToPromotedUnderlyingType;
4603 }
4604
4605 /// CompareStandardConversionSequences - Compare two standard
4606 /// conversion sequences to determine whether one is better than the
4607 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4608 static ImplicitConversionSequence::CompareKind
4609 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4610 const StandardConversionSequence& SCS1,
4611 const StandardConversionSequence& SCS2)
4612 {
4613 // Standard conversion sequence S1 is a better conversion sequence
4614 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4615
4616 // -- S1 is a proper subsequence of S2 (comparing the conversion
4617 // sequences in the canonical form defined by 13.3.3.1.1,
4618 // excluding any Lvalue Transformation; the identity conversion
4619 // sequence is considered to be a subsequence of any
4620 // non-identity conversion sequence) or, if not that,
4621 if (ImplicitConversionSequence::CompareKind CK
4622 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4623 return CK;
4624
4625 // -- the rank of S1 is better than the rank of S2 (by the rules
4626 // defined below), or, if not that,
4627 ImplicitConversionRank Rank1 = SCS1.getRank();
4628 ImplicitConversionRank Rank2 = SCS2.getRank();
4629 if (Rank1 < Rank2)
4630 return ImplicitConversionSequence::Better;
4631 else if (Rank2 < Rank1)
4632 return ImplicitConversionSequence::Worse;
4633
4634 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4635 // are indistinguishable unless one of the following rules
4636 // applies:
4637
4638 // A conversion that is not a conversion of a pointer, or
4639 // pointer to member, to bool is better than another conversion
4640 // that is such a conversion.
4641 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4642 return SCS2.isPointerConversionToBool()
4643 ? ImplicitConversionSequence::Better
4644 : ImplicitConversionSequence::Worse;
4645
4646 // C++14 [over.ics.rank]p4b2:
4647 // This is retroactively applied to C++11 by CWG 1601.
4648 //
4649 // A conversion that promotes an enumeration whose underlying type is fixed
4650 // to its underlying type is better than one that promotes to the promoted
4651 // underlying type, if the two are different.
4652 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4653 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4654 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4655 FEP1 != FEP2)
4656 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4657 ? ImplicitConversionSequence::Better
4658 : ImplicitConversionSequence::Worse;
4659
4660 // C++ [over.ics.rank]p4b2:
4661 //
4662 // If class B is derived directly or indirectly from class A,
4663 // conversion of B* to A* is better than conversion of B* to
4664 // void*, and conversion of A* to void* is better than conversion
4665 // of B* to void*.
4666 bool SCS1ConvertsToVoid
4667 = SCS1.isPointerConversionToVoidPointer(S.Context);
4668 bool SCS2ConvertsToVoid
4669 = SCS2.isPointerConversionToVoidPointer(S.Context);
4670 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4671 // Exactly one of the conversion sequences is a conversion to
4672 // a void pointer; it's the worse conversion.
4673 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4674 : ImplicitConversionSequence::Worse;
4675 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4676 // Neither conversion sequence converts to a void pointer; compare
4677 // their derived-to-base conversions.
4678 if (ImplicitConversionSequence::CompareKind DerivedCK
4679 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4680 return DerivedCK;
4681 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4682 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4683 // Both conversion sequences are conversions to void
4684 // pointers. Compare the source types to determine if there's an
4685 // inheritance relationship in their sources.
4686 QualType FromType1 = SCS1.getFromType();
4687 QualType FromType2 = SCS2.getFromType();
4688
4689 // Adjust the types we're converting from via the array-to-pointer
4690 // conversion, if we need to.
4691 if (SCS1.First == ICK_Array_To_Pointer)
4692 FromType1 = S.Context.getArrayDecayedType(FromType1);
4693 if (SCS2.First == ICK_Array_To_Pointer)
4694 FromType2 = S.Context.getArrayDecayedType(FromType2);
4695
4696 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4697 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4698
4699 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4700 return ImplicitConversionSequence::Better;
4701 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4702 return ImplicitConversionSequence::Worse;
4703
4704 // Objective-C++: If one interface is more specific than the
4705 // other, it is the better one.
4706 const ObjCObjectPointerType* FromObjCPtr1
4707 = FromType1->getAs<ObjCObjectPointerType>();
4708 const ObjCObjectPointerType* FromObjCPtr2
4709 = FromType2->getAs<ObjCObjectPointerType>();
4710 if (FromObjCPtr1 && FromObjCPtr2) {
4711 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4712 FromObjCPtr2);
4713 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4714 FromObjCPtr1);
4715 if (AssignLeft != AssignRight) {
4716 return AssignLeft? ImplicitConversionSequence::Better
4717 : ImplicitConversionSequence::Worse;
4718 }
4719 }
4720 }
4721
4722 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4723 // Check for a better reference binding based on the kind of bindings.
4724 if (isBetterReferenceBindingKind(SCS1, SCS2))
4725 return ImplicitConversionSequence::Better;
4726 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4727 return ImplicitConversionSequence::Worse;
4728 }
4729
4730 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4731 // bullet 3).
4732 if (ImplicitConversionSequence::CompareKind QualCK
4733 = CompareQualificationConversions(S, SCS1, SCS2))
4734 return QualCK;
4735
4736 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4737 // C++ [over.ics.rank]p3b4:
4738 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4739 // which the references refer are the same type except for
4740 // top-level cv-qualifiers, and the type to which the reference
4741 // initialized by S2 refers is more cv-qualified than the type
4742 // to which the reference initialized by S1 refers.
4743 QualType T1 = SCS1.getToType(2);
4744 QualType T2 = SCS2.getToType(2);
4745 T1 = S.Context.getCanonicalType(T1);
4746 T2 = S.Context.getCanonicalType(T2);
4747 Qualifiers T1Quals, T2Quals;
4748 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4749 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4750 if (UnqualT1 == UnqualT2) {
4751 // Objective-C++ ARC: If the references refer to objects with different
4752 // lifetimes, prefer bindings that don't change lifetime.
4753 if (SCS1.ObjCLifetimeConversionBinding !=
4754 SCS2.ObjCLifetimeConversionBinding) {
4755 return SCS1.ObjCLifetimeConversionBinding
4756 ? ImplicitConversionSequence::Worse
4757 : ImplicitConversionSequence::Better;
4758 }
4759
4760 // If the type is an array type, promote the element qualifiers to the
4761 // type for comparison.
4762 if (isa<ArrayType>(T1) && T1Quals)
4763 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4764 if (isa<ArrayType>(T2) && T2Quals)
4765 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4766 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4767 return ImplicitConversionSequence::Better;
4768 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4769 return ImplicitConversionSequence::Worse;
4770 }
4771 }
4772
4773 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4774 // floating-to-integral conversion if the integral conversion
4775 // is between types of the same size.
4776 // For example:
4777 // void f(float);
4778 // void f(int);
4779 // int main {
4780 // long a;
4781 // f(a);
4782 // }
4783 // Here, MSVC will call f(int) instead of generating a compile error
4784 // as clang will do in standard mode.
4785 if (S.getLangOpts().MSVCCompat &&
4786 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4787 SCS1.Second == ICK_Integral_Conversion &&
4788 SCS2.Second == ICK_Floating_Integral &&
4789 S.Context.getTypeSize(SCS1.getFromType()) ==
4790 S.Context.getTypeSize(SCS1.getToType(2)))
4791 return ImplicitConversionSequence::Better;
4792
4793 // Prefer a compatible vector conversion over a lax vector conversion
4794 // For example:
4795 //
4796 // typedef float __v4sf __attribute__((__vector_size__(16)));
4797 // void f(vector float);
4798 // void f(vector signed int);
4799 // int main() {
4800 // __v4sf a;
4801 // f(a);
4802 // }
4803 // Here, we'd like to choose f(vector float) and not
4804 // report an ambiguous call error
4805 if (SCS1.Second == ICK_Vector_Conversion &&
4806 SCS2.Second == ICK_Vector_Conversion) {
4807 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4808 SCS1.getFromType(), SCS1.getToType(2));
4809 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4810 SCS2.getFromType(), SCS2.getToType(2));
4811
4812 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4813 return SCS1IsCompatibleVectorConversion
4814 ? ImplicitConversionSequence::Better
4815 : ImplicitConversionSequence::Worse;
4816 }
4817
4818 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4819 SCS2.Second == ICK_SVE_Vector_Conversion) {
4820 bool SCS1IsCompatibleSVEVectorConversion =
4821 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4822 bool SCS2IsCompatibleSVEVectorConversion =
4823 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4824
4825 if (SCS1IsCompatibleSVEVectorConversion !=
4826 SCS2IsCompatibleSVEVectorConversion)
4827 return SCS1IsCompatibleSVEVectorConversion
4828 ? ImplicitConversionSequence::Better
4829 : ImplicitConversionSequence::Worse;
4830 }
4831
4832 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4833 SCS2.Second == ICK_RVV_Vector_Conversion) {
4834 bool SCS1IsCompatibleRVVVectorConversion =
4835 S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4836 bool SCS2IsCompatibleRVVVectorConversion =
4837 S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4838
4839 if (SCS1IsCompatibleRVVVectorConversion !=
4840 SCS2IsCompatibleRVVVectorConversion)
4841 return SCS1IsCompatibleRVVVectorConversion
4842 ? ImplicitConversionSequence::Better
4843 : ImplicitConversionSequence::Worse;
4844 }
4845 return ImplicitConversionSequence::Indistinguishable;
4846 }
4847
4848 /// CompareQualificationConversions - Compares two standard conversion
4849 /// sequences to determine whether they can be ranked based on their
4850 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4851 static ImplicitConversionSequence::CompareKind
4852 CompareQualificationConversions(Sema &S,
4853 const StandardConversionSequence& SCS1,
4854 const StandardConversionSequence& SCS2) {
4855 // C++ [over.ics.rank]p3:
4856 // -- S1 and S2 differ only in their qualification conversion and
4857 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4858 // [C++98]
4859 // [...] and the cv-qualification signature of type T1 is a proper subset
4860 // of the cv-qualification signature of type T2, and S1 is not the
4861 // deprecated string literal array-to-pointer conversion (4.2).
4862 // [C++2a]
4863 // [...] where T1 can be converted to T2 by a qualification conversion.
4864 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4865 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4866 return ImplicitConversionSequence::Indistinguishable;
4867
4868 // FIXME: the example in the standard doesn't use a qualification
4869 // conversion (!)
4870 QualType T1 = SCS1.getToType(2);
4871 QualType T2 = SCS2.getToType(2);
4872 T1 = S.Context.getCanonicalType(T1);
4873 T2 = S.Context.getCanonicalType(T2);
4874 assert(!T1->isReferenceType() && !T2->isReferenceType());
4875 Qualifiers T1Quals, T2Quals;
4876 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4877 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4878
4879 // If the types are the same, we won't learn anything by unwrapping
4880 // them.
4881 if (UnqualT1 == UnqualT2)
4882 return ImplicitConversionSequence::Indistinguishable;
4883
4884 // Don't ever prefer a standard conversion sequence that uses the deprecated
4885 // string literal array to pointer conversion.
4886 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4887 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4888
4889 // Objective-C++ ARC:
4890 // Prefer qualification conversions not involving a change in lifetime
4891 // to qualification conversions that do change lifetime.
4892 if (SCS1.QualificationIncludesObjCLifetime &&
4893 !SCS2.QualificationIncludesObjCLifetime)
4894 CanPick1 = false;
4895 if (SCS2.QualificationIncludesObjCLifetime &&
4896 !SCS1.QualificationIncludesObjCLifetime)
4897 CanPick2 = false;
4898
4899 bool ObjCLifetimeConversion;
4900 if (CanPick1 &&
4901 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4902 CanPick1 = false;
4903 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4904 // directions, so we can't short-cut this second check in general.
4905 if (CanPick2 &&
4906 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4907 CanPick2 = false;
4908
4909 if (CanPick1 != CanPick2)
4910 return CanPick1 ? ImplicitConversionSequence::Better
4911 : ImplicitConversionSequence::Worse;
4912 return ImplicitConversionSequence::Indistinguishable;
4913 }
4914
4915 /// CompareDerivedToBaseConversions - Compares two standard conversion
4916 /// sequences to determine whether they can be ranked based on their
4917 /// various kinds of derived-to-base conversions (C++
4918 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4919 /// conversions between Objective-C interface types.
4920 static ImplicitConversionSequence::CompareKind
4921 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4922 const StandardConversionSequence& SCS1,
4923 const StandardConversionSequence& SCS2) {
4924 QualType FromType1 = SCS1.getFromType();
4925 QualType ToType1 = SCS1.getToType(1);
4926 QualType FromType2 = SCS2.getFromType();
4927 QualType ToType2 = SCS2.getToType(1);
4928
4929 // Adjust the types we're converting from via the array-to-pointer
4930 // conversion, if we need to.
4931 if (SCS1.First == ICK_Array_To_Pointer)
4932 FromType1 = S.Context.getArrayDecayedType(FromType1);
4933 if (SCS2.First == ICK_Array_To_Pointer)
4934 FromType2 = S.Context.getArrayDecayedType(FromType2);
4935
4936 // Canonicalize all of the types.
4937 FromType1 = S.Context.getCanonicalType(FromType1);
4938 ToType1 = S.Context.getCanonicalType(ToType1);
4939 FromType2 = S.Context.getCanonicalType(FromType2);
4940 ToType2 = S.Context.getCanonicalType(ToType2);
4941
4942 // C++ [over.ics.rank]p4b3:
4943 //
4944 // If class B is derived directly or indirectly from class A and
4945 // class C is derived directly or indirectly from B,
4946 //
4947 // Compare based on pointer conversions.
4948 if (SCS1.Second == ICK_Pointer_Conversion &&
4949 SCS2.Second == ICK_Pointer_Conversion &&
4950 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4951 FromType1->isPointerType() && FromType2->isPointerType() &&
4952 ToType1->isPointerType() && ToType2->isPointerType()) {
4953 QualType FromPointee1 =
4954 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4955 QualType ToPointee1 =
4956 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4957 QualType FromPointee2 =
4958 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4959 QualType ToPointee2 =
4960 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4961
4962 // -- conversion of C* to B* is better than conversion of C* to A*,
4963 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4964 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4965 return ImplicitConversionSequence::Better;
4966 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4967 return ImplicitConversionSequence::Worse;
4968 }
4969
4970 // -- conversion of B* to A* is better than conversion of C* to A*,
4971 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4972 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4973 return ImplicitConversionSequence::Better;
4974 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4975 return ImplicitConversionSequence::Worse;
4976 }
4977 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4978 SCS2.Second == ICK_Pointer_Conversion) {
4979 const ObjCObjectPointerType *FromPtr1
4980 = FromType1->getAs<ObjCObjectPointerType>();
4981 const ObjCObjectPointerType *FromPtr2
4982 = FromType2->getAs<ObjCObjectPointerType>();
4983 const ObjCObjectPointerType *ToPtr1
4984 = ToType1->getAs<ObjCObjectPointerType>();
4985 const ObjCObjectPointerType *ToPtr2
4986 = ToType2->getAs<ObjCObjectPointerType>();
4987
4988 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4989 // Apply the same conversion ranking rules for Objective-C pointer types
4990 // that we do for C++ pointers to class types. However, we employ the
4991 // Objective-C pseudo-subtyping relationship used for assignment of
4992 // Objective-C pointer types.
4993 bool FromAssignLeft
4994 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4995 bool FromAssignRight
4996 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4997 bool ToAssignLeft
4998 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4999 bool ToAssignRight
5000 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5001
5002 // A conversion to an a non-id object pointer type or qualified 'id'
5003 // type is better than a conversion to 'id'.
5004 if (ToPtr1->isObjCIdType() &&
5005 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5006 return ImplicitConversionSequence::Worse;
5007 if (ToPtr2->isObjCIdType() &&
5008 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5009 return ImplicitConversionSequence::Better;
5010
5011 // A conversion to a non-id object pointer type is better than a
5012 // conversion to a qualified 'id' type
5013 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5014 return ImplicitConversionSequence::Worse;
5015 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5016 return ImplicitConversionSequence::Better;
5017
5018 // A conversion to an a non-Class object pointer type or qualified 'Class'
5019 // type is better than a conversion to 'Class'.
5020 if (ToPtr1->isObjCClassType() &&
5021 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5022 return ImplicitConversionSequence::Worse;
5023 if (ToPtr2->isObjCClassType() &&
5024 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5025 return ImplicitConversionSequence::Better;
5026
5027 // A conversion to a non-Class object pointer type is better than a
5028 // conversion to a qualified 'Class' type.
5029 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5030 return ImplicitConversionSequence::Worse;
5031 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5032 return ImplicitConversionSequence::Better;
5033
5034 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5035 if (S.Context.hasSameType(FromType1, FromType2) &&
5036 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5037 (ToAssignLeft != ToAssignRight)) {
5038 if (FromPtr1->isSpecialized()) {
5039 // "conversion of B<A> * to B * is better than conversion of B * to
5040 // C *.
5041 bool IsFirstSame =
5042 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5043 bool IsSecondSame =
5044 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5045 if (IsFirstSame) {
5046 if (!IsSecondSame)
5047 return ImplicitConversionSequence::Better;
5048 } else if (IsSecondSame)
5049 return ImplicitConversionSequence::Worse;
5050 }
5051 return ToAssignLeft? ImplicitConversionSequence::Worse
5052 : ImplicitConversionSequence::Better;
5053 }
5054
5055 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5056 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5057 (FromAssignLeft != FromAssignRight))
5058 return FromAssignLeft? ImplicitConversionSequence::Better
5059 : ImplicitConversionSequence::Worse;
5060 }
5061 }
5062
5063 // Ranking of member-pointer types.
5064 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5065 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5066 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5067 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5068 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5069 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5070 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5071 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5072 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5073 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5074 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5075 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5076 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5077 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5078 return ImplicitConversionSequence::Worse;
5079 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5080 return ImplicitConversionSequence::Better;
5081 }
5082 // conversion of B::* to C::* is better than conversion of A::* to C::*
5083 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5084 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5085 return ImplicitConversionSequence::Better;
5086 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5087 return ImplicitConversionSequence::Worse;
5088 }
5089 }
5090
5091 if (SCS1.Second == ICK_Derived_To_Base) {
5092 // -- conversion of C to B is better than conversion of C to A,
5093 // -- binding of an expression of type C to a reference of type
5094 // B& is better than binding an expression of type C to a
5095 // reference of type A&,
5096 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5097 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5098 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5099 return ImplicitConversionSequence::Better;
5100 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5101 return ImplicitConversionSequence::Worse;
5102 }
5103
5104 // -- conversion of B to A is better than conversion of C to A.
5105 // -- binding of an expression of type B to a reference of type
5106 // A& is better than binding an expression of type C to a
5107 // reference of type A&,
5108 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5109 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5110 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5111 return ImplicitConversionSequence::Better;
5112 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5113 return ImplicitConversionSequence::Worse;
5114 }
5115 }
5116
5117 return ImplicitConversionSequence::Indistinguishable;
5118 }
5119
5120 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5121 if (!T.getQualifiers().hasUnaligned())
5122 return T;
5123
5124 Qualifiers Q;
5125 T = Ctx.getUnqualifiedArrayType(T, Q);
5126 Q.removeUnaligned();
5127 return Ctx.getQualifiedType(T, Q);
5128 }
5129
5130 Sema::ReferenceCompareResult
5131 Sema::CompareReferenceRelationship(SourceLocation Loc,
5132 QualType OrigT1, QualType OrigT2,
5133 ReferenceConversions *ConvOut) {
5134 assert(!OrigT1->isReferenceType() &&
5135 "T1 must be the pointee type of the reference type");
5136 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5137
5138 QualType T1 = Context.getCanonicalType(OrigT1);
5139 QualType T2 = Context.getCanonicalType(OrigT2);
5140 Qualifiers T1Quals, T2Quals;
5141 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5142 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5143
5144 ReferenceConversions ConvTmp;
5145 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5146 Conv = ReferenceConversions();
5147
5148 // C++2a [dcl.init.ref]p4:
5149 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5150 // reference-related to "cv2 T2" if T1 is similar to T2, or
5151 // T1 is a base class of T2.
5152 // "cv1 T1" is reference-compatible with "cv2 T2" if
5153 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5154 // "pointer to cv1 T1" via a standard conversion sequence.
5155
5156 // Check for standard conversions we can apply to pointers: derived-to-base
5157 // conversions, ObjC pointer conversions, and function pointer conversions.
5158 // (Qualification conversions are checked last.)
5159 if (UnqualT1 == UnqualT2) {
5160 // Nothing to do.
5161 } else if (isCompleteType(Loc, OrigT2) &&
5162 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5163 Conv |= ReferenceConversions::DerivedToBase;
5164 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5165 UnqualT2->isObjCObjectOrInterfaceType() &&
5166 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5167 Conv |= ReferenceConversions::ObjC;
5168 else if (UnqualT2->isFunctionType() &&
5169 IsFunctionConversion(UnqualT2, UnqualT1)) {
5170 Conv |= ReferenceConversions::Function;
5171 // No need to check qualifiers; function types don't have them.
5172 return Ref_Compatible;
5173 }
5174 bool ConvertedReferent = Conv != 0;
5175
5176 // We can have a qualification conversion. Compute whether the types are
5177 // similar at the same time.
5178 bool PreviousToQualsIncludeConst = true;
5179 bool TopLevel = true;
5180 do {
5181 if (T1 == T2)
5182 break;
5183
5184 // We will need a qualification conversion.
5185 Conv |= ReferenceConversions::Qualification;
5186
5187 // Track whether we performed a qualification conversion anywhere other
5188 // than the top level. This matters for ranking reference bindings in
5189 // overload resolution.
5190 if (!TopLevel)
5191 Conv |= ReferenceConversions::NestedQualification;
5192
5193 // MS compiler ignores __unaligned qualifier for references; do the same.
5194 T1 = withoutUnaligned(Context, T1);
5195 T2 = withoutUnaligned(Context, T2);
5196
5197 // If we find a qualifier mismatch, the types are not reference-compatible,
5198 // but are still be reference-related if they're similar.
5199 bool ObjCLifetimeConversion = false;
5200 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5201 PreviousToQualsIncludeConst,
5202 ObjCLifetimeConversion, getASTContext()))
5203 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5204 ? Ref_Related
5205 : Ref_Incompatible;
5206
5207 // FIXME: Should we track this for any level other than the first?
5208 if (ObjCLifetimeConversion)
5209 Conv |= ReferenceConversions::ObjCLifetime;
5210
5211 TopLevel = false;
5212 } while (Context.UnwrapSimilarTypes(T1, T2));
5213
5214 // At this point, if the types are reference-related, we must either have the
5215 // same inner type (ignoring qualifiers), or must have already worked out how
5216 // to convert the referent.
5217 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5218 ? Ref_Compatible
5219 : Ref_Incompatible;
5220 }
5221
5222 /// Look for a user-defined conversion to a value reference-compatible
5223 /// with DeclType. Return true if something definite is found.
5224 static bool
5225 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5226 QualType DeclType, SourceLocation DeclLoc,
5227 Expr *Init, QualType T2, bool AllowRvalues,
5228 bool AllowExplicit) {
5229 assert(T2->isRecordType() && "Can only find conversions of record types.");
5230 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5231 OverloadCandidateSet CandidateSet(
5232 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5233 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5234 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5235 NamedDecl *D = *I;
5236 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5237 if (isa<UsingShadowDecl>(D))
5238 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5239
5240 FunctionTemplateDecl *ConvTemplate
5241 = dyn_cast<FunctionTemplateDecl>(D);
5242 CXXConversionDecl *Conv;
5243 if (ConvTemplate)
5244 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5245 else
5246 Conv = cast<CXXConversionDecl>(D);
5247
5248 if (AllowRvalues) {
5249 // If we are initializing an rvalue reference, don't permit conversion
5250 // functions that return lvalues.
5251 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5252 const ReferenceType *RefType
5253 = Conv->getConversionType()->getAs<LValueReferenceType>();
5254 if (RefType && !RefType->getPointeeType()->isFunctionType())
5255 continue;
5256 }
5257
5258 if (!ConvTemplate &&
5259 S.CompareReferenceRelationship(
5260 DeclLoc,
5261 Conv->getConversionType()
5262 .getNonReferenceType()
5263 .getUnqualifiedType(),
5264 DeclType.getNonReferenceType().getUnqualifiedType()) ==
5265 Sema::Ref_Incompatible)
5266 continue;
5267 } else {
5268 // If the conversion function doesn't return a reference type,
5269 // it can't be considered for this conversion. An rvalue reference
5270 // is only acceptable if its referencee is a function type.
5271
5272 const ReferenceType *RefType =
5273 Conv->getConversionType()->getAs<ReferenceType>();
5274 if (!RefType ||
5275 (!RefType->isLValueReferenceType() &&
5276 !RefType->getPointeeType()->isFunctionType()))
5277 continue;
5278 }
5279
5280 if (ConvTemplate)
5281 S.AddTemplateConversionCandidate(
5282 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5283 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5284 else
5285 S.AddConversionCandidate(
5286 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5287 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5288 }
5289
5290 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5291
5292 OverloadCandidateSet::iterator Best;
5293 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5294 case OR_Success:
5295
5296 assert(Best->HasFinalConversion);
5297
5298 // C++ [over.ics.ref]p1:
5299 //
5300 // [...] If the parameter binds directly to the result of
5301 // applying a conversion function to the argument
5302 // expression, the implicit conversion sequence is a
5303 // user-defined conversion sequence (13.3.3.1.2), with the
5304 // second standard conversion sequence either an identity
5305 // conversion or, if the conversion function returns an
5306 // entity of a type that is a derived class of the parameter
5307 // type, a derived-to-base Conversion.
5308 if (!Best->FinalConversion.DirectBinding)
5309 return false;
5310
5311 ICS.setUserDefined();
5312 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5313 ICS.UserDefined.After = Best->FinalConversion;
5314 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5315 ICS.UserDefined.ConversionFunction = Best->Function;
5316 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5317 ICS.UserDefined.EllipsisConversion = false;
5318 assert(ICS.UserDefined.After.ReferenceBinding &&
5319 ICS.UserDefined.After.DirectBinding &&
5320 "Expected a direct reference binding!");
5321 return true;
5322
5323 case OR_Ambiguous:
5324 ICS.setAmbiguous();
5325 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5326 Cand != CandidateSet.end(); ++Cand)
5327 if (Cand->Best)
5328 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5329 return true;
5330
5331 case OR_No_Viable_Function:
5332 case OR_Deleted:
5333 // There was no suitable conversion, or we found a deleted
5334 // conversion; continue with other checks.
5335 return false;
5336 }
5337
5338 llvm_unreachable("Invalid OverloadResult!");
5339 }
5340
5341 /// Compute an implicit conversion sequence for reference
5342 /// initialization.
5343 static ImplicitConversionSequence
5344 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5345 SourceLocation DeclLoc,
5346 bool SuppressUserConversions,
5347 bool AllowExplicit) {
5348 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5349
5350 // Most paths end in a failed conversion.
5351 ImplicitConversionSequence ICS;
5352 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5353
5354 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5355 QualType T2 = Init->getType();
5356
5357 // If the initializer is the address of an overloaded function, try
5358 // to resolve the overloaded function. If all goes well, T2 is the
5359 // type of the resulting function.
5360 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5361 DeclAccessPair Found;
5362 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
5363 false, Found))
5364 T2 = Fn->getType();
5365 }
5366
5367 // Compute some basic properties of the types and the initializer.
5368 bool isRValRef = DeclType->isRValueReferenceType();
5369 Expr::Classification InitCategory = Init->Classify(S.Context);
5370
5371 Sema::ReferenceConversions RefConv;
5372 Sema::ReferenceCompareResult RefRelationship =
5373 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5374
5375 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5376 ICS.setStandard();
5377 ICS.Standard.First = ICK_Identity;
5378 // FIXME: A reference binding can be a function conversion too. We should
5379 // consider that when ordering reference-to-function bindings.
5380 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5381 ? ICK_Derived_To_Base
5382 : (RefConv & Sema::ReferenceConversions::ObjC)
5383 ? ICK_Compatible_Conversion
5384 : ICK_Identity;
5385 ICS.Standard.Dimension = ICK_Identity;
5386 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5387 // a reference binding that performs a non-top-level qualification
5388 // conversion as a qualification conversion, not as an identity conversion.
5389 ICS.Standard.Third = (RefConv &
5390 Sema::ReferenceConversions::NestedQualification)
5391 ? ICK_Qualification
5392 : ICK_Identity;
5393 ICS.Standard.setFromType(T2);
5394 ICS.Standard.setToType(0, T2);
5395 ICS.Standard.setToType(1, T1);
5396 ICS.Standard.setToType(2, T1);
5397 ICS.Standard.ReferenceBinding = true;
5398 ICS.Standard.DirectBinding = BindsDirectly;
5399 ICS.Standard.IsLvalueReference = !isRValRef;
5400 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5401 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5402 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5403 ICS.Standard.ObjCLifetimeConversionBinding =
5404 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5405 ICS.Standard.FromBracedInitList = false;
5406 ICS.Standard.CopyConstructor = nullptr;
5407 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5408 };
5409
5410 // C++0x [dcl.init.ref]p5:
5411 // A reference to type "cv1 T1" is initialized by an expression
5412 // of type "cv2 T2" as follows:
5413
5414 // -- If reference is an lvalue reference and the initializer expression
5415 if (!isRValRef) {
5416 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5417 // reference-compatible with "cv2 T2," or
5418 //
5419 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5420 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5421 // C++ [over.ics.ref]p1:
5422 // When a parameter of reference type binds directly (8.5.3)
5423 // to an argument expression, the implicit conversion sequence
5424 // is the identity conversion, unless the argument expression
5425 // has a type that is a derived class of the parameter type,
5426 // in which case the implicit conversion sequence is a
5427 // derived-to-base Conversion (13.3.3.1).
5428 SetAsReferenceBinding(/*BindsDirectly=*/true);
5429
5430 // Nothing more to do: the inaccessibility/ambiguity check for
5431 // derived-to-base conversions is suppressed when we're
5432 // computing the implicit conversion sequence (C++
5433 // [over.best.ics]p2).
5434 return ICS;
5435 }
5436
5437 // -- has a class type (i.e., T2 is a class type), where T1 is
5438 // not reference-related to T2, and can be implicitly
5439 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5440 // is reference-compatible with "cv3 T3" 92) (this
5441 // conversion is selected by enumerating the applicable
5442 // conversion functions (13.3.1.6) and choosing the best
5443 // one through overload resolution (13.3)),
5444 if (!SuppressUserConversions && T2->isRecordType() &&
5445 S.isCompleteType(DeclLoc, T2) &&
5446 RefRelationship == Sema::Ref_Incompatible) {
5447 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5448 Init, T2, /*AllowRvalues=*/false,
5449 AllowExplicit))
5450 return ICS;
5451 }
5452 }
5453
5454 // -- Otherwise, the reference shall be an lvalue reference to a
5455 // non-volatile const type (i.e., cv1 shall be const), or the reference
5456 // shall be an rvalue reference.
5457 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5458 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5459 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
5460 return ICS;
5461 }
5462
5463 // -- If the initializer expression
5464 //
5465 // -- is an xvalue, class prvalue, array prvalue or function
5466 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5467 if (RefRelationship == Sema::Ref_Compatible &&
5468 (InitCategory.isXValue() ||
5469 (InitCategory.isPRValue() &&
5470 (T2->isRecordType() || T2->isArrayType())) ||
5471 (InitCategory.isLValue() && T2->isFunctionType()))) {
5472 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5473 // binding unless we're binding to a class prvalue.
5474 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5475 // allow the use of rvalue references in C++98/03 for the benefit of
5476 // standard library implementors; therefore, we need the xvalue check here.
5477 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5478 !(InitCategory.isPRValue() || T2->isRecordType()));
5479 return ICS;
5480 }
5481
5482 // -- has a class type (i.e., T2 is a class type), where T1 is not
5483 // reference-related to T2, and can be implicitly converted to
5484 // an xvalue, class prvalue, or function lvalue of type
5485 // "cv3 T3", where "cv1 T1" is reference-compatible with
5486 // "cv3 T3",
5487 //
5488 // then the reference is bound to the value of the initializer
5489 // expression in the first case and to the result of the conversion
5490 // in the second case (or, in either case, to an appropriate base
5491 // class subobject).
5492 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5493 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5494 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5495 Init, T2, /*AllowRvalues=*/true,
5496 AllowExplicit)) {
5497 // In the second case, if the reference is an rvalue reference
5498 // and the second standard conversion sequence of the
5499 // user-defined conversion sequence includes an lvalue-to-rvalue
5500 // conversion, the program is ill-formed.
5501 if (ICS.isUserDefined() && isRValRef &&
5502 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5503 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5504
5505 return ICS;
5506 }
5507
5508 // A temporary of function type cannot be created; don't even try.
5509 if (T1->isFunctionType())
5510 return ICS;
5511
5512 // -- Otherwise, a temporary of type "cv1 T1" is created and
5513 // initialized from the initializer expression using the
5514 // rules for a non-reference copy initialization (8.5). The
5515 // reference is then bound to the temporary. If T1 is
5516 // reference-related to T2, cv1 must be the same
5517 // cv-qualification as, or greater cv-qualification than,
5518 // cv2; otherwise, the program is ill-formed.
5519 if (RefRelationship == Sema::Ref_Related) {
5520 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5521 // we would be reference-compatible or reference-compatible with
5522 // added qualification. But that wasn't the case, so the reference
5523 // initialization fails.
5524 //
5525 // Note that we only want to check address spaces and cvr-qualifiers here.
5526 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5527 Qualifiers T1Quals = T1.getQualifiers();
5528 Qualifiers T2Quals = T2.getQualifiers();
5529 T1Quals.removeObjCGCAttr();
5530 T1Quals.removeObjCLifetime();
5531 T2Quals.removeObjCGCAttr();
5532 T2Quals.removeObjCLifetime();
5533 // MS compiler ignores __unaligned qualifier for references; do the same.
5534 T1Quals.removeUnaligned();
5535 T2Quals.removeUnaligned();
5536 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5537 return ICS;
5538 }
5539
5540 // If at least one of the types is a class type, the types are not
5541 // related, and we aren't allowed any user conversions, the
5542 // reference binding fails. This case is important for breaking
5543 // recursion, since TryImplicitConversion below will attempt to
5544 // create a temporary through the use of a copy constructor.
5545 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5546 (T1->isRecordType() || T2->isRecordType()))
5547 return ICS;
5548
5549 // If T1 is reference-related to T2 and the reference is an rvalue
5550 // reference, the initializer expression shall not be an lvalue.
5551 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5552 Init->Classify(S.Context).isLValue()) {
5553 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5554 return ICS;
5555 }
5556
5557 // C++ [over.ics.ref]p2:
5558 // When a parameter of reference type is not bound directly to
5559 // an argument expression, the conversion sequence is the one
5560 // required to convert the argument expression to the
5561 // underlying type of the reference according to
5562 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5563 // to copy-initializing a temporary of the underlying type with
5564 // the argument expression. Any difference in top-level
5565 // cv-qualification is subsumed by the initialization itself
5566 // and does not constitute a conversion.
5567 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5568 AllowedExplicit::None,
5569 /*InOverloadResolution=*/false,
5570 /*CStyle=*/false,
5571 /*AllowObjCWritebackConversion=*/false,
5572 /*AllowObjCConversionOnExplicit=*/false);
5573
5574 // Of course, that's still a reference binding.
5575 if (ICS.isStandard()) {
5576 ICS.Standard.ReferenceBinding = true;
5577 ICS.Standard.IsLvalueReference = !isRValRef;
5578 ICS.Standard.BindsToFunctionLvalue = false;
5579 ICS.Standard.BindsToRvalue = true;
5580 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5581 ICS.Standard.ObjCLifetimeConversionBinding = false;
5582 } else if (ICS.isUserDefined()) {
5583 const ReferenceType *LValRefType =
5584 ICS.UserDefined.ConversionFunction->getReturnType()
5585 ->getAs<LValueReferenceType>();
5586
5587 // C++ [over.ics.ref]p3:
5588 // Except for an implicit object parameter, for which see 13.3.1, a
5589 // standard conversion sequence cannot be formed if it requires [...]
5590 // binding an rvalue reference to an lvalue other than a function
5591 // lvalue.
5592 // Note that the function case is not possible here.
5593 if (isRValRef && LValRefType) {
5594 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5595 return ICS;
5596 }
5597
5598 ICS.UserDefined.After.ReferenceBinding = true;
5599 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5600 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5601 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5602 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5603 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5604 ICS.UserDefined.After.FromBracedInitList = false;
5605 }
5606
5607 return ICS;
5608 }
5609
5610 static ImplicitConversionSequence
5611 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5612 bool SuppressUserConversions,
5613 bool InOverloadResolution,
5614 bool AllowObjCWritebackConversion,
5615 bool AllowExplicit = false);
5616
5617 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5618 /// initializer list From.
5619 static ImplicitConversionSequence
5620 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5621 bool SuppressUserConversions,
5622 bool InOverloadResolution,
5623 bool AllowObjCWritebackConversion) {
5624 // C++11 [over.ics.list]p1:
5625 // When an argument is an initializer list, it is not an expression and
5626 // special rules apply for converting it to a parameter type.
5627
5628 ImplicitConversionSequence Result;
5629 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5630
5631 // We need a complete type for what follows. With one C++20 exception,
5632 // incomplete types can never be initialized from init lists.
5633 QualType InitTy = ToType;
5634 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5635 if (AT && S.getLangOpts().CPlusPlus20)
5636 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5637 // C++20 allows list initialization of an incomplete array type.
5638 InitTy = IAT->getElementType();
5639 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5640 return Result;
5641
5642 // C++20 [over.ics.list]/2:
5643 // If the initializer list is a designated-initializer-list, a conversion
5644 // is only possible if the parameter has an aggregate type
5645 //
5646 // FIXME: The exception for reference initialization here is not part of the
5647 // language rules, but follow other compilers in adding it as a tentative DR
5648 // resolution.
5649 bool IsDesignatedInit = From->hasDesignatedInit();
5650 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5651 IsDesignatedInit)
5652 return Result;
5653
5654 // Per DR1467 and DR2137:
5655 // If the parameter type is an aggregate class X and the initializer list
5656 // has a single element of type cv U, where U is X or a class derived from
5657 // X, the implicit conversion sequence is the one required to convert the
5658 // element to the parameter type.
5659 //
5660 // Otherwise, if the parameter type is a character array [... ]
5661 // and the initializer list has a single element that is an
5662 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5663 // implicit conversion sequence is the identity conversion.
5664 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5665 if (ToType->isRecordType() && ToType->isAggregateType()) {
5666 QualType InitType = From->getInit(0)->getType();
5667 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5668 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5669 return TryCopyInitialization(S, From->getInit(0), ToType,
5670 SuppressUserConversions,
5671 InOverloadResolution,
5672 AllowObjCWritebackConversion);
5673 }
5674
5675 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5676 InitializedEntity Entity =
5677 InitializedEntity::InitializeParameter(S.Context, ToType,
5678 /*Consumed=*/false);
5679 if (S.CanPerformCopyInitialization(Entity, From)) {
5680 Result.setStandard();
5681 Result.Standard.setAsIdentityConversion();
5682 Result.Standard.setFromType(ToType);
5683 Result.Standard.setAllToTypes(ToType);
5684 return Result;
5685 }
5686 }
5687 }
5688
5689 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5690 // C++11 [over.ics.list]p2:
5691 // If the parameter type is std::initializer_list<X> or "array of X" and
5692 // all the elements can be implicitly converted to X, the implicit
5693 // conversion sequence is the worst conversion necessary to convert an
5694 // element of the list to X.
5695 //
5696 // C++14 [over.ics.list]p3:
5697 // Otherwise, if the parameter type is "array of N X", if the initializer
5698 // list has exactly N elements or if it has fewer than N elements and X is
5699 // default-constructible, and if all the elements of the initializer list
5700 // can be implicitly converted to X, the implicit conversion sequence is
5701 // the worst conversion necessary to convert an element of the list to X.
5702 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5703 unsigned e = From->getNumInits();
5704 ImplicitConversionSequence DfltElt;
5705 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5706 QualType());
5707 QualType ContTy = ToType;
5708 bool IsUnbounded = false;
5709 if (AT) {
5710 InitTy = AT->getElementType();
5711 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5712 if (CT->getSize().ult(e)) {
5713 // Too many inits, fatally bad
5714 Result.setBad(BadConversionSequence::too_many_initializers, From,
5715 ToType);
5716 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5717 return Result;
5718 }
5719 if (CT->getSize().ugt(e)) {
5720 // Need an init from empty {}, is there one?
5721 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5722 From->getEndLoc());
5723 EmptyList.setType(S.Context.VoidTy);
5724 DfltElt = TryListConversion(
5725 S, &EmptyList, InitTy, SuppressUserConversions,
5726 InOverloadResolution, AllowObjCWritebackConversion);
5727 if (DfltElt.isBad()) {
5728 // No {} init, fatally bad
5729 Result.setBad(BadConversionSequence::too_few_initializers, From,
5730 ToType);
5731 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5732 return Result;
5733 }
5734 }
5735 } else {
5736 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5737 IsUnbounded = true;
5738 if (!e) {
5739 // Cannot convert to zero-sized.
5740 Result.setBad(BadConversionSequence::too_few_initializers, From,
5741 ToType);
5742 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5743 return Result;
5744 }
5745 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5746 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5747 ArraySizeModifier::Normal, 0);
5748 }
5749 }
5750
5751 Result.setStandard();
5752 Result.Standard.setAsIdentityConversion();
5753 Result.Standard.setFromType(InitTy);
5754 Result.Standard.setAllToTypes(InitTy);
5755 for (unsigned i = 0; i < e; ++i) {
5756 Expr *Init = From->getInit(i);
5757 ImplicitConversionSequence ICS = TryCopyInitialization(
5758 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5759 AllowObjCWritebackConversion);
5760
5761 // Keep the worse conversion seen so far.
5762 // FIXME: Sequences are not totally ordered, so 'worse' can be
5763 // ambiguous. CWG has been informed.
5764 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5765 Result) ==
5766 ImplicitConversionSequence::Worse) {
5767 Result = ICS;
5768 // Bail as soon as we find something unconvertible.
5769 if (Result.isBad()) {
5770 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5771 return Result;
5772 }
5773 }
5774 }
5775
5776 // If we needed any implicit {} initialization, compare that now.
5777 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5778 // has been informed that this might not be the best thing.
5779 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5780 S, From->getEndLoc(), DfltElt, Result) ==
5781 ImplicitConversionSequence::Worse)
5782 Result = DfltElt;
5783 // Record the type being initialized so that we may compare sequences
5784 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5785 return Result;
5786 }
5787
5788 // C++14 [over.ics.list]p4:
5789 // C++11 [over.ics.list]p3:
5790 // Otherwise, if the parameter is a non-aggregate class X and overload
5791 // resolution chooses a single best constructor [...] the implicit
5792 // conversion sequence is a user-defined conversion sequence. If multiple
5793 // constructors are viable but none is better than the others, the
5794 // implicit conversion sequence is a user-defined conversion sequence.
5795 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5796 // This function can deal with initializer lists.
5797 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5798 AllowedExplicit::None,
5799 InOverloadResolution, /*CStyle=*/false,
5800 AllowObjCWritebackConversion,
5801 /*AllowObjCConversionOnExplicit=*/false);
5802 }
5803
5804 // C++14 [over.ics.list]p5:
5805 // C++11 [over.ics.list]p4:
5806 // Otherwise, if the parameter has an aggregate type which can be
5807 // initialized from the initializer list [...] the implicit conversion
5808 // sequence is a user-defined conversion sequence.
5809 if (ToType->isAggregateType()) {
5810 // Type is an aggregate, argument is an init list. At this point it comes
5811 // down to checking whether the initialization works.
5812 // FIXME: Find out whether this parameter is consumed or not.
5813 InitializedEntity Entity =
5814 InitializedEntity::InitializeParameter(S.Context, ToType,
5815 /*Consumed=*/false);
5816 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5817 From)) {
5818 Result.setUserDefined();
5819 Result.UserDefined.Before.setAsIdentityConversion();
5820 // Initializer lists don't have a type.
5821 Result.UserDefined.Before.setFromType(QualType());
5822 Result.UserDefined.Before.setAllToTypes(QualType());
5823
5824 Result.UserDefined.After.setAsIdentityConversion();
5825 Result.UserDefined.After.setFromType(ToType);
5826 Result.UserDefined.After.setAllToTypes(ToType);
5827 Result.UserDefined.ConversionFunction = nullptr;
5828 }
5829 return Result;
5830 }
5831
5832 // C++14 [over.ics.list]p6:
5833 // C++11 [over.ics.list]p5:
5834 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5835 if (ToType->isReferenceType()) {
5836 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5837 // mention initializer lists in any way. So we go by what list-
5838 // initialization would do and try to extrapolate from that.
5839
5840 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5841
5842 // If the initializer list has a single element that is reference-related
5843 // to the parameter type, we initialize the reference from that.
5844 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5845 Expr *Init = From->getInit(0);
5846
5847 QualType T2 = Init->getType();
5848
5849 // If the initializer is the address of an overloaded function, try
5850 // to resolve the overloaded function. If all goes well, T2 is the
5851 // type of the resulting function.
5852 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5853 DeclAccessPair Found;
5854 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5855 Init, ToType, false, Found))
5856 T2 = Fn->getType();
5857 }
5858
5859 // Compute some basic properties of the types and the initializer.
5860 Sema::ReferenceCompareResult RefRelationship =
5861 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5862
5863 if (RefRelationship >= Sema::Ref_Related) {
5864 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5865 SuppressUserConversions,
5866 /*AllowExplicit=*/false);
5867 }
5868 }
5869
5870 // Otherwise, we bind the reference to a temporary created from the
5871 // initializer list.
5872 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5873 InOverloadResolution,
5874 AllowObjCWritebackConversion);
5875 if (Result.isFailure())
5876 return Result;
5877 assert(!Result.isEllipsis() &&
5878 "Sub-initialization cannot result in ellipsis conversion.");
5879
5880 // Can we even bind to a temporary?
5881 if (ToType->isRValueReferenceType() ||
5882 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5883 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5884 Result.UserDefined.After;
5885 SCS.ReferenceBinding = true;
5886 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5887 SCS.BindsToRvalue = true;
5888 SCS.BindsToFunctionLvalue = false;
5889 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5890 SCS.ObjCLifetimeConversionBinding = false;
5891 SCS.FromBracedInitList = false;
5892
5893 } else
5894 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5895 From, ToType);
5896 return Result;
5897 }
5898
5899 // C++14 [over.ics.list]p7:
5900 // C++11 [over.ics.list]p6:
5901 // Otherwise, if the parameter type is not a class:
5902 if (!ToType->isRecordType()) {
5903 // - if the initializer list has one element that is not itself an
5904 // initializer list, the implicit conversion sequence is the one
5905 // required to convert the element to the parameter type.
5906 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5907 // single integer.
5908 unsigned NumInits = From->getNumInits();
5909 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5910 !isa<EmbedExpr>(From->getInit(0))) {
5911 Result = TryCopyInitialization(
5912 S, From->getInit(0), ToType, SuppressUserConversions,
5913 InOverloadResolution, AllowObjCWritebackConversion);
5914 if (Result.isStandard())
5915 Result.Standard.FromBracedInitList = true;
5916 }
5917 // - if the initializer list has no elements, the implicit conversion
5918 // sequence is the identity conversion.
5919 else if (NumInits == 0) {
5920 Result.setStandard();
5921 Result.Standard.setAsIdentityConversion();
5922 Result.Standard.setFromType(ToType);
5923 Result.Standard.setAllToTypes(ToType);
5924 }
5925 return Result;
5926 }
5927
5928 // C++14 [over.ics.list]p8:
5929 // C++11 [over.ics.list]p7:
5930 // In all cases other than those enumerated above, no conversion is possible
5931 return Result;
5932 }
5933
5934 /// TryCopyInitialization - Try to copy-initialize a value of type
5935 /// ToType from the expression From. Return the implicit conversion
5936 /// sequence required to pass this argument, which may be a bad
5937 /// conversion sequence (meaning that the argument cannot be passed to
5938 /// a parameter of this type). If @p SuppressUserConversions, then we
5939 /// do not permit any user-defined conversion sequences.
5940 static ImplicitConversionSequence
5941 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5942 bool SuppressUserConversions,
5943 bool InOverloadResolution,
5944 bool AllowObjCWritebackConversion,
5945 bool AllowExplicit) {
5946 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5947 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5948 InOverloadResolution,AllowObjCWritebackConversion);
5949
5950 if (ToType->isReferenceType())
5951 return TryReferenceInit(S, From, ToType,
5952 /*FIXME:*/ From->getBeginLoc(),
5953 SuppressUserConversions, AllowExplicit);
5954
5955 return TryImplicitConversion(S, From, ToType,
5956 SuppressUserConversions,
5957 AllowedExplicit::None,
5958 InOverloadResolution,
5959 /*CStyle=*/false,
5960 AllowObjCWritebackConversion,
5961 /*AllowObjCConversionOnExplicit=*/false);
5962 }
5963
5964 static bool TryCopyInitialization(const CanQualType FromQTy,
5965 const CanQualType ToQTy,
5966 Sema &S,
5967 SourceLocation Loc,
5968 ExprValueKind FromVK) {
5969 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5970 ImplicitConversionSequence ICS =
5971 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5972
5973 return !ICS.isBad();
5974 }
5975
5976 /// TryObjectArgumentInitialization - Try to initialize the object
5977 /// parameter of the given member function (@c Method) from the
5978 /// expression @p From.
5979 static ImplicitConversionSequence TryObjectArgumentInitialization(
5980 Sema &S, SourceLocation Loc, QualType FromType,
5981 Expr::Classification FromClassification, CXXMethodDecl *Method,
5982 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5983 QualType ExplicitParameterType = QualType(),
5984 bool SuppressUserConversion = false) {
5985
5986 // We need to have an object of class type.
5987 if (const auto *PT = FromType->getAs<PointerType>()) {
5988 FromType = PT->getPointeeType();
5989
5990 // When we had a pointer, it's implicitly dereferenced, so we
5991 // better have an lvalue.
5992 assert(FromClassification.isLValue());
5993 }
5994
5995 auto ValueKindFromClassification = [](Expr::Classification C) {
5996 if (C.isPRValue())
5997 return clang::VK_PRValue;
5998 if (C.isXValue())
5999 return VK_XValue;
6000 return clang::VK_LValue;
6001 };
6002
6003 if (Method->isExplicitObjectMemberFunction()) {
6004 if (ExplicitParameterType.isNull())
6005 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6006 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6007 ValueKindFromClassification(FromClassification));
6008 ImplicitConversionSequence ICS = TryCopyInitialization(
6009 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6010 /*InOverloadResolution=*/true, false);
6011 if (ICS.isBad())
6012 ICS.Bad.FromExpr = nullptr;
6013 return ICS;
6014 }
6015
6016 assert(FromType->isRecordType());
6017
6018 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6019 // C++98 [class.dtor]p2:
6020 // A destructor can be invoked for a const, volatile or const volatile
6021 // object.
6022 // C++98 [over.match.funcs]p4:
6023 // For static member functions, the implicit object parameter is considered
6024 // to match any object (since if the function is selected, the object is
6025 // discarded).
6026 Qualifiers Quals = Method->getMethodQualifiers();
6027 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6028 Quals.addConst();
6029 Quals.addVolatile();
6030 }
6031
6032 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6033
6034 // Set up the conversion sequence as a "bad" conversion, to allow us
6035 // to exit early.
6036 ImplicitConversionSequence ICS;
6037
6038 // C++0x [over.match.funcs]p4:
6039 // For non-static member functions, the type of the implicit object
6040 // parameter is
6041 //
6042 // - "lvalue reference to cv X" for functions declared without a
6043 // ref-qualifier or with the & ref-qualifier
6044 // - "rvalue reference to cv X" for functions declared with the &&
6045 // ref-qualifier
6046 //
6047 // where X is the class of which the function is a member and cv is the
6048 // cv-qualification on the member function declaration.
6049 //
6050 // However, when finding an implicit conversion sequence for the argument, we
6051 // are not allowed to perform user-defined conversions
6052 // (C++ [over.match.funcs]p5). We perform a simplified version of
6053 // reference binding here, that allows class rvalues to bind to
6054 // non-constant references.
6055
6056 // First check the qualifiers.
6057 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6058 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6059 if (ImplicitParamType.getCVRQualifiers() !=
6060 FromTypeCanon.getLocalCVRQualifiers() &&
6061 !ImplicitParamType.isAtLeastAsQualifiedAs(
6062 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6063 ICS.setBad(BadConversionSequence::bad_qualifiers,
6064 FromType, ImplicitParamType);
6065 return ICS;
6066 }
6067
6068 if (FromTypeCanon.hasAddressSpace()) {
6069 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6070 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6071 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6072 S.getASTContext())) {
6073 ICS.setBad(BadConversionSequence::bad_qualifiers,
6074 FromType, ImplicitParamType);
6075 return ICS;
6076 }
6077 }
6078
6079 // Check that we have either the same type or a derived type. It
6080 // affects the conversion rank.
6081 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6082 ImplicitConversionKind SecondKind;
6083 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6084 SecondKind = ICK_Identity;
6085 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6086 SecondKind = ICK_Derived_To_Base;
6087 } else if (!Method->isExplicitObjectMemberFunction()) {
6088 ICS.setBad(BadConversionSequence::unrelated_class,
6089 FromType, ImplicitParamType);
6090 return ICS;
6091 }
6092
6093 // Check the ref-qualifier.
6094 switch (Method->getRefQualifier()) {
6095 case RQ_None:
6096 // Do nothing; we don't care about lvalueness or rvalueness.
6097 break;
6098
6099 case RQ_LValue:
6100 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6101 // non-const lvalue reference cannot bind to an rvalue
6102 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6103 ImplicitParamType);
6104 return ICS;
6105 }
6106 break;
6107
6108 case RQ_RValue:
6109 if (!FromClassification.isRValue()) {
6110 // rvalue reference cannot bind to an lvalue
6111 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6112 ImplicitParamType);
6113 return ICS;
6114 }
6115 break;
6116 }
6117
6118 // Success. Mark this as a reference binding.
6119 ICS.setStandard();
6120 ICS.Standard.setAsIdentityConversion();
6121 ICS.Standard.Second = SecondKind;
6122 ICS.Standard.setFromType(FromType);
6123 ICS.Standard.setAllToTypes(ImplicitParamType);
6124 ICS.Standard.ReferenceBinding = true;
6125 ICS.Standard.DirectBinding = true;
6126 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6127 ICS.Standard.BindsToFunctionLvalue = false;
6128 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6129 ICS.Standard.FromBracedInitList = false;
6130 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6131 = (Method->getRefQualifier() == RQ_None);
6132 return ICS;
6133 }
6134
6135 /// PerformObjectArgumentInitialization - Perform initialization of
6136 /// the implicit object parameter for the given Method with the given
6137 /// expression.
6138 ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6139 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6140 CXXMethodDecl *Method) {
6141 QualType FromRecordType, DestType;
6142 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6143
6144 Expr::Classification FromClassification;
6145 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6146 FromRecordType = PT->getPointeeType();
6147 DestType = Method->getThisType();
6148 FromClassification = Expr::Classification::makeSimpleLValue();
6149 } else {
6150 FromRecordType = From->getType();
6151 DestType = ImplicitParamRecordType;
6152 FromClassification = From->Classify(Context);
6153
6154 // CWG2813 [expr.call]p6:
6155 // If the function is an implicit object member function, the object
6156 // expression of the class member access shall be a glvalue [...]
6157 if (From->isPRValue()) {
6158 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6159 Method->getRefQualifier() !=
6160 RefQualifierKind::RQ_RValue);
6161 }
6162 }
6163
6164 // Note that we always use the true parent context when performing
6165 // the actual argument initialization.
6166 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6167 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6168 Method->getParent());
6169 if (ICS.isBad()) {
6170 switch (ICS.Bad.Kind) {
6171 case BadConversionSequence::bad_qualifiers: {
6172 Qualifiers FromQs = FromRecordType.getQualifiers();
6173 Qualifiers ToQs = DestType.getQualifiers();
6174 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6175 if (CVR) {
6176 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6177 << Method->getDeclName() << FromRecordType << (CVR - 1)
6178 << From->getSourceRange();
6179 Diag(Method->getLocation(), diag::note_previous_decl)
6180 << Method->getDeclName();
6181 return ExprError();
6182 }
6183 break;
6184 }
6185
6186 case BadConversionSequence::lvalue_ref_to_rvalue:
6187 case BadConversionSequence::rvalue_ref_to_lvalue: {
6188 bool IsRValueQualified =
6189 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6190 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6191 << Method->getDeclName() << FromClassification.isRValue()
6192 << IsRValueQualified;
6193 Diag(Method->getLocation(), diag::note_previous_decl)
6194 << Method->getDeclName();
6195 return ExprError();
6196 }
6197
6198 case BadConversionSequence::no_conversion:
6199 case BadConversionSequence::unrelated_class:
6200 break;
6201
6202 case BadConversionSequence::too_few_initializers:
6203 case BadConversionSequence::too_many_initializers:
6204 llvm_unreachable("Lists are not objects");
6205 }
6206
6207 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6208 << ImplicitParamRecordType << FromRecordType
6209 << From->getSourceRange();
6210 }
6211
6212 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6213 ExprResult FromRes =
6214 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6215 if (FromRes.isInvalid())
6216 return ExprError();
6217 From = FromRes.get();
6218 }
6219
6220 if (!Context.hasSameType(From->getType(), DestType)) {
6221 CastKind CK;
6222 QualType PteeTy = DestType->getPointeeType();
6223 LangAS DestAS =
6224 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6225 if (FromRecordType.getAddressSpace() != DestAS)
6226 CK = CK_AddressSpaceConversion;
6227 else
6228 CK = CK_NoOp;
6229 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6230 }
6231 return From;
6232 }
6233
6234 /// TryContextuallyConvertToBool - Attempt to contextually convert the
6235 /// expression From to bool (C++0x [conv]p3).
6236 static ImplicitConversionSequence
6237 TryContextuallyConvertToBool(Sema &S, Expr *From) {
6238 // C++ [dcl.init]/17.8:
6239 // - Otherwise, if the initialization is direct-initialization, the source
6240 // type is std::nullptr_t, and the destination type is bool, the initial
6241 // value of the object being initialized is false.
6242 if (From->getType()->isNullPtrType())
6243 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
6244 S.Context.BoolTy,
6245 From->isGLValue());
6246
6247 // All other direct-initialization of bool is equivalent to an implicit
6248 // conversion to bool in which explicit conversions are permitted.
6249 return TryImplicitConversion(S, From, S.Context.BoolTy,
6250 /*SuppressUserConversions=*/false,
6251 AllowedExplicit::Conversions,
6252 /*InOverloadResolution=*/false,
6253 /*CStyle=*/false,
6254 /*AllowObjCWritebackConversion=*/false,
6255 /*AllowObjCConversionOnExplicit=*/false);
6256 }
6257
6258 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6259 if (checkPlaceholderForOverload(*this, From))
6260 return ExprError();
6261
6262 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
6263 if (!ICS.isBad())
6264 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6265 AssignmentAction::Converting);
6266
6267 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6268 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6269 << From->getType() << From->getSourceRange();
6270 return ExprError();
6271 }
6272
6273 /// Check that the specified conversion is permitted in a converted constant
6274 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
6275 /// is acceptable.
6276 static bool CheckConvertedConstantConversions(Sema &S,
6277 StandardConversionSequence &SCS) {
6278 // Since we know that the target type is an integral or unscoped enumeration
6279 // type, most conversion kinds are impossible. All possible First and Third
6280 // conversions are fine.
6281 switch (SCS.Second) {
6282 case ICK_Identity:
6283 case ICK_Integral_Promotion:
6284 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6285 case ICK_Zero_Queue_Conversion:
6286 return true;
6287
6288 case ICK_Boolean_Conversion:
6289 // Conversion from an integral or unscoped enumeration type to bool is
6290 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6291 // conversion, so we allow it in a converted constant expression.
6292 //
6293 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6294 // a lot of popular code. We should at least add a warning for this
6295 // (non-conforming) extension.
6296 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6297 SCS.getToType(2)->isBooleanType();
6298
6299 case ICK_Pointer_Conversion:
6300 case ICK_Pointer_Member:
6301 // C++1z: null pointer conversions and null member pointer conversions are
6302 // only permitted if the source type is std::nullptr_t.
6303 return SCS.getFromType()->isNullPtrType();
6304
6305 case ICK_Floating_Promotion:
6306 case ICK_Complex_Promotion:
6307 case ICK_Floating_Conversion:
6308 case ICK_Complex_Conversion:
6309 case ICK_Floating_Integral:
6310 case ICK_Compatible_Conversion:
6311 case ICK_Derived_To_Base:
6312 case ICK_Vector_Conversion:
6313 case ICK_SVE_Vector_Conversion:
6314 case ICK_RVV_Vector_Conversion:
6315 case ICK_HLSL_Vector_Splat:
6316 case ICK_HLSL_Matrix_Splat:
6317 case ICK_Vector_Splat:
6318 case ICK_Complex_Real:
6319 case ICK_Block_Pointer_Conversion:
6320 case ICK_TransparentUnionConversion:
6321 case ICK_Writeback_Conversion:
6322 case ICK_Zero_Event_Conversion:
6323 case ICK_C_Only_Conversion:
6324 case ICK_Incompatible_Pointer_Conversion:
6325 case ICK_Fixed_Point_Conversion:
6326 case ICK_HLSL_Vector_Truncation:
6327 case ICK_HLSL_Matrix_Truncation:
6328 return false;
6329
6330 case ICK_Lvalue_To_Rvalue:
6331 case ICK_Array_To_Pointer:
6332 case ICK_Function_To_Pointer:
6333 case ICK_HLSL_Array_RValue:
6334 llvm_unreachable("found a first conversion kind in Second");
6335
6336 case ICK_Function_Conversion:
6337 case ICK_Qualification:
6338 llvm_unreachable("found a third conversion kind in Second");
6339
6340 case ICK_Num_Conversion_Kinds:
6341 break;
6342 }
6343
6344 llvm_unreachable("unknown conversion kind");
6345 }
6346
6347 /// BuildConvertedConstantExpression - Check that the expression From is a
6348 /// converted constant expression of type T, perform the conversion but
6349 /// does not evaluate the expression
6350 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6351 QualType T, CCEKind CCE,
6352 NamedDecl *Dest,
6353 APValue &PreNarrowingValue) {
6354 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6355 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);
6356 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6357 "converted constant expression outside C++11 or TTP matching");
6358
6359 if (checkPlaceholderForOverload(S, From))
6360 return ExprError();
6361
6362 // C++1z [expr.const]p3:
6363 // A converted constant expression of type T is an expression,
6364 // implicitly converted to type T, where the converted
6365 // expression is a constant expression and the implicit conversion
6366 // sequence contains only [... list of conversions ...].
6367 ImplicitConversionSequence ICS =
6368 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6369 ? TryContextuallyConvertToBool(S, From)
6370 : TryCopyInitialization(S, From, T,
6371 /*SuppressUserConversions=*/false,
6372 /*InOverloadResolution=*/false,
6373 /*AllowObjCWritebackConversion=*/false,
6374 /*AllowExplicit=*/false);
6375 StandardConversionSequence *SCS = nullptr;
6376 switch (ICS.getKind()) {
6377 case ImplicitConversionSequence::StandardConversion:
6378 SCS = &ICS.Standard;
6379 break;
6380 case ImplicitConversionSequence::UserDefinedConversion:
6381 if (T->isRecordType())
6382 SCS = &ICS.UserDefined.Before;
6383 else
6384 SCS = &ICS.UserDefined.After;
6385 break;
6386 case ImplicitConversionSequence::AmbiguousConversion:
6387 case ImplicitConversionSequence::BadConversion:
6388 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
6389 return S.Diag(From->getBeginLoc(),
6390 diag::err_typecheck_converted_constant_expression)
6391 << From->getType() << From->getSourceRange() << T;
6392 return ExprError();
6393
6394 case ImplicitConversionSequence::EllipsisConversion:
6395 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6396 llvm_unreachable("bad conversion in converted constant expression");
6397 }
6398
6399 // Check that we would only use permitted conversions.
6400 if (!CheckConvertedConstantConversions(S, *SCS)) {
6401 return S.Diag(From->getBeginLoc(),
6402 diag::err_typecheck_converted_constant_expression_disallowed)
6403 << From->getType() << From->getSourceRange() << T;
6404 }
6405 // [...] and where the reference binding (if any) binds directly.
6406 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6407 return S.Diag(From->getBeginLoc(),
6408 diag::err_typecheck_converted_constant_expression_indirect)
6409 << From->getType() << From->getSourceRange() << T;
6410 }
6411 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6412 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6413 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6414 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6415 // case explicitly.
6416 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6417 return S.Diag(From->getBeginLoc(),
6418 diag::err_reference_bind_to_bitfield_in_cce)
6419 << From->getSourceRange();
6420 }
6421
6422 // Usually we can simply apply the ImplicitConversionSequence we formed
6423 // earlier, but that's not guaranteed to work when initializing an object of
6424 // class type.
6425 ExprResult Result;
6426 bool IsTemplateArgument =
6427 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6428 if (T->isRecordType()) {
6429 assert(IsTemplateArgument &&
6430 "unexpected class type converted constant expr");
6431 Result = S.PerformCopyInitialization(
6432 InitializedEntity::InitializeTemplateParameter(
6433 T, cast<NonTypeTemplateParmDecl>(Dest)),
6434 SourceLocation(), From);
6435 } else {
6436 Result =
6437 S.PerformImplicitConversion(From, T, ICS, AssignmentAction::Converting);
6438 }
6439 if (Result.isInvalid())
6440 return Result;
6441
6442 // C++2a [intro.execution]p5:
6443 // A full-expression is [...] a constant-expression [...]
6444 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6445 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6446 IsTemplateArgument);
6447 if (Result.isInvalid())
6448 return Result;
6449
6450 // Check for a narrowing implicit conversion.
6451 bool ReturnPreNarrowingValue = false;
6452 QualType PreNarrowingType;
6453 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6454 PreNarrowingType)) {
6455 case NK_Variable_Narrowing:
6456 // Implicit conversion to a narrower type, and the value is not a constant
6457 // expression. We'll diagnose this in a moment.
6458 case NK_Not_Narrowing:
6459 break;
6460
6461 case NK_Constant_Narrowing:
6462 if (CCE == CCEKind::ArrayBound &&
6463 PreNarrowingType->isIntegralOrEnumerationType() &&
6464 PreNarrowingValue.isInt()) {
6465 // Don't diagnose array bound narrowing here; we produce more precise
6466 // errors by allowing the un-narrowed value through.
6467 ReturnPreNarrowingValue = true;
6468 break;
6469 }
6470 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6471 << CCE << /*Constant*/ 1
6472 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6473 // If this is an SFINAE Context, treat the result as invalid so it stops
6474 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6475 // FIXME: Should do this whenever the above diagnostic is an error, but
6476 // without further changes this would degrade some other diagnostics.
6477 if (S.isSFINAEContext())
6478 return ExprError();
6479 break;
6480
6481 case NK_Dependent_Narrowing:
6482 // Implicit conversion to a narrower type, but the expression is
6483 // value-dependent so we can't tell whether it's actually narrowing.
6484 // For matching the parameters of a TTP, the conversion is ill-formed
6485 // if it may narrow.
6486 if (CCE != CCEKind::TempArgStrict)
6487 break;
6488 [[fallthrough]];
6489 case NK_Type_Narrowing:
6490 // FIXME: It would be better to diagnose that the expression is not a
6491 // constant expression.
6492 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6493 << CCE << /*Constant*/ 0 << From->getType() << T;
6494 if (S.isSFINAEContext())
6495 return ExprError();
6496 break;
6497 }
6498 if (!ReturnPreNarrowingValue)
6499 PreNarrowingValue = {};
6500
6501 return Result;
6502 }
6503
6504 /// CheckConvertedConstantExpression - Check that the expression From is a
6505 /// converted constant expression of type T, perform the conversion and produce
6506 /// the converted expression, per C++11 [expr.const]p3.
6507 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6508 QualType T, APValue &Value,
6509 CCEKind CCE, bool RequireInt,
6510 NamedDecl *Dest) {
6511
6512 APValue PreNarrowingValue;
6513 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6514 PreNarrowingValue);
6515 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6516 Value = APValue();
6517 return Result;
6518 }
6519 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6520 RequireInt, PreNarrowingValue);
6521 }
6522
6523 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6524 CCEKind CCE,
6525 NamedDecl *Dest) {
6526 APValue PreNarrowingValue;
6527 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6528 PreNarrowingValue);
6529 }
6530
6531 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6532 APValue &Value, CCEKind CCE,
6533 NamedDecl *Dest) {
6534 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6535 Dest);
6536 }
6537
6538 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6539 llvm::APSInt &Value,
6540 CCEKind CCE) {
6541 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6542
6543 APValue V;
6544 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6545 /*Dest=*/nullptr);
6546 if (!R.isInvalid() && !R.get()->isValueDependent())
6547 Value = V.getInt();
6548 return R;
6549 }
6550
6551 ExprResult
6552 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6553 CCEKind CCE, bool RequireInt,
6554 const APValue &PreNarrowingValue) {
6555
6556 ExprResult Result = E;
6557 // Check the expression is a constant expression.
6558 SmallVector<PartialDiagnosticAt, 8> Notes;
6559 Expr::EvalResult Eval;
6560 Eval.Diag = &Notes;
6561
6562 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6563
6564 ConstantExprKind Kind;
6565 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6566 Kind = ConstantExprKind::ClassTemplateArgument;
6567 else if (CCE == CCEKind::TemplateArg)
6568 Kind = ConstantExprKind::NonClassTemplateArgument;
6569 else
6570 Kind = ConstantExprKind::Normal;
6571
6572 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6573 (RequireInt && !Eval.Val.isInt())) {
6574 // The expression can't be folded, so we can't keep it at this position in
6575 // the AST.
6576 Result = ExprError();
6577 } else {
6578 Value = Eval.Val;
6579
6580 if (Notes.empty()) {
6581 // It's a constant expression.
6582 Expr *E = Result.get();
6583 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6584 // We expect a ConstantExpr to have a value associated with it
6585 // by this point.
6586 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6587 "ConstantExpr has no value associated with it");
6588 (void)CE;
6589 } else {
6590 E = ConstantExpr::Create(Context, Result.get(), Value);
6591 }
6592 if (!PreNarrowingValue.isAbsent())
6593 Value = std::move(PreNarrowingValue);
6594 return E;
6595 }
6596 }
6597
6598 // It's not a constant expression. Produce an appropriate diagnostic.
6599 if (Notes.size() == 1 &&
6600 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6601 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6602 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6603 diag::note_constexpr_invalid_template_arg) {
6604 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6605 for (unsigned I = 0; I < Notes.size(); ++I)
6606 Diag(Notes[I].first, Notes[I].second);
6607 } else {
6608 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6609 << CCE << E->getSourceRange();
6610 for (unsigned I = 0; I < Notes.size(); ++I)
6611 Diag(Notes[I].first, Notes[I].second);
6612 }
6613 return ExprError();
6614 }
6615
6616 /// dropPointerConversions - If the given standard conversion sequence
6617 /// involves any pointer conversions, remove them. This may change
6618 /// the result type of the conversion sequence.
6619 static void dropPointerConversion(StandardConversionSequence &SCS) {
6620 if (SCS.Second == ICK_Pointer_Conversion) {
6621 SCS.Second = ICK_Identity;
6622 SCS.Dimension = ICK_Identity;
6623 SCS.Third = ICK_Identity;
6624 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6625 }
6626 }
6627
6628 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6629 /// convert the expression From to an Objective-C pointer type.
6630 static ImplicitConversionSequence
6631 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6632 // Do an implicit conversion to 'id'.
6633 QualType Ty = S.Context.getObjCIdType();
6634 ImplicitConversionSequence ICS
6635 = TryImplicitConversion(S, From, Ty,
6636 // FIXME: Are these flags correct?
6637 /*SuppressUserConversions=*/false,
6638 AllowedExplicit::Conversions,
6639 /*InOverloadResolution=*/false,
6640 /*CStyle=*/false,
6641 /*AllowObjCWritebackConversion=*/false,
6642 /*AllowObjCConversionOnExplicit=*/true);
6643
6644 // Strip off any final conversions to 'id'.
6645 switch (ICS.getKind()) {
6646 case ImplicitConversionSequence::BadConversion:
6647 case ImplicitConversionSequence::AmbiguousConversion:
6648 case ImplicitConversionSequence::EllipsisConversion:
6649 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6650 break;
6651
6652 case ImplicitConversionSequence::UserDefinedConversion:
6653 dropPointerConversion(ICS.UserDefined.After);
6654 break;
6655
6656 case ImplicitConversionSequence::StandardConversion:
6657 dropPointerConversion(ICS.Standard);
6658 break;
6659 }
6660
6661 return ICS;
6662 }
6663
6664 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6665 if (checkPlaceholderForOverload(*this, From))
6666 return ExprError();
6667
6668 QualType Ty = Context.getObjCIdType();
6669 ImplicitConversionSequence ICS =
6670 TryContextuallyConvertToObjCPointer(*this, From);
6671 if (!ICS.isBad())
6672 return PerformImplicitConversion(From, Ty, ICS,
6673 AssignmentAction::Converting);
6674 return ExprResult();
6675 }
6676
6677 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6678 const Expr *Base = nullptr;
6679 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6680 "expected a member expression");
6681
6682 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6683 M && !M->isImplicitAccess())
6684 Base = M->getBase();
6685 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6686 M && !M->isImplicitAccess())
6687 Base = M->getBase();
6688
6689 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6690
6691 if (T->isPointerType())
6692 T = T->getPointeeType();
6693
6694 return T;
6695 }
6696
6697 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6698 const FunctionDecl *Fun) {
6699 QualType ObjType = Obj->getType();
6700 if (ObjType->isPointerType()) {
6701 ObjType = ObjType->getPointeeType();
6702 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6703 VK_LValue, OK_Ordinary, SourceLocation(),
6704 /*CanOverflow=*/false, FPOptionsOverride());
6705 }
6706 return Obj;
6707 }
6708
6709 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6710 FunctionDecl *Fun) {
6711 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6712 return S.PerformCopyInitialization(
6713 InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)),
6714 Obj->getExprLoc(), Obj);
6715 }
6716
6717 static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6718 Expr *Object, MultiExprArg &Args,
6719 SmallVectorImpl<Expr *> &NewArgs) {
6720 assert(Method->isExplicitObjectMemberFunction() &&
6721 "Method is not an explicit member function");
6722 assert(NewArgs.empty() && "NewArgs should be empty");
6723
6724 NewArgs.reserve(Args.size() + 1);
6725 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6726 NewArgs.push_back(This);
6727 NewArgs.append(Args.begin(), Args.end());
6728 Args = NewArgs;
6729 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6730 Method, Object->getBeginLoc());
6731 }
6732
6733 /// Determine whether the provided type is an integral type, or an enumeration
6734 /// type of a permitted flavor.
6735 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6736 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6737 : T->isIntegralOrUnscopedEnumerationType();
6738 }
6739
6740 static ExprResult
6741 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6742 Sema::ContextualImplicitConverter &Converter,
6743 QualType T, UnresolvedSetImpl &ViableConversions) {
6744
6745 if (Converter.Suppress)
6746 return ExprError();
6747
6748 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6749 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6750 CXXConversionDecl *Conv =
6751 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6752 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6753 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6754 }
6755 return From;
6756 }
6757
6758 static bool
6759 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6760 Sema::ContextualImplicitConverter &Converter,
6761 QualType T, bool HadMultipleCandidates,
6762 UnresolvedSetImpl &ExplicitConversions) {
6763 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6764 DeclAccessPair Found = ExplicitConversions[0];
6765 CXXConversionDecl *Conversion =
6766 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6767
6768 // The user probably meant to invoke the given explicit
6769 // conversion; use it.
6770 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6771 std::string TypeStr;
6772 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6773
6774 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6775 << FixItHint::CreateInsertion(From->getBeginLoc(),
6776 "static_cast<" + TypeStr + ">(")
6777 << FixItHint::CreateInsertion(
6778 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6779 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6780
6781 // If we aren't in a SFINAE context, build a call to the
6782 // explicit conversion function.
6783 if (SemaRef.isSFINAEContext())
6784 return true;
6785
6786 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6787 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6788 HadMultipleCandidates);
6789 if (Result.isInvalid())
6790 return true;
6791
6792 // Replace the conversion with a RecoveryExpr, so we don't try to
6793 // instantiate it later, but can further diagnose here.
6794 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6795 From, Result.get()->getType());
6796 if (Result.isInvalid())
6797 return true;
6798 From = Result.get();
6799 }
6800 return false;
6801 }
6802
6803 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6804 Sema::ContextualImplicitConverter &Converter,
6805 QualType T, bool HadMultipleCandidates,
6806 DeclAccessPair &Found) {
6807 CXXConversionDecl *Conversion =
6808 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6809 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6810
6811 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6812 if (!Converter.SuppressConversion) {
6813 if (SemaRef.isSFINAEContext())
6814 return true;
6815
6816 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6817 << From->getSourceRange();
6818 }
6819
6820 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6821 HadMultipleCandidates);
6822 if (Result.isInvalid())
6823 return true;
6824 // Record usage of conversion in an implicit cast.
6825 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6826 CK_UserDefinedConversion, Result.get(),
6827 nullptr, Result.get()->getValueKind(),
6828 SemaRef.CurFPFeatureOverrides());
6829 return false;
6830 }
6831
6832 static ExprResult finishContextualImplicitConversion(
6833 Sema &SemaRef, SourceLocation Loc, Expr *From,
6834 Sema::ContextualImplicitConverter &Converter) {
6835 if (!Converter.match(From->getType()) && !Converter.Suppress)
6836 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6837 << From->getSourceRange();
6838
6839 return SemaRef.DefaultLvalueConversion(From);
6840 }
6841
6842 static void
6843 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6844 UnresolvedSetImpl &ViableConversions,
6845 OverloadCandidateSet &CandidateSet) {
6846 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6847 NamedDecl *D = FoundDecl.getDecl();
6848 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6849 if (isa<UsingShadowDecl>(D))
6850 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6851
6852 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6853 SemaRef.AddTemplateConversionCandidate(
6854 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6855 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6856 continue;
6857 }
6858 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6859 SemaRef.AddConversionCandidate(
6860 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6861 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6862 }
6863 }
6864
6865 /// Attempt to convert the given expression to a type which is accepted
6866 /// by the given converter.
6867 ///
6868 /// This routine will attempt to convert an expression of class type to a
6869 /// type accepted by the specified converter. In C++11 and before, the class
6870 /// must have a single non-explicit conversion function converting to a matching
6871 /// type. In C++1y, there can be multiple such conversion functions, but only
6872 /// one target type.
6873 ///
6874 /// \param Loc The source location of the construct that requires the
6875 /// conversion.
6876 ///
6877 /// \param From The expression we're converting from.
6878 ///
6879 /// \param Converter Used to control and diagnose the conversion process.
6880 ///
6881 /// \returns The expression, converted to an integral or enumeration type if
6882 /// successful.
6883 ExprResult Sema::PerformContextualImplicitConversion(
6884 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6885 // We can't perform any more checking for type-dependent expressions.
6886 if (From->isTypeDependent())
6887 return From;
6888
6889 // Process placeholders immediately.
6890 if (From->hasPlaceholderType()) {
6891 ExprResult result = CheckPlaceholderExpr(From);
6892 if (result.isInvalid())
6893 return result;
6894 From = result.get();
6895 }
6896
6897 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6898 ExprResult Converted = DefaultLvalueConversion(From);
6899 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6900 // If the expression already has a matching type, we're golden.
6901 if (Converter.match(T))
6902 return Converted;
6903
6904 // FIXME: Check for missing '()' if T is a function type?
6905
6906 // We can only perform contextual implicit conversions on objects of class
6907 // type.
6908 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6909 if (!RecordTy || !getLangOpts().CPlusPlus) {
6910 if (!Converter.Suppress)
6911 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6912 return From;
6913 }
6914
6915 // We must have a complete class type.
6916 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6917 ContextualImplicitConverter &Converter;
6918 Expr *From;
6919
6920 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6921 : Converter(Converter), From(From) {}
6922
6923 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6924 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6925 }
6926 } IncompleteDiagnoser(Converter, From);
6927
6928 if (Converter.Suppress ? !isCompleteType(Loc, T)
6929 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6930 return From;
6931
6932 // Look for a conversion to an integral or enumeration type.
6933 UnresolvedSet<4>
6934 ViableConversions; // These are *potentially* viable in C++1y.
6935 UnresolvedSet<4> ExplicitConversions;
6936 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
6937 ->getDefinitionOrSelf()
6938 ->getVisibleConversionFunctions();
6939
6940 bool HadMultipleCandidates =
6941 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6942
6943 // To check that there is only one target type, in C++1y:
6944 QualType ToType;
6945 bool HasUniqueTargetType = true;
6946
6947 // Collect explicit or viable (potentially in C++1y) conversions.
6948 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6949 NamedDecl *D = (*I)->getUnderlyingDecl();
6950 CXXConversionDecl *Conversion;
6951 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6952 if (ConvTemplate) {
6953 if (getLangOpts().CPlusPlus14)
6954 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6955 else
6956 continue; // C++11 does not consider conversion operator templates(?).
6957 } else
6958 Conversion = cast<CXXConversionDecl>(D);
6959
6960 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6961 "Conversion operator templates are considered potentially "
6962 "viable in C++1y");
6963
6964 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6965 if (Converter.match(CurToType) || ConvTemplate) {
6966
6967 if (Conversion->isExplicit()) {
6968 // FIXME: For C++1y, do we need this restriction?
6969 // cf. diagnoseNoViableConversion()
6970 if (!ConvTemplate)
6971 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6972 } else {
6973 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6974 if (ToType.isNull())
6975 ToType = CurToType.getUnqualifiedType();
6976 else if (HasUniqueTargetType &&
6977 (CurToType.getUnqualifiedType() != ToType))
6978 HasUniqueTargetType = false;
6979 }
6980 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6981 }
6982 }
6983 }
6984
6985 if (getLangOpts().CPlusPlus14) {
6986 // C++1y [conv]p6:
6987 // ... An expression e of class type E appearing in such a context
6988 // is said to be contextually implicitly converted to a specified
6989 // type T and is well-formed if and only if e can be implicitly
6990 // converted to a type T that is determined as follows: E is searched
6991 // for conversion functions whose return type is cv T or reference to
6992 // cv T such that T is allowed by the context. There shall be
6993 // exactly one such T.
6994
6995 // If no unique T is found:
6996 if (ToType.isNull()) {
6997 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6998 HadMultipleCandidates,
6999 ExplicitConversions))
7000 return ExprError();
7001 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7002 }
7003
7004 // If more than one unique Ts are found:
7005 if (!HasUniqueTargetType)
7006 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7007 ViableConversions);
7008
7009 // If one unique T is found:
7010 // First, build a candidate set from the previously recorded
7011 // potentially viable conversions.
7012 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7013 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7014 CandidateSet);
7015
7016 // Then, perform overload resolution over the candidate set.
7017 OverloadCandidateSet::iterator Best;
7018 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7019 case OR_Success: {
7020 // Apply this conversion.
7021 DeclAccessPair Found =
7022 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7023 if (recordConversion(*this, Loc, From, Converter, T,
7024 HadMultipleCandidates, Found))
7025 return ExprError();
7026 break;
7027 }
7028 case OR_Ambiguous:
7029 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7030 ViableConversions);
7031 case OR_No_Viable_Function:
7032 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7033 HadMultipleCandidates,
7034 ExplicitConversions))
7035 return ExprError();
7036 [[fallthrough]];
7037 case OR_Deleted:
7038 // We'll complain below about a non-integral condition type.
7039 break;
7040 }
7041 } else {
7042 switch (ViableConversions.size()) {
7043 case 0: {
7044 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7045 HadMultipleCandidates,
7046 ExplicitConversions))
7047 return ExprError();
7048
7049 // We'll complain below about a non-integral condition type.
7050 break;
7051 }
7052 case 1: {
7053 // Apply this conversion.
7054 DeclAccessPair Found = ViableConversions[0];
7055 if (recordConversion(*this, Loc, From, Converter, T,
7056 HadMultipleCandidates, Found))
7057 return ExprError();
7058 break;
7059 }
7060 default:
7061 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7062 ViableConversions);
7063 }
7064 }
7065
7066 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7067 }
7068
7069 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7070 /// an acceptable non-member overloaded operator for a call whose
7071 /// arguments have types T1 (and, if non-empty, T2). This routine
7072 /// implements the check in C++ [over.match.oper]p3b2 concerning
7073 /// enumeration types.
7074 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7075 FunctionDecl *Fn,
7076 ArrayRef<Expr *> Args) {
7077 QualType T1 = Args[0]->getType();
7078 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7079
7080 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7081 return true;
7082
7083 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7084 return true;
7085
7086 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7087 if (Proto->getNumParams() < 1)
7088 return false;
7089
7090 if (T1->isEnumeralType()) {
7091 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7092 if (Context.hasSameUnqualifiedType(T1, ArgType))
7093 return true;
7094 }
7095
7096 if (Proto->getNumParams() < 2)
7097 return false;
7098
7099 if (!T2.isNull() && T2->isEnumeralType()) {
7100 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7101 if (Context.hasSameUnqualifiedType(T2, ArgType))
7102 return true;
7103 }
7104
7105 return false;
7106 }
7107
7108 static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7109 if (FD->isTargetMultiVersionDefault())
7110 return false;
7111
7112 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7113 return FD->isTargetMultiVersion();
7114
7115 if (!FD->isMultiVersion())
7116 return false;
7117
7118 // Among multiple target versions consider either the default,
7119 // or the first non-default in the absence of default version.
7120 unsigned SeenAt = 0;
7121 unsigned I = 0;
7122 bool HasDefault = false;
7123 FD->getASTContext().forEachMultiversionedFunctionVersion(
7124 FD, [&](const FunctionDecl *CurFD) {
7125 if (FD == CurFD)
7126 SeenAt = I;
7127 else if (CurFD->isTargetMultiVersionDefault())
7128 HasDefault = true;
7129 ++I;
7130 });
7131 return HasDefault || SeenAt != 0;
7132 }
7133
7134 void Sema::AddOverloadCandidate(
7135 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7136 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7137 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7138 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7139 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7140 bool StrictPackMatch) {
7141 const FunctionProtoType *Proto
7142 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7143 assert(Proto && "Functions without a prototype cannot be overloaded");
7144 assert(!Function->getDescribedFunctionTemplate() &&
7145 "Use AddTemplateOverloadCandidate for function templates");
7146
7147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7148 if (!isa<CXXConstructorDecl>(Method)) {
7149 // If we get here, it's because we're calling a member function
7150 // that is named without a member access expression (e.g.,
7151 // "this->f") that was either written explicitly or created
7152 // implicitly. This can happen with a qualified call to a member
7153 // function, e.g., X::f(). We use an empty type for the implied
7154 // object argument (C++ [over.call.func]p3), and the acting context
7155 // is irrelevant.
7156 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7157 Expr::Classification::makeSimpleLValue(), Args,
7158 CandidateSet, SuppressUserConversions,
7159 PartialOverloading, EarlyConversions, PO,
7160 StrictPackMatch);
7161 return;
7162 }
7163 // We treat a constructor like a non-member function, since its object
7164 // argument doesn't participate in overload resolution.
7165 }
7166
7167 if (!CandidateSet.isNewCandidate(Function, PO))
7168 return;
7169
7170 // C++11 [class.copy]p11: [DR1402]
7171 // A defaulted move constructor that is defined as deleted is ignored by
7172 // overload resolution.
7173 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7174 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7175 Constructor->isMoveConstructor())
7176 return;
7177
7178 // Overload resolution is always an unevaluated context.
7179 EnterExpressionEvaluationContext Unevaluated(
7180 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7181
7182 // C++ [over.match.oper]p3:
7183 // if no operand has a class type, only those non-member functions in the
7184 // lookup set that have a first parameter of type T1 or "reference to
7185 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7186 // is a right operand) a second parameter of type T2 or "reference to
7187 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7188 // candidate functions.
7189 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7190 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
7191 return;
7192
7193 // Add this candidate
7194 OverloadCandidate &Candidate =
7195 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7196 Candidate.FoundDecl = FoundDecl;
7197 Candidate.Function = Function;
7198 Candidate.Viable = true;
7199 Candidate.RewriteKind =
7200 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7201 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7202 Candidate.ExplicitCallArguments = Args.size();
7203 Candidate.StrictPackMatch = StrictPackMatch;
7204
7205 // Explicit functions are not actually candidates at all if we're not
7206 // allowing them in this context, but keep them around so we can point
7207 // to them in diagnostics.
7208 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7209 Candidate.Viable = false;
7210 Candidate.FailureKind = ovl_fail_explicit;
7211 return;
7212 }
7213
7214 // Functions with internal linkage are only viable in the same module unit.
7215 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7216 /// FIXME: Currently, the semantics of linkage in clang is slightly
7217 /// different from the semantics in C++ spec. In C++ spec, only names
7218 /// have linkage. So that all entities of the same should share one
7219 /// linkage. But in clang, different entities of the same could have
7220 /// different linkage.
7221 const NamedDecl *ND = Function;
7222 bool IsImplicitlyInstantiated = false;
7223 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7224 ND = SpecInfo->getTemplate();
7225 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7226 TSK_ImplicitInstantiation;
7227 }
7228
7229 /// Don't remove inline functions with internal linkage from the overload
7230 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7231 /// However:
7232 /// - Inline functions with internal linkage are a common pattern in
7233 /// headers to avoid ODR issues.
7234 /// - The global module is meant to be a transition mechanism for C and C++
7235 /// headers, and the current rules as written work against that goal.
7236 const bool IsInlineFunctionInGMF =
7237 Function->isFromGlobalModule() &&
7238 (IsImplicitlyInstantiated || Function->isInlined());
7239
7240 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7241 Candidate.Viable = false;
7242 Candidate.FailureKind = ovl_fail_module_mismatched;
7243 return;
7244 }
7245 }
7246
7247 if (isNonViableMultiVersionOverload(Function)) {
7248 Candidate.Viable = false;
7249 Candidate.FailureKind = ovl_non_default_multiversion_function;
7250 return;
7251 }
7252
7253 if (Constructor) {
7254 // C++ [class.copy]p3:
7255 // A member function template is never instantiated to perform the copy
7256 // of a class object to an object of its class type.
7257 CanQualType ClassType =
7258 Context.getCanonicalTagType(Constructor->getParent());
7259 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7260 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7261 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7262 ClassType))) {
7263 Candidate.Viable = false;
7264 Candidate.FailureKind = ovl_fail_illegal_constructor;
7265 return;
7266 }
7267
7268 // C++ [over.match.funcs]p8: (proposed DR resolution)
7269 // A constructor inherited from class type C that has a first parameter
7270 // of type "reference to P" (including such a constructor instantiated
7271 // from a template) is excluded from the set of candidate functions when
7272 // constructing an object of type cv D if the argument list has exactly
7273 // one argument and D is reference-related to P and P is reference-related
7274 // to C.
7275 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7276 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7277 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7278 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7279 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7280 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7281 SourceLocation Loc = Args.front()->getExprLoc();
7282 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7283 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7284 Candidate.Viable = false;
7285 Candidate.FailureKind = ovl_fail_inhctor_slice;
7286 return;
7287 }
7288 }
7289
7290 // Check that the constructor is capable of constructing an object in the
7291 // destination address space.
7292 if (!Qualifiers::isAddressSpaceSupersetOf(
7293 Constructor->getMethodQualifiers().getAddressSpace(),
7294 CandidateSet.getDestAS(), getASTContext())) {
7295 Candidate.Viable = false;
7296 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7297 }
7298 }
7299
7300 unsigned NumParams = Proto->getNumParams();
7301
7302 // (C++ 13.3.2p2): A candidate function having fewer than m
7303 // parameters is viable only if it has an ellipsis in its parameter
7304 // list (8.3.5).
7305 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7306 !Proto->isVariadic() &&
7307 shouldEnforceArgLimit(PartialOverloading, Function)) {
7308 Candidate.Viable = false;
7309 Candidate.FailureKind = ovl_fail_too_many_arguments;
7310 return;
7311 }
7312
7313 // (C++ 13.3.2p2): A candidate function having more than m parameters
7314 // is viable only if the (m+1)st parameter has a default argument
7315 // (8.3.6). For the purposes of overload resolution, the
7316 // parameter list is truncated on the right, so that there are
7317 // exactly m parameters.
7318 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7319 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7320 !PartialOverloading) {
7321 // Not enough arguments.
7322 Candidate.Viable = false;
7323 Candidate.FailureKind = ovl_fail_too_few_arguments;
7324 return;
7325 }
7326
7327 // (CUDA B.1): Check for invalid calls between targets.
7328 if (getLangOpts().CUDA) {
7329 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7330 // Skip the check for callers that are implicit members, because in this
7331 // case we may not yet know what the member's target is; the target is
7332 // inferred for the member automatically, based on the bases and fields of
7333 // the class.
7334 if (!(Caller && Caller->isImplicit()) &&
7335 !CUDA().IsAllowedCall(Caller, Function)) {
7336 Candidate.Viable = false;
7337 Candidate.FailureKind = ovl_fail_bad_target;
7338 return;
7339 }
7340 }
7341
7342 if (Function->getTrailingRequiresClause()) {
7343 ConstraintSatisfaction Satisfaction;
7344 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7345 /*ForOverloadResolution*/ true) ||
7346 !Satisfaction.IsSatisfied) {
7347 Candidate.Viable = false;
7348 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7349 return;
7350 }
7351 }
7352
7353 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7354 // Determine the implicit conversion sequences for each of the
7355 // arguments.
7356 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7357 unsigned ConvIdx =
7358 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7359 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7360 // We already formed a conversion sequence for this parameter during
7361 // template argument deduction.
7362 } else if (ArgIdx < NumParams) {
7363 // (C++ 13.3.2p3): for F to be a viable function, there shall
7364 // exist for each argument an implicit conversion sequence
7365 // (13.3.3.1) that converts that argument to the corresponding
7366 // parameter of F.
7367 QualType ParamType = Proto->getParamType(ArgIdx);
7368 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7369 if (ParamABI == ParameterABI::HLSLOut ||
7370 ParamABI == ParameterABI::HLSLInOut)
7371 ParamType = ParamType.getNonReferenceType();
7372 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7373 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7374 /*InOverloadResolution=*/true,
7375 /*AllowObjCWritebackConversion=*/
7376 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7377 if (Candidate.Conversions[ConvIdx].isBad()) {
7378 Candidate.Viable = false;
7379 Candidate.FailureKind = ovl_fail_bad_conversion;
7380 return;
7381 }
7382 } else {
7383 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7384 // argument for which there is no corresponding parameter is
7385 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7386 Candidate.Conversions[ConvIdx].setEllipsis();
7387 }
7388 }
7389
7390 if (EnableIfAttr *FailedAttr =
7391 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7392 Candidate.Viable = false;
7393 Candidate.FailureKind = ovl_fail_enable_if;
7394 Candidate.DeductionFailure.Data = FailedAttr;
7395 return;
7396 }
7397 }
7398
7399 ObjCMethodDecl *
7400 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7401 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7402 if (Methods.size() <= 1)
7403 return nullptr;
7404
7405 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7406 bool Match = true;
7407 ObjCMethodDecl *Method = Methods[b];
7408 unsigned NumNamedArgs = Sel.getNumArgs();
7409 // Method might have more arguments than selector indicates. This is due
7410 // to addition of c-style arguments in method.
7411 if (Method->param_size() > NumNamedArgs)
7412 NumNamedArgs = Method->param_size();
7413 if (Args.size() < NumNamedArgs)
7414 continue;
7415
7416 for (unsigned i = 0; i < NumNamedArgs; i++) {
7417 // We can't do any type-checking on a type-dependent argument.
7418 if (Args[i]->isTypeDependent()) {
7419 Match = false;
7420 break;
7421 }
7422
7423 ParmVarDecl *param = Method->parameters()[i];
7424 Expr *argExpr = Args[i];
7425 assert(argExpr && "SelectBestMethod(): missing expression");
7426
7427 // Strip the unbridged-cast placeholder expression off unless it's
7428 // a consumed argument.
7429 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7430 !param->hasAttr<CFConsumedAttr>())
7431 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7432
7433 // If the parameter is __unknown_anytype, move on to the next method.
7434 if (param->getType() == Context.UnknownAnyTy) {
7435 Match = false;
7436 break;
7437 }
7438
7439 ImplicitConversionSequence ConversionState
7440 = TryCopyInitialization(*this, argExpr, param->getType(),
7441 /*SuppressUserConversions*/false,
7442 /*InOverloadResolution=*/true,
7443 /*AllowObjCWritebackConversion=*/
7444 getLangOpts().ObjCAutoRefCount,
7445 /*AllowExplicit*/false);
7446 // This function looks for a reasonably-exact match, so we consider
7447 // incompatible pointer conversions to be a failure here.
7448 if (ConversionState.isBad() ||
7449 (ConversionState.isStandard() &&
7450 ConversionState.Standard.Second ==
7451 ICK_Incompatible_Pointer_Conversion)) {
7452 Match = false;
7453 break;
7454 }
7455 }
7456 // Promote additional arguments to variadic methods.
7457 if (Match && Method->isVariadic()) {
7458 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7459 if (Args[i]->isTypeDependent()) {
7460 Match = false;
7461 break;
7462 }
7463 ExprResult Arg = DefaultVariadicArgumentPromotion(
7464 Args[i], VariadicCallType::Method, nullptr);
7465 if (Arg.isInvalid()) {
7466 Match = false;
7467 break;
7468 }
7469 }
7470 } else {
7471 // Check for extra arguments to non-variadic methods.
7472 if (Args.size() != NumNamedArgs)
7473 Match = false;
7474 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7475 // Special case when selectors have no argument. In this case, select
7476 // one with the most general result type of 'id'.
7477 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7478 QualType ReturnT = Methods[b]->getReturnType();
7479 if (ReturnT->isObjCIdType())
7480 return Methods[b];
7481 }
7482 }
7483 }
7484
7485 if (Match)
7486 return Method;
7487 }
7488 return nullptr;
7489 }
7490
7491 static bool convertArgsForAvailabilityChecks(
7492 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7493 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7494 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7495 if (ThisArg) {
7496 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7497 assert(!isa<CXXConstructorDecl>(Method) &&
7498 "Shouldn't have `this` for ctors!");
7499 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7500 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7501 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7502 if (R.isInvalid())
7503 return false;
7504 ConvertedThis = R.get();
7505 } else {
7506 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7507 (void)MD;
7508 assert((MissingImplicitThis || MD->isStatic() ||
7509 isa<CXXConstructorDecl>(MD)) &&
7510 "Expected `this` for non-ctor instance methods");
7511 }
7512 ConvertedThis = nullptr;
7513 }
7514
7515 // Ignore any variadic arguments. Converting them is pointless, since the
7516 // user can't refer to them in the function condition.
7517 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7518
7519 // Convert the arguments.
7520 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7521 ExprResult R;
7522 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
7523 S.Context, Function->getParamDecl(I)),
7524 SourceLocation(), Args[I]);
7525
7526 if (R.isInvalid())
7527 return false;
7528
7529 ConvertedArgs.push_back(R.get());
7530 }
7531
7532 if (Trap.hasErrorOccurred())
7533 return false;
7534
7535 // Push default arguments if needed.
7536 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7537 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7538 ParmVarDecl *P = Function->getParamDecl(i);
7539 if (!P->hasDefaultArg())
7540 return false;
7541 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7542 if (R.isInvalid())
7543 return false;
7544 ConvertedArgs.push_back(R.get());
7545 }
7546
7547 if (Trap.hasErrorOccurred())
7548 return false;
7549 }
7550 return true;
7551 }
7552
7553 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7554 SourceLocation CallLoc,
7555 ArrayRef<Expr *> Args,
7556 bool MissingImplicitThis) {
7557 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7558 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7559 return nullptr;
7560
7561 SFINAETrap Trap(*this);
7562 SmallVector<Expr *, 16> ConvertedArgs;
7563 // FIXME: We should look into making enable_if late-parsed.
7564 Expr *DiscardedThis;
7565 if (!convertArgsForAvailabilityChecks(
7566 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7567 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7568 return *EnableIfAttrs.begin();
7569
7570 for (auto *EIA : EnableIfAttrs) {
7571 APValue Result;
7572 // FIXME: This doesn't consider value-dependent cases, because doing so is
7573 // very difficult. Ideally, we should handle them more gracefully.
7574 if (EIA->getCond()->isValueDependent() ||
7575 !EIA->getCond()->EvaluateWithSubstitution(
7576 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7577 return EIA;
7578
7579 if (!Result.isInt() || !Result.getInt().getBoolValue())
7580 return EIA;
7581 }
7582 return nullptr;
7583 }
7584
7585 template <typename CheckFn>
7586 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7587 bool ArgDependent, SourceLocation Loc,
7588 CheckFn &&IsSuccessful) {
7589 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7590 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7591 if (ArgDependent == DIA->getArgDependent())
7592 Attrs.push_back(DIA);
7593 }
7594
7595 // Common case: No diagnose_if attributes, so we can quit early.
7596 if (Attrs.empty())
7597 return false;
7598
7599 auto WarningBegin = std::stable_partition(
7600 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7601 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7602 DIA->getWarningGroup().empty();
7603 });
7604
7605 // Note that diagnose_if attributes are late-parsed, so they appear in the
7606 // correct order (unlike enable_if attributes).
7607 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7608 IsSuccessful);
7609 if (ErrAttr != WarningBegin) {
7610 const DiagnoseIfAttr *DIA = *ErrAttr;
7611 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7612 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7613 << DIA->getParent() << DIA->getCond()->getSourceRange();
7614 return true;
7615 }
7616
7617 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7618 switch (Sev) {
7619 case DiagnoseIfAttr::DS_warning:
7620 return diag::Severity::Warning;
7621 case DiagnoseIfAttr::DS_error:
7622 return diag::Severity::Error;
7623 }
7624 llvm_unreachable("Fully covered switch above!");
7625 };
7626
7627 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7628 if (IsSuccessful(DIA)) {
7629 if (DIA->getWarningGroup().empty() &&
7630 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7631 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7632 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7633 << DIA->getParent() << DIA->getCond()->getSourceRange();
7634 } else {
7635 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7636 DIA->getWarningGroup());
7637 assert(DiagGroup);
7638 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7639 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7640 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7641 S.Diag(Loc, DiagID) << DIA->getMessage();
7642 }
7643 }
7644
7645 return false;
7646 }
7647
7648 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7649 const Expr *ThisArg,
7650 ArrayRef<const Expr *> Args,
7651 SourceLocation Loc) {
7652 return diagnoseDiagnoseIfAttrsWith(
7653 *this, Function, /*ArgDependent=*/true, Loc,
7654 [&](const DiagnoseIfAttr *DIA) {
7655 APValue Result;
7656 // It's sane to use the same Args for any redecl of this function, since
7657 // EvaluateWithSubstitution only cares about the position of each
7658 // argument in the arg list, not the ParmVarDecl* it maps to.
7659 if (!DIA->getCond()->EvaluateWithSubstitution(
7660 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7661 return false;
7662 return Result.isInt() && Result.getInt().getBoolValue();
7663 });
7664 }
7665
7666 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7667 SourceLocation Loc) {
7668 return diagnoseDiagnoseIfAttrsWith(
7669 *this, ND, /*ArgDependent=*/false, Loc,
7670 [&](const DiagnoseIfAttr *DIA) {
7671 bool Result;
7672 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7673 Result;
7674 });
7675 }
7676
7677 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7678 ArrayRef<Expr *> Args,
7679 OverloadCandidateSet &CandidateSet,
7680 TemplateArgumentListInfo *ExplicitTemplateArgs,
7681 bool SuppressUserConversions,
7682 bool PartialOverloading,
7683 bool FirstArgumentIsBase) {
7684 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7685 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7686 ArrayRef<Expr *> FunctionArgs = Args;
7687
7688 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7689 FunctionDecl *FD =
7690 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7691
7692 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7693 QualType ObjectType;
7694 Expr::Classification ObjectClassification;
7695 if (Args.size() > 0) {
7696 if (Expr *E = Args[0]) {
7697 // Use the explicit base to restrict the lookup:
7698 ObjectType = E->getType();
7699 // Pointers in the object arguments are implicitly dereferenced, so we
7700 // always classify them as l-values.
7701 if (!ObjectType.isNull() && ObjectType->isPointerType())
7702 ObjectClassification = Expr::Classification::makeSimpleLValue();
7703 else
7704 ObjectClassification = E->Classify(Context);
7705 } // .. else there is an implicit base.
7706 FunctionArgs = Args.slice(1);
7707 }
7708 if (FunTmpl) {
7709 AddMethodTemplateCandidate(
7710 FunTmpl, F.getPair(),
7711 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7712 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7713 FunctionArgs, CandidateSet, SuppressUserConversions,
7714 PartialOverloading);
7715 } else {
7716 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7717 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7718 ObjectClassification, FunctionArgs, CandidateSet,
7719 SuppressUserConversions, PartialOverloading);
7720 }
7721 } else {
7722 // This branch handles both standalone functions and static methods.
7723
7724 // Slice the first argument (which is the base) when we access
7725 // static method as non-static.
7726 if (Args.size() > 0 &&
7727 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7728 !isa<CXXConstructorDecl>(FD)))) {
7729 assert(cast<CXXMethodDecl>(FD)->isStatic());
7730 FunctionArgs = Args.slice(1);
7731 }
7732 if (FunTmpl) {
7733 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7734 ExplicitTemplateArgs, FunctionArgs,
7735 CandidateSet, SuppressUserConversions,
7736 PartialOverloading);
7737 } else {
7738 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7739 SuppressUserConversions, PartialOverloading);
7740 }
7741 }
7742 }
7743 }
7744
7745 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7746 Expr::Classification ObjectClassification,
7747 ArrayRef<Expr *> Args,
7748 OverloadCandidateSet &CandidateSet,
7749 bool SuppressUserConversions,
7750 OverloadCandidateParamOrder PO) {
7751 NamedDecl *Decl = FoundDecl.getDecl();
7752 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7753
7754 if (isa<UsingShadowDecl>(Decl))
7755 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7756
7757 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7758 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7759 "Expected a member function template");
7760 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7761 /*ExplicitArgs*/ nullptr, ObjectType,
7762 ObjectClassification, Args, CandidateSet,
7763 SuppressUserConversions, false, PO);
7764 } else {
7765 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7766 ObjectType, ObjectClassification, Args, CandidateSet,
7767 SuppressUserConversions, false, {}, PO);
7768 }
7769 }
7770
7771 void Sema::AddMethodCandidate(
7772 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7773 CXXRecordDecl *ActingContext, QualType ObjectType,
7774 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7775 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7776 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7777 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7778 const FunctionProtoType *Proto
7779 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7780 assert(Proto && "Methods without a prototype cannot be overloaded");
7781 assert(!isa<CXXConstructorDecl>(Method) &&
7782 "Use AddOverloadCandidate for constructors");
7783
7784 if (!CandidateSet.isNewCandidate(Method, PO))
7785 return;
7786
7787 // C++11 [class.copy]p23: [DR1402]
7788 // A defaulted move assignment operator that is defined as deleted is
7789 // ignored by overload resolution.
7790 if (Method->isDefaulted() && Method->isDeleted() &&
7791 Method->isMoveAssignmentOperator())
7792 return;
7793
7794 // Overload resolution is always an unevaluated context.
7795 EnterExpressionEvaluationContext Unevaluated(
7796 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7797
7798 bool IgnoreExplicitObject =
7799 (Method->isExplicitObjectMemberFunction() &&
7800 CandidateSet.getKind() ==
7801 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7802 bool ImplicitObjectMethodTreatedAsStatic =
7803 CandidateSet.getKind() ==
7804 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7805 Method->isImplicitObjectMemberFunction();
7806
7807 unsigned ExplicitOffset =
7808 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7809
7810 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7811 int(ImplicitObjectMethodTreatedAsStatic);
7812
7813 unsigned ExtraArgs =
7814 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7815 ? 0
7816 : 1;
7817
7818 // Add this candidate
7819 OverloadCandidate &Candidate =
7820 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7821 Candidate.FoundDecl = FoundDecl;
7822 Candidate.Function = Method;
7823 Candidate.RewriteKind =
7824 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7825 Candidate.TookAddressOfOverload =
7826 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7827 Candidate.ExplicitCallArguments = Args.size();
7828 Candidate.StrictPackMatch = StrictPackMatch;
7829
7830 // (C++ 13.3.2p2): A candidate function having fewer than m
7831 // parameters is viable only if it has an ellipsis in its parameter
7832 // list (8.3.5).
7833 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7834 !Proto->isVariadic() &&
7835 shouldEnforceArgLimit(PartialOverloading, Method)) {
7836 Candidate.Viable = false;
7837 Candidate.FailureKind = ovl_fail_too_many_arguments;
7838 return;
7839 }
7840
7841 // (C++ 13.3.2p2): A candidate function having more than m parameters
7842 // is viable only if the (m+1)st parameter has a default argument
7843 // (8.3.6). For the purposes of overload resolution, the
7844 // parameter list is truncated on the right, so that there are
7845 // exactly m parameters.
7846 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7847 ExplicitOffset +
7848 int(ImplicitObjectMethodTreatedAsStatic);
7849
7850 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7851 // Not enough arguments.
7852 Candidate.Viable = false;
7853 Candidate.FailureKind = ovl_fail_too_few_arguments;
7854 return;
7855 }
7856
7857 Candidate.Viable = true;
7858
7859 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7860 if (!IgnoreExplicitObject) {
7861 if (ObjectType.isNull())
7862 Candidate.IgnoreObjectArgument = true;
7863 else if (Method->isStatic()) {
7864 // [over.best.ics.general]p8
7865 // When the parameter is the implicit object parameter of a static member
7866 // function, the implicit conversion sequence is a standard conversion
7867 // sequence that is neither better nor worse than any other standard
7868 // conversion sequence.
7869 //
7870 // This is a rule that was introduced in C++23 to support static lambdas.
7871 // We apply it retroactively because we want to support static lambdas as
7872 // an extension and it doesn't hurt previous code.
7873 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7874 } else {
7875 // Determine the implicit conversion sequence for the object
7876 // parameter.
7877 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7878 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7879 Method, ActingContext, /*InOverloadResolution=*/true);
7880 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7881 Candidate.Viable = false;
7882 Candidate.FailureKind = ovl_fail_bad_conversion;
7883 return;
7884 }
7885 }
7886 }
7887
7888 // (CUDA B.1): Check for invalid calls between targets.
7889 if (getLangOpts().CUDA)
7890 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7891 Method)) {
7892 Candidate.Viable = false;
7893 Candidate.FailureKind = ovl_fail_bad_target;
7894 return;
7895 }
7896
7897 if (Method->getTrailingRequiresClause()) {
7898 ConstraintSatisfaction Satisfaction;
7899 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7900 /*ForOverloadResolution*/ true) ||
7901 !Satisfaction.IsSatisfied) {
7902 Candidate.Viable = false;
7903 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7904 return;
7905 }
7906 }
7907
7908 // Determine the implicit conversion sequences for each of the
7909 // arguments.
7910 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7911 unsigned ConvIdx =
7912 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7913 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7914 // We already formed a conversion sequence for this parameter during
7915 // template argument deduction.
7916 } else if (ArgIdx < NumParams) {
7917 // (C++ 13.3.2p3): for F to be a viable function, there shall
7918 // exist for each argument an implicit conversion sequence
7919 // (13.3.3.1) that converts that argument to the corresponding
7920 // parameter of F.
7921 QualType ParamType;
7922 if (ImplicitObjectMethodTreatedAsStatic) {
7923 ParamType = ArgIdx == 0
7924 ? Method->getFunctionObjectParameterReferenceType()
7925 : Proto->getParamType(ArgIdx - 1);
7926 } else {
7927 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7928 }
7929 Candidate.Conversions[ConvIdx]
7930 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7931 SuppressUserConversions,
7932 /*InOverloadResolution=*/true,
7933 /*AllowObjCWritebackConversion=*/
7934 getLangOpts().ObjCAutoRefCount);
7935 if (Candidate.Conversions[ConvIdx].isBad()) {
7936 Candidate.Viable = false;
7937 Candidate.FailureKind = ovl_fail_bad_conversion;
7938 return;
7939 }
7940 } else {
7941 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7942 // argument for which there is no corresponding parameter is
7943 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7944 Candidate.Conversions[ConvIdx].setEllipsis();
7945 }
7946 }
7947
7948 if (EnableIfAttr *FailedAttr =
7949 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7950 Candidate.Viable = false;
7951 Candidate.FailureKind = ovl_fail_enable_if;
7952 Candidate.DeductionFailure.Data = FailedAttr;
7953 return;
7954 }
7955
7956 if (isNonViableMultiVersionOverload(Method)) {
7957 Candidate.Viable = false;
7958 Candidate.FailureKind = ovl_non_default_multiversion_function;
7959 }
7960 }
7961
7962 static void AddMethodTemplateCandidateImmediately(
7963 Sema &S, OverloadCandidateSet &CandidateSet,
7964 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7965 CXXRecordDecl *ActingContext,
7966 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7967 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7968 bool SuppressUserConversions, bool PartialOverloading,
7969 OverloadCandidateParamOrder PO) {
7970
7971 // C++ [over.match.funcs]p7:
7972 // In each case where a candidate is a function template, candidate
7973 // function template specializations are generated using template argument
7974 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7975 // candidate functions in the usual way.113) A given name can refer to one
7976 // or more function templates and also to a set of overloaded non-template
7977 // functions. In such a case, the candidate functions generated from each
7978 // function template are combined with the set of non-template candidate
7979 // functions.
7980 TemplateDeductionInfo Info(CandidateSet.getLocation());
7981 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7982 FunctionDecl *Specialization = nullptr;
7983 ConversionSequenceList Conversions;
7984 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
7985 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7986 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7987 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7988 CandidateSet.getKind() ==
7989 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
7990 [&](ArrayRef<QualType> ParamTypes,
7991 bool OnlyInitializeNonUserDefinedConversions) {
7992 return S.CheckNonDependentConversions(
7993 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7994 Sema::CheckNonDependentConversionsFlag(
7995 SuppressUserConversions,
7996 OnlyInitializeNonUserDefinedConversions),
7997 ActingContext, ObjectType, ObjectClassification, PO);
7998 });
7999 Result != TemplateDeductionResult::Success) {
8000 OverloadCandidate &Candidate =
8001 CandidateSet.addCandidate(Conversions.size(), Conversions);
8002 Candidate.FoundDecl = FoundDecl;
8003 Candidate.Function = Method;
8004 Candidate.Viable = false;
8005 Candidate.RewriteKind =
8006 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8007 Candidate.IsSurrogate = false;
8008 Candidate.TookAddressOfOverload =
8009 CandidateSet.getKind() ==
8010 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8011
8012 Candidate.IgnoreObjectArgument =
8013 Method->isStatic() ||
8014 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8015 Candidate.ExplicitCallArguments = Args.size();
8016 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8017 Candidate.FailureKind = ovl_fail_bad_conversion;
8018 else {
8019 Candidate.FailureKind = ovl_fail_bad_deduction;
8020 Candidate.DeductionFailure =
8021 MakeDeductionFailureInfo(S.Context, Result, Info);
8022 }
8023 return;
8024 }
8025
8026 // Add the function template specialization produced by template argument
8027 // deduction as a candidate.
8028 assert(Specialization && "Missing member function template specialization?");
8029 assert(isa<CXXMethodDecl>(Specialization) &&
8030 "Specialization is not a member function?");
8031 S.AddMethodCandidate(
8032 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8033 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8034 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8035 }
8036
8037 void Sema::AddMethodTemplateCandidate(
8038 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8039 CXXRecordDecl *ActingContext,
8040 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8041 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8042 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8043 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8044 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8045 return;
8046
8047 if (ExplicitTemplateArgs ||
8048 !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts())) {
8049 AddMethodTemplateCandidateImmediately(
8050 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8051 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8052 SuppressUserConversions, PartialOverloading, PO);
8053 return;
8054 }
8055
8056 CandidateSet.AddDeferredMethodTemplateCandidate(
8057 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8058 Args, SuppressUserConversions, PartialOverloading, PO);
8059 }
8060
8061 /// Determine whether a given function template has a simple explicit specifier
8062 /// or a non-value-dependent explicit-specification that evaluates to true.
8063 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8064 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
8065 }
8066
8067 static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8068 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).getKind() ==
8069 ExplicitSpecKind::Unresolved;
8070 }
8071
8072 static void AddTemplateOverloadCandidateImmediately(
8073 Sema &S, OverloadCandidateSet &CandidateSet,
8074 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8075 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8076 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8077 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8078 bool AggregateCandidateDeduction) {
8079
8080 // If the function template has a non-dependent explicit specification,
8081 // exclude it now if appropriate; we are not permitted to perform deduction
8082 // and substitution in this case.
8083 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8084 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8085 Candidate.FoundDecl = FoundDecl;
8086 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8087 Candidate.Viable = false;
8088 Candidate.FailureKind = ovl_fail_explicit;
8089 return;
8090 }
8091
8092 // C++ [over.match.funcs]p7:
8093 // In each case where a candidate is a function template, candidate
8094 // function template specializations are generated using template argument
8095 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8096 // candidate functions in the usual way.113) A given name can refer to one
8097 // or more function templates and also to a set of overloaded non-template
8098 // functions. In such a case, the candidate functions generated from each
8099 // function template are combined with the set of non-template candidate
8100 // functions.
8101 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8102 FunctionTemplate->getTemplateDepth());
8103 FunctionDecl *Specialization = nullptr;
8104 ConversionSequenceList Conversions;
8105 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8106 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8107 PartialOverloading, AggregateCandidateDeduction,
8108 /*PartialOrdering=*/false,
8109 /*ObjectType=*/QualType(),
8110 /*ObjectClassification=*/Expr::Classification(),
8111 CandidateSet.getKind() ==
8112 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8113 [&](ArrayRef<QualType> ParamTypes,
8114 bool OnlyInitializeNonUserDefinedConversions) {
8115 return S.CheckNonDependentConversions(
8116 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8117 Sema::CheckNonDependentConversionsFlag(
8118 SuppressUserConversions,
8119 OnlyInitializeNonUserDefinedConversions),
8120 nullptr, QualType(), {}, PO);
8121 });
8122 Result != TemplateDeductionResult::Success) {
8123 OverloadCandidate &Candidate =
8124 CandidateSet.addCandidate(Conversions.size(), Conversions);
8125 Candidate.FoundDecl = FoundDecl;
8126 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8127 Candidate.Viable = false;
8128 Candidate.RewriteKind =
8129 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8130 Candidate.IsSurrogate = false;
8131 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8132 // Ignore the object argument if there is one, since we don't have an object
8133 // type.
8134 Candidate.TookAddressOfOverload =
8135 CandidateSet.getKind() ==
8136 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8137
8138 Candidate.IgnoreObjectArgument =
8139 isa<CXXMethodDecl>(Candidate.Function) &&
8140 !cast<CXXMethodDecl>(Candidate.Function)
8141 ->isExplicitObjectMemberFunction() &&
8142 !isa<CXXConstructorDecl>(Candidate.Function);
8143
8144 Candidate.ExplicitCallArguments = Args.size();
8145 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8146 Candidate.FailureKind = ovl_fail_bad_conversion;
8147 else {
8148 Candidate.FailureKind = ovl_fail_bad_deduction;
8149 Candidate.DeductionFailure =
8150 MakeDeductionFailureInfo(S.Context, Result, Info);
8151 }
8152 return;
8153 }
8154
8155 // Add the function template specialization produced by template argument
8156 // deduction as a candidate.
8157 assert(Specialization && "Missing function template specialization?");
8158 S.AddOverloadCandidate(
8159 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8160 PartialOverloading, AllowExplicit,
8161 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8162 Info.AggregateDeductionCandidateHasMismatchedArity,
8163 Info.hasStrictPackMatch());
8164 }
8165
8166 void Sema::AddTemplateOverloadCandidate(
8167 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8168 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8169 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8170 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8171 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8172 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8173 return;
8174
8175 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8176
8177 if (ExplicitTemplateArgs ||
8178 !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||
8179 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8180 DependentExplicitSpecifier)) {
8181
8182 AddTemplateOverloadCandidateImmediately(
8183 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8184 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8185 IsADLCandidate, PO, AggregateCandidateDeduction);
8186
8187 if (DependentExplicitSpecifier)
8188 CandidateSet.DisableResolutionByPerfectCandidate();
8189 return;
8190 }
8191
8192 CandidateSet.AddDeferredTemplateCandidate(
8193 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8194 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8195 AggregateCandidateDeduction);
8196 }
8197
8198 bool Sema::CheckNonDependentConversions(
8199 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8200 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8201 ConversionSequenceList &Conversions,
8202 CheckNonDependentConversionsFlag UserConversionFlag,
8203 CXXRecordDecl *ActingContext, QualType ObjectType,
8204 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8205 // FIXME: The cases in which we allow explicit conversions for constructor
8206 // arguments never consider calling a constructor template. It's not clear
8207 // that is correct.
8208 const bool AllowExplicit = false;
8209
8210 bool ForOverloadSetAddressResolution =
8211 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8212 auto *FD = FunctionTemplate->getTemplatedDecl();
8213 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8214 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8215 !isa<CXXConstructorDecl>(Method);
8216 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8217
8218 if (Conversions.empty())
8219 Conversions =
8220 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8221
8222 // Overload resolution is always an unevaluated context.
8223 EnterExpressionEvaluationContext Unevaluated(
8224 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8225
8226 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8227 // require that, but this check should never result in a hard error, and
8228 // overload resolution is permitted to sidestep instantiations.
8229 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8230 !ObjectType.isNull()) {
8231 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8232 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8233 !ParamTypes[0]->isDependentType()) {
8234 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8235 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8236 Method, ActingContext, /*InOverloadResolution=*/true,
8237 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8238 : QualType());
8239 if (Conversions[ConvIdx].isBad())
8240 return true;
8241 }
8242 }
8243
8244 // A speculative workaround for self-dependent constraint bugs that manifest
8245 // after CWG2369.
8246 // FIXME: Add references to the standard once P3606 is adopted.
8247 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8248 QualType ArgType) {
8249 ParamType = ParamType.getNonReferenceType();
8250 ArgType = ArgType.getNonReferenceType();
8251 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8252 if (PointerConv) {
8253 ParamType = ParamType->getPointeeType();
8254 ArgType = ArgType->getPointeeType();
8255 }
8256
8257 if (auto *RD = ParamType->getAsCXXRecordDecl();
8258 RD && RD->hasDefinition() &&
8259 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8260 auto Info = getConstructorInfo(ND);
8261 if (!Info)
8262 return false;
8263 CXXConstructorDecl *Ctor = Info.Constructor;
8264 /// isConvertingConstructor takes copy/move constructors into
8265 /// account!
8266 return !Ctor->isCopyOrMoveConstructor() &&
8267 Ctor->isConvertingConstructor(
8268 /*AllowExplicit=*/true);
8269 }))
8270 return true;
8271 if (auto *RD = ArgType->getAsCXXRecordDecl();
8272 RD && RD->hasDefinition() &&
8273 !RD->getVisibleConversionFunctions().empty())
8274 return true;
8275
8276 return false;
8277 };
8278
8279 unsigned Offset =
8280 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8281 : 0;
8282
8283 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8284 I != N; ++I) {
8285 QualType ParamType = ParamTypes[I + Offset];
8286 if (!ParamType->isDependentType()) {
8287 unsigned ConvIdx;
8288 if (PO == OverloadCandidateParamOrder::Reversed) {
8289 ConvIdx = Args.size() - 1 - I;
8290 assert(Args.size() + ThisConversions == 2 &&
8291 "number of args (including 'this') must be exactly 2 for "
8292 "reversed order");
8293 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8294 // would also be 0. 'this' got ConvIdx = 1 previously.
8295 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8296 } else {
8297 // For members, 'this' got ConvIdx = 0 previously.
8298 ConvIdx = ThisConversions + I;
8299 }
8300 if (Conversions[ConvIdx].isInitialized())
8301 continue;
8302 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8303 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8304 continue;
8305 Conversions[ConvIdx] = TryCopyInitialization(
8306 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8307 /*InOverloadResolution=*/true,
8308 /*AllowObjCWritebackConversion=*/
8309 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8310 if (Conversions[ConvIdx].isBad())
8311 return true;
8312 }
8313 }
8314
8315 return false;
8316 }
8317
8318 /// Determine whether this is an allowable conversion from the result
8319 /// of an explicit conversion operator to the expected type, per C++
8320 /// [over.match.conv]p1 and [over.match.ref]p1.
8321 ///
8322 /// \param ConvType The return type of the conversion function.
8323 ///
8324 /// \param ToType The type we are converting to.
8325 ///
8326 /// \param AllowObjCPointerConversion Allow a conversion from one
8327 /// Objective-C pointer to another.
8328 ///
8329 /// \returns true if the conversion is allowable, false otherwise.
8330 static bool isAllowableExplicitConversion(Sema &S,
8331 QualType ConvType, QualType ToType,
8332 bool AllowObjCPointerConversion) {
8333 QualType ToNonRefType = ToType.getNonReferenceType();
8334
8335 // Easy case: the types are the same.
8336 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8337 return true;
8338
8339 // Allow qualification conversions.
8340 bool ObjCLifetimeConversion;
8341 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8342 ObjCLifetimeConversion))
8343 return true;
8344
8345 // If we're not allowed to consider Objective-C pointer conversions,
8346 // we're done.
8347 if (!AllowObjCPointerConversion)
8348 return false;
8349
8350 // Is this an Objective-C pointer conversion?
8351 bool IncompatibleObjC = false;
8352 QualType ConvertedType;
8353 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8354 IncompatibleObjC);
8355 }
8356
8357 void Sema::AddConversionCandidate(
8358 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8359 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8360 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8361 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8362 assert(!Conversion->getDescribedFunctionTemplate() &&
8363 "Conversion function templates use AddTemplateConversionCandidate");
8364 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8365 if (!CandidateSet.isNewCandidate(Conversion))
8366 return;
8367
8368 // If the conversion function has an undeduced return type, trigger its
8369 // deduction now.
8370 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8371 if (DeduceReturnType(Conversion, From->getExprLoc()))
8372 return;
8373 ConvType = Conversion->getConversionType().getNonReferenceType();
8374 }
8375
8376 // If we don't allow any conversion of the result type, ignore conversion
8377 // functions that don't convert to exactly (possibly cv-qualified) T.
8378 if (!AllowResultConversion &&
8379 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8380 return;
8381
8382 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8383 // operator is only a candidate if its return type is the target type or
8384 // can be converted to the target type with a qualification conversion.
8385 //
8386 // FIXME: Include such functions in the candidate list and explain why we
8387 // can't select them.
8388 if (Conversion->isExplicit() &&
8389 !isAllowableExplicitConversion(*this, ConvType, ToType,
8390 AllowObjCConversionOnExplicit))
8391 return;
8392
8393 // Overload resolution is always an unevaluated context.
8394 EnterExpressionEvaluationContext Unevaluated(
8395 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8396
8397 // Add this candidate
8398 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8399 Candidate.FoundDecl = FoundDecl;
8400 Candidate.Function = Conversion;
8401 Candidate.FinalConversion.setAsIdentityConversion();
8402 Candidate.FinalConversion.setFromType(ConvType);
8403 Candidate.FinalConversion.setAllToTypes(ToType);
8404 Candidate.HasFinalConversion = true;
8405 Candidate.Viable = true;
8406 Candidate.ExplicitCallArguments = 1;
8407 Candidate.StrictPackMatch = StrictPackMatch;
8408
8409 // Explicit functions are not actually candidates at all if we're not
8410 // allowing them in this context, but keep them around so we can point
8411 // to them in diagnostics.
8412 if (!AllowExplicit && Conversion->isExplicit()) {
8413 Candidate.Viable = false;
8414 Candidate.FailureKind = ovl_fail_explicit;
8415 return;
8416 }
8417
8418 // C++ [over.match.funcs]p4:
8419 // For conversion functions, the function is considered to be a member of
8420 // the class of the implicit implied object argument for the purpose of
8421 // defining the type of the implicit object parameter.
8422 //
8423 // Determine the implicit conversion sequence for the implicit
8424 // object parameter.
8425 QualType ObjectType = From->getType();
8426 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8427 ObjectType = FromPtrType->getPointeeType();
8428 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8429 // C++23 [over.best.ics.general]
8430 // However, if the target is [...]
8431 // - the object parameter of a user-defined conversion function
8432 // [...] user-defined conversion sequences are not considered.
8433 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8434 *this, CandidateSet.getLocation(), From->getType(),
8435 From->Classify(Context), Conversion, ConversionContext,
8436 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8437 /*SuppressUserConversion*/ true);
8438
8439 if (Candidate.Conversions[0].isBad()) {
8440 Candidate.Viable = false;
8441 Candidate.FailureKind = ovl_fail_bad_conversion;
8442 return;
8443 }
8444
8445 if (Conversion->getTrailingRequiresClause()) {
8446 ConstraintSatisfaction Satisfaction;
8447 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8448 !Satisfaction.IsSatisfied) {
8449 Candidate.Viable = false;
8450 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8451 return;
8452 }
8453 }
8454
8455 // We won't go through a user-defined type conversion function to convert a
8456 // derived to base as such conversions are given Conversion Rank. They only
8457 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8458 QualType FromCanon
8459 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8460 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8461 if (FromCanon == ToCanon ||
8462 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8463 Candidate.Viable = false;
8464 Candidate.FailureKind = ovl_fail_trivial_conversion;
8465 return;
8466 }
8467
8468 // To determine what the conversion from the result of calling the
8469 // conversion function to the type we're eventually trying to
8470 // convert to (ToType), we need to synthesize a call to the
8471 // conversion function and attempt copy initialization from it. This
8472 // makes sure that we get the right semantics with respect to
8473 // lvalues/rvalues and the type. Fortunately, we can allocate this
8474 // call on the stack and we don't need its arguments to be
8475 // well-formed.
8476 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8477 VK_LValue, From->getBeginLoc());
8478 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8479 Context.getPointerType(Conversion->getType()),
8480 CK_FunctionToPointerDecay, &ConversionRef,
8481 VK_PRValue, FPOptionsOverride());
8482
8483 QualType ConversionType = Conversion->getConversionType();
8484 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8485 Candidate.Viable = false;
8486 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8487 return;
8488 }
8489
8490 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8491
8492 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8493
8494 // Introduce a temporary expression with the right type and value category
8495 // that we can use for deduction purposes.
8496 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8497
8498 ImplicitConversionSequence ICS =
8499 TryCopyInitialization(*this, &FakeCall, ToType,
8500 /*SuppressUserConversions=*/true,
8501 /*InOverloadResolution=*/false,
8502 /*AllowObjCWritebackConversion=*/false);
8503
8504 switch (ICS.getKind()) {
8505 case ImplicitConversionSequence::StandardConversion:
8506 Candidate.FinalConversion = ICS.Standard;
8507 Candidate.HasFinalConversion = true;
8508
8509 // C++ [over.ics.user]p3:
8510 // If the user-defined conversion is specified by a specialization of a
8511 // conversion function template, the second standard conversion sequence
8512 // shall have exact match rank.
8513 if (Conversion->getPrimaryTemplate() &&
8514 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
8515 Candidate.Viable = false;
8516 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8517 return;
8518 }
8519
8520 // C++0x [dcl.init.ref]p5:
8521 // In the second case, if the reference is an rvalue reference and
8522 // the second standard conversion sequence of the user-defined
8523 // conversion sequence includes an lvalue-to-rvalue conversion, the
8524 // program is ill-formed.
8525 if (ToType->isRValueReferenceType() &&
8526 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8527 Candidate.Viable = false;
8528 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8529 return;
8530 }
8531 break;
8532
8533 case ImplicitConversionSequence::BadConversion:
8534 Candidate.Viable = false;
8535 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8536 return;
8537
8538 default:
8539 llvm_unreachable(
8540 "Can only end up with a standard conversion sequence or failure");
8541 }
8542
8543 if (EnableIfAttr *FailedAttr =
8544 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8545 Candidate.Viable = false;
8546 Candidate.FailureKind = ovl_fail_enable_if;
8547 Candidate.DeductionFailure.Data = FailedAttr;
8548 return;
8549 }
8550
8551 if (isNonViableMultiVersionOverload(Conversion)) {
8552 Candidate.Viable = false;
8553 Candidate.FailureKind = ovl_non_default_multiversion_function;
8554 }
8555 }
8556
8557 static void AddTemplateConversionCandidateImmediately(
8558 Sema &S, OverloadCandidateSet &CandidateSet,
8559 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8560 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8561 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8562 bool AllowResultConversion) {
8563
8564 // If the function template has a non-dependent explicit specification,
8565 // exclude it now if appropriate; we are not permitted to perform deduction
8566 // and substitution in this case.
8567 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8568 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8569 Candidate.FoundDecl = FoundDecl;
8570 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8571 Candidate.Viable = false;
8572 Candidate.FailureKind = ovl_fail_explicit;
8573 return;
8574 }
8575
8576 QualType ObjectType = From->getType();
8577 Expr::Classification ObjectClassification = From->Classify(S.Context);
8578
8579 TemplateDeductionInfo Info(CandidateSet.getLocation());
8580 CXXConversionDecl *Specialization = nullptr;
8581 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8582 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8583 Specialization, Info);
8584 Result != TemplateDeductionResult::Success) {
8585 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8586 Candidate.FoundDecl = FoundDecl;
8587 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8588 Candidate.Viable = false;
8589 Candidate.FailureKind = ovl_fail_bad_deduction;
8590 Candidate.ExplicitCallArguments = 1;
8591 Candidate.DeductionFailure =
8592 MakeDeductionFailureInfo(S.Context, Result, Info);
8593 return;
8594 }
8595
8596 // Add the conversion function template specialization produced by
8597 // template argument deduction as a candidate.
8598 assert(Specialization && "Missing function template specialization?");
8599 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8600 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8601 AllowExplicit, AllowResultConversion,
8602 Info.hasStrictPackMatch());
8603 }
8604
8605 void Sema::AddTemplateConversionCandidate(
8606 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8607 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8608 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8609 bool AllowExplicit, bool AllowResultConversion) {
8610 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8611 "Only conversion function templates permitted here");
8612
8613 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8614 return;
8615
8616 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||
8617 CandidateSet.getKind() ==
8618 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8619 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8620 AddTemplateConversionCandidateImmediately(
8621 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8622 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8623 AllowResultConversion);
8624
8625 CandidateSet.DisableResolutionByPerfectCandidate();
8626 return;
8627 }
8628
8629 CandidateSet.AddDeferredConversionTemplateCandidate(
8630 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8631 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8632 }
8633
8634 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8635 DeclAccessPair FoundDecl,
8636 CXXRecordDecl *ActingContext,
8637 const FunctionProtoType *Proto,
8638 Expr *Object,
8639 ArrayRef<Expr *> Args,
8640 OverloadCandidateSet& CandidateSet) {
8641 if (!CandidateSet.isNewCandidate(Conversion))
8642 return;
8643
8644 // Overload resolution is always an unevaluated context.
8645 EnterExpressionEvaluationContext Unevaluated(
8646 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8647
8648 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8649 Candidate.FoundDecl = FoundDecl;
8650 Candidate.Function = nullptr;
8651 Candidate.Surrogate = Conversion;
8652 Candidate.IsSurrogate = true;
8653 Candidate.Viable = true;
8654 Candidate.ExplicitCallArguments = Args.size();
8655
8656 // Determine the implicit conversion sequence for the implicit
8657 // object parameter.
8658 ImplicitConversionSequence ObjectInit;
8659 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8660 ObjectInit = TryCopyInitialization(*this, Object,
8661 Conversion->getParamDecl(0)->getType(),
8662 /*SuppressUserConversions=*/false,
8663 /*InOverloadResolution=*/true, false);
8664 } else {
8665 ObjectInit = TryObjectArgumentInitialization(
8666 *this, CandidateSet.getLocation(), Object->getType(),
8667 Object->Classify(Context), Conversion, ActingContext);
8668 }
8669
8670 if (ObjectInit.isBad()) {
8671 Candidate.Viable = false;
8672 Candidate.FailureKind = ovl_fail_bad_conversion;
8673 Candidate.Conversions[0] = ObjectInit;
8674 return;
8675 }
8676
8677 // The first conversion is actually a user-defined conversion whose
8678 // first conversion is ObjectInit's standard conversion (which is
8679 // effectively a reference binding). Record it as such.
8680 Candidate.Conversions[0].setUserDefined();
8681 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8682 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8683 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8684 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8685 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8686 Candidate.Conversions[0].UserDefined.After
8687 = Candidate.Conversions[0].UserDefined.Before;
8688 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8689
8690 // Find the
8691 unsigned NumParams = Proto->getNumParams();
8692
8693 // (C++ 13.3.2p2): A candidate function having fewer than m
8694 // parameters is viable only if it has an ellipsis in its parameter
8695 // list (8.3.5).
8696 if (Args.size() > NumParams && !Proto->isVariadic()) {
8697 Candidate.Viable = false;
8698 Candidate.FailureKind = ovl_fail_too_many_arguments;
8699 return;
8700 }
8701
8702 // Function types don't have any default arguments, so just check if
8703 // we have enough arguments.
8704 if (Args.size() < NumParams) {
8705 // Not enough arguments.
8706 Candidate.Viable = false;
8707 Candidate.FailureKind = ovl_fail_too_few_arguments;
8708 return;
8709 }
8710
8711 // Determine the implicit conversion sequences for each of the
8712 // arguments.
8713 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8714 if (ArgIdx < NumParams) {
8715 // (C++ 13.3.2p3): for F to be a viable function, there shall
8716 // exist for each argument an implicit conversion sequence
8717 // (13.3.3.1) that converts that argument to the corresponding
8718 // parameter of F.
8719 QualType ParamType = Proto->getParamType(ArgIdx);
8720 Candidate.Conversions[ArgIdx + 1]
8721 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8722 /*SuppressUserConversions=*/false,
8723 /*InOverloadResolution=*/false,
8724 /*AllowObjCWritebackConversion=*/
8725 getLangOpts().ObjCAutoRefCount);
8726 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8727 Candidate.Viable = false;
8728 Candidate.FailureKind = ovl_fail_bad_conversion;
8729 return;
8730 }
8731 } else {
8732 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8733 // argument for which there is no corresponding parameter is
8734 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8735 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8736 }
8737 }
8738
8739 if (Conversion->getTrailingRequiresClause()) {
8740 ConstraintSatisfaction Satisfaction;
8741 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8742 /*ForOverloadResolution*/ true) ||
8743 !Satisfaction.IsSatisfied) {
8744 Candidate.Viable = false;
8745 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8746 return;
8747 }
8748 }
8749
8750 if (EnableIfAttr *FailedAttr =
8751 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8752 Candidate.Viable = false;
8753 Candidate.FailureKind = ovl_fail_enable_if;
8754 Candidate.DeductionFailure.Data = FailedAttr;
8755 return;
8756 }
8757 }
8758
8759 void Sema::AddNonMemberOperatorCandidates(
8760 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8761 OverloadCandidateSet &CandidateSet,
8762 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8763 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8764 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8765 ArrayRef<Expr *> FunctionArgs = Args;
8766
8767 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8768 FunctionDecl *FD =
8769 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8770
8771 // Don't consider rewritten functions if we're not rewriting.
8772 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8773 continue;
8774
8775 assert(!isa<CXXMethodDecl>(FD) &&
8776 "unqualified operator lookup found a member function");
8777
8778 if (FunTmpl) {
8779 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8780 FunctionArgs, CandidateSet);
8781 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8782
8783 // As template candidates are not deduced immediately,
8784 // persist the array in the overload set.
8785 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8786 FunctionArgs[1], FunctionArgs[0]);
8787 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8788 Reversed, CandidateSet, false, false, true,
8789 ADLCallKind::NotADL,
8790 OverloadCandidateParamOrder::Reversed);
8791 }
8792 } else {
8793 if (ExplicitTemplateArgs)
8794 continue;
8795 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8796 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8797 AddOverloadCandidate(FD, F.getPair(),
8798 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8799 false, false, true, false, ADLCallKind::NotADL, {},
8800 OverloadCandidateParamOrder::Reversed);
8801 }
8802 }
8803 }
8804
8805 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8806 SourceLocation OpLoc,
8807 ArrayRef<Expr *> Args,
8808 OverloadCandidateSet &CandidateSet,
8809 OverloadCandidateParamOrder PO) {
8810 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8811
8812 // C++ [over.match.oper]p3:
8813 // For a unary operator @ with an operand of a type whose
8814 // cv-unqualified version is T1, and for a binary operator @ with
8815 // a left operand of a type whose cv-unqualified version is T1 and
8816 // a right operand of a type whose cv-unqualified version is T2,
8817 // three sets of candidate functions, designated member
8818 // candidates, non-member candidates and built-in candidates, are
8819 // constructed as follows:
8820 QualType T1 = Args[0]->getType();
8821
8822 // -- If T1 is a complete class type or a class currently being
8823 // defined, the set of member candidates is the result of the
8824 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8825 // the set of member candidates is empty.
8826 if (T1->isRecordType()) {
8827 bool IsComplete = isCompleteType(OpLoc, T1);
8828 auto *T1RD = T1->getAsCXXRecordDecl();
8829 // Complete the type if it can be completed.
8830 // If the type is neither complete nor being defined, bail out now.
8831 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8832 return;
8833
8834 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8835 LookupQualifiedName(Operators, T1RD);
8836 Operators.suppressAccessDiagnostics();
8837
8838 for (LookupResult::iterator Oper = Operators.begin(),
8839 OperEnd = Operators.end();
8840 Oper != OperEnd; ++Oper) {
8841 if (Oper->getAsFunction() &&
8842 PO == OverloadCandidateParamOrder::Reversed &&
8843 !CandidateSet.getRewriteInfo().shouldAddReversed(
8844 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8845 continue;
8846 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8847 Args[0]->Classify(Context), Args.slice(1),
8848 CandidateSet, /*SuppressUserConversion=*/false, PO);
8849 }
8850 }
8851 }
8852
8853 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8854 OverloadCandidateSet& CandidateSet,
8855 bool IsAssignmentOperator,
8856 unsigned NumContextualBoolArguments) {
8857 // Overload resolution is always an unevaluated context.
8858 EnterExpressionEvaluationContext Unevaluated(
8859 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8860
8861 // Add this candidate
8862 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8863 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8864 Candidate.Function = nullptr;
8865 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8866
8867 // Determine the implicit conversion sequences for each of the
8868 // arguments.
8869 Candidate.Viable = true;
8870 Candidate.ExplicitCallArguments = Args.size();
8871 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8872 // C++ [over.match.oper]p4:
8873 // For the built-in assignment operators, conversions of the
8874 // left operand are restricted as follows:
8875 // -- no temporaries are introduced to hold the left operand, and
8876 // -- no user-defined conversions are applied to the left
8877 // operand to achieve a type match with the left-most
8878 // parameter of a built-in candidate.
8879 //
8880 // We block these conversions by turning off user-defined
8881 // conversions, since that is the only way that initialization of
8882 // a reference to a non-class type can occur from something that
8883 // is not of the same type.
8884 if (ArgIdx < NumContextualBoolArguments) {
8885 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8886 "Contextual conversion to bool requires bool type");
8887 Candidate.Conversions[ArgIdx]
8888 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8889 } else {
8890 Candidate.Conversions[ArgIdx]
8891 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8892 ArgIdx == 0 && IsAssignmentOperator,
8893 /*InOverloadResolution=*/false,
8894 /*AllowObjCWritebackConversion=*/
8895 getLangOpts().ObjCAutoRefCount);
8896 }
8897 if (Candidate.Conversions[ArgIdx].isBad()) {
8898 Candidate.Viable = false;
8899 Candidate.FailureKind = ovl_fail_bad_conversion;
8900 break;
8901 }
8902 }
8903 }
8904
8905 namespace {
8906
8907 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8908 /// candidate operator functions for built-in operators (C++
8909 /// [over.built]). The types are separated into pointer types and
8910 /// enumeration types.
8911 class BuiltinCandidateTypeSet {
8912 /// TypeSet - A set of types.
8913 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8914
8915 /// PointerTypes - The set of pointer types that will be used in the
8916 /// built-in candidates.
8917 TypeSet PointerTypes;
8918
8919 /// MemberPointerTypes - The set of member pointer types that will be
8920 /// used in the built-in candidates.
8921 TypeSet MemberPointerTypes;
8922
8923 /// EnumerationTypes - The set of enumeration types that will be
8924 /// used in the built-in candidates.
8925 TypeSet EnumerationTypes;
8926
8927 /// The set of vector types that will be used in the built-in
8928 /// candidates.
8929 TypeSet VectorTypes;
8930
8931 /// The set of matrix types that will be used in the built-in
8932 /// candidates.
8933 TypeSet MatrixTypes;
8934
8935 /// The set of _BitInt types that will be used in the built-in candidates.
8936 TypeSet BitIntTypes;
8937
8938 /// A flag indicating non-record types are viable candidates
8939 bool HasNonRecordTypes;
8940
8941 /// A flag indicating whether either arithmetic or enumeration types
8942 /// were present in the candidate set.
8943 bool HasArithmeticOrEnumeralTypes;
8944
8945 /// A flag indicating whether the nullptr type was present in the
8946 /// candidate set.
8947 bool HasNullPtrType;
8948
8949 /// Sema - The semantic analysis instance where we are building the
8950 /// candidate type set.
8951 Sema &SemaRef;
8952
8953 /// Context - The AST context in which we will build the type sets.
8954 ASTContext &Context;
8955
8956 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8957 const Qualifiers &VisibleQuals);
8958 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8959
8960 public:
8961 /// iterator - Iterates through the types that are part of the set.
8962 typedef TypeSet::iterator iterator;
8963
8964 BuiltinCandidateTypeSet(Sema &SemaRef)
8965 : HasNonRecordTypes(false),
8966 HasArithmeticOrEnumeralTypes(false),
8967 HasNullPtrType(false),
8968 SemaRef(SemaRef),
8969 Context(SemaRef.Context) { }
8970
8971 void AddTypesConvertedFrom(QualType Ty,
8972 SourceLocation Loc,
8973 bool AllowUserConversions,
8974 bool AllowExplicitConversions,
8975 const Qualifiers &VisibleTypeConversionsQuals);
8976
8977 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8978 llvm::iterator_range<iterator> member_pointer_types() {
8979 return MemberPointerTypes;
8980 }
8981 llvm::iterator_range<iterator> enumeration_types() {
8982 return EnumerationTypes;
8983 }
8984 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8985 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8986 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8987
8988 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8989 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8990 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8991 bool hasNullPtrType() const { return HasNullPtrType; }
8992 };
8993
8994 } // end anonymous namespace
8995
8996 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8997 /// the set of pointer types along with any more-qualified variants of
8998 /// that type. For example, if @p Ty is "int const *", this routine
8999 /// will add "int const *", "int const volatile *", "int const
9000 /// restrict *", and "int const volatile restrict *" to the set of
9001 /// pointer types. Returns true if the add of @p Ty itself succeeded,
9002 /// false otherwise.
9003 ///
9004 /// FIXME: what to do about extended qualifiers?
9005 bool
9006 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9007 const Qualifiers &VisibleQuals) {
9008
9009 // Insert this type.
9010 if (!PointerTypes.insert(Ty))
9011 return false;
9012
9013 QualType PointeeTy;
9014 const PointerType *PointerTy = Ty->getAs<PointerType>();
9015 bool buildObjCPtr = false;
9016 if (!PointerTy) {
9017 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9018 PointeeTy = PTy->getPointeeType();
9019 buildObjCPtr = true;
9020 } else {
9021 PointeeTy = PointerTy->getPointeeType();
9022 }
9023
9024 // Don't add qualified variants of arrays. For one, they're not allowed
9025 // (the qualifier would sink to the element type), and for another, the
9026 // only overload situation where it matters is subscript or pointer +- int,
9027 // and those shouldn't have qualifier variants anyway.
9028 if (PointeeTy->isArrayType())
9029 return true;
9030
9031 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9032 bool hasVolatile = VisibleQuals.hasVolatile();
9033 bool hasRestrict = VisibleQuals.hasRestrict();
9034
9035 // Iterate through all strict supersets of BaseCVR.
9036 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9037 if ((CVR | BaseCVR) != CVR) continue;
9038 // Skip over volatile if no volatile found anywhere in the types.
9039 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9040
9041 // Skip over restrict if no restrict found anywhere in the types, or if
9042 // the type cannot be restrict-qualified.
9043 if ((CVR & Qualifiers::Restrict) &&
9044 (!hasRestrict ||
9045 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9046 continue;
9047
9048 // Build qualified pointee type.
9049 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9050
9051 // Build qualified pointer type.
9052 QualType QPointerTy;
9053 if (!buildObjCPtr)
9054 QPointerTy = Context.getPointerType(QPointeeTy);
9055 else
9056 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9057
9058 // Insert qualified pointer type.
9059 PointerTypes.insert(QPointerTy);
9060 }
9061
9062 return true;
9063 }
9064
9065 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9066 /// to the set of pointer types along with any more-qualified variants of
9067 /// that type. For example, if @p Ty is "int const *", this routine
9068 /// will add "int const *", "int const volatile *", "int const
9069 /// restrict *", and "int const volatile restrict *" to the set of
9070 /// pointer types. Returns true if the add of @p Ty itself succeeded,
9071 /// false otherwise.
9072 ///
9073 /// FIXME: what to do about extended qualifiers?
9074 bool
9075 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9076 QualType Ty) {
9077 // Insert this type.
9078 if (!MemberPointerTypes.insert(Ty))
9079 return false;
9080
9081 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9082 assert(PointerTy && "type was not a member pointer type!");
9083
9084 QualType PointeeTy = PointerTy->getPointeeType();
9085 // Don't add qualified variants of arrays. For one, they're not allowed
9086 // (the qualifier would sink to the element type), and for another, the
9087 // only overload situation where it matters is subscript or pointer +- int,
9088 // and those shouldn't have qualifier variants anyway.
9089 if (PointeeTy->isArrayType())
9090 return true;
9091 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9092
9093 // Iterate through all strict supersets of the pointee type's CVR
9094 // qualifiers.
9095 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9096 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9097 if ((CVR | BaseCVR) != CVR) continue;
9098
9099 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9100 MemberPointerTypes.insert(Context.getMemberPointerType(
9101 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9102 }
9103
9104 return true;
9105 }
9106
9107 /// AddTypesConvertedFrom - Add each of the types to which the type @p
9108 /// Ty can be implicit converted to the given set of @p Types. We're
9109 /// primarily interested in pointer types and enumeration types. We also
9110 /// take member pointer types, for the conditional operator.
9111 /// AllowUserConversions is true if we should look at the conversion
9112 /// functions of a class type, and AllowExplicitConversions if we
9113 /// should also include the explicit conversion functions of a class
9114 /// type.
9115 void
9116 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9117 SourceLocation Loc,
9118 bool AllowUserConversions,
9119 bool AllowExplicitConversions,
9120 const Qualifiers &VisibleQuals) {
9121 // Only deal with canonical types.
9122 Ty = Context.getCanonicalType(Ty);
9123
9124 // Look through reference types; they aren't part of the type of an
9125 // expression for the purposes of conversions.
9126 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9127 Ty = RefTy->getPointeeType();
9128
9129 // If we're dealing with an array type, decay to the pointer.
9130 if (Ty->isArrayType())
9131 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9132
9133 // Otherwise, we don't care about qualifiers on the type.
9134 Ty = Ty.getLocalUnqualifiedType();
9135
9136 // Flag if we ever add a non-record type.
9137 bool TyIsRec = Ty->isRecordType();
9138 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9139
9140 // Flag if we encounter an arithmetic type.
9141 HasArithmeticOrEnumeralTypes =
9142 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9143
9144 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9145 PointerTypes.insert(Ty);
9146 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9147 // Insert our type, and its more-qualified variants, into the set
9148 // of types.
9149 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9150 return;
9151 } else if (Ty->isMemberPointerType()) {
9152 // Member pointers are far easier, since the pointee can't be converted.
9153 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9154 return;
9155 } else if (Ty->isEnumeralType()) {
9156 HasArithmeticOrEnumeralTypes = true;
9157 EnumerationTypes.insert(Ty);
9158 } else if (Ty->isBitIntType()) {
9159 HasArithmeticOrEnumeralTypes = true;
9160 BitIntTypes.insert(Ty);
9161 } else if (Ty->isVectorType()) {
9162 // We treat vector types as arithmetic types in many contexts as an
9163 // extension.
9164 HasArithmeticOrEnumeralTypes = true;
9165 VectorTypes.insert(Ty);
9166 } else if (Ty->isMatrixType()) {
9167 // Similar to vector types, we treat vector types as arithmetic types in
9168 // many contexts as an extension.
9169 HasArithmeticOrEnumeralTypes = true;
9170 MatrixTypes.insert(Ty);
9171 } else if (Ty->isNullPtrType()) {
9172 HasNullPtrType = true;
9173 } else if (AllowUserConversions && TyIsRec) {
9174 // No conversion functions in incomplete types.
9175 if (!SemaRef.isCompleteType(Loc, Ty))
9176 return;
9177
9178 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9179 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9180 if (isa<UsingShadowDecl>(D))
9181 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9182
9183 // Skip conversion function templates; they don't tell us anything
9184 // about which builtin types we can convert to.
9185 if (isa<FunctionTemplateDecl>(D))
9186 continue;
9187
9188 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9189 if (AllowExplicitConversions || !Conv->isExplicit()) {
9190 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9191 VisibleQuals);
9192 }
9193 }
9194 }
9195 }
9196 /// Helper function for adjusting address spaces for the pointer or reference
9197 /// operands of builtin operators depending on the argument.
9198 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9199 Expr *Arg) {
9200 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
9201 }
9202
9203 /// Helper function for AddBuiltinOperatorCandidates() that adds
9204 /// the volatile- and non-volatile-qualified assignment operators for the
9205 /// given type to the candidate set.
9206 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9207 QualType T,
9208 ArrayRef<Expr *> Args,
9209 OverloadCandidateSet &CandidateSet) {
9210 QualType ParamTypes[2];
9211
9212 // T& operator=(T&, T)
9213 ParamTypes[0] = S.Context.getLValueReferenceType(
9214 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
9215 ParamTypes[1] = T;
9216 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9217 /*IsAssignmentOperator=*/true);
9218
9219 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9220 // volatile T& operator=(volatile T&, T)
9221 ParamTypes[0] = S.Context.getLValueReferenceType(
9222 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
9223 Args[0]));
9224 ParamTypes[1] = T;
9225 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9226 /*IsAssignmentOperator=*/true);
9227 }
9228 }
9229
9230 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9231 /// if any, found in visible type conversion functions found in ArgExpr's type.
9232 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9233 Qualifiers VRQuals;
9234 CXXRecordDecl *ClassDecl;
9235 if (const MemberPointerType *RHSMPType =
9236 ArgExpr->getType()->getAs<MemberPointerType>())
9237 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9238 else
9239 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9240 if (!ClassDecl) {
9241 // Just to be safe, assume the worst case.
9242 VRQuals.addVolatile();
9243 VRQuals.addRestrict();
9244 return VRQuals;
9245 }
9246 if (!ClassDecl->hasDefinition())
9247 return VRQuals;
9248
9249 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9250 if (isa<UsingShadowDecl>(D))
9251 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9252 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9253 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9254 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9255 CanTy = ResTypeRef->getPointeeType();
9256 // Need to go down the pointer/mempointer chain and add qualifiers
9257 // as see them.
9258 bool done = false;
9259 while (!done) {
9260 if (CanTy.isRestrictQualified())
9261 VRQuals.addRestrict();
9262 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9263 CanTy = ResTypePtr->getPointeeType();
9264 else if (const MemberPointerType *ResTypeMPtr =
9265 CanTy->getAs<MemberPointerType>())
9266 CanTy = ResTypeMPtr->getPointeeType();
9267 else
9268 done = true;
9269 if (CanTy.isVolatileQualified())
9270 VRQuals.addVolatile();
9271 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9272 return VRQuals;
9273 }
9274 }
9275 }
9276 return VRQuals;
9277 }
9278
9279 // Note: We're currently only handling qualifiers that are meaningful for the
9280 // LHS of compound assignment overloading.
9281 static void forAllQualifierCombinationsImpl(
9282 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9283 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9284 // _Atomic
9285 if (Available.hasAtomic()) {
9286 Available.removeAtomic();
9287 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9288 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9289 return;
9290 }
9291
9292 // volatile
9293 if (Available.hasVolatile()) {
9294 Available.removeVolatile();
9295 assert(!Applied.hasVolatile());
9296 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9297 Callback);
9298 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9299 return;
9300 }
9301
9302 Callback(Applied);
9303 }
9304
9305 static void forAllQualifierCombinations(
9306 QualifiersAndAtomic Quals,
9307 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9308 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
9309 Callback);
9310 }
9311
9312 static QualType makeQualifiedLValueReferenceType(QualType Base,
9313 QualifiersAndAtomic Quals,
9314 Sema &S) {
9315 if (Quals.hasAtomic())
9316 Base = S.Context.getAtomicType(Base);
9317 if (Quals.hasVolatile())
9318 Base = S.Context.getVolatileType(Base);
9319 return S.Context.getLValueReferenceType(Base);
9320 }
9321
9322 namespace {
9323
9324 /// Helper class to manage the addition of builtin operator overload
9325 /// candidates. It provides shared state and utility methods used throughout
9326 /// the process, as well as a helper method to add each group of builtin
9327 /// operator overloads from the standard to a candidate set.
9328 class BuiltinOperatorOverloadBuilder {
9329 // Common instance state available to all overload candidate addition methods.
9330 Sema &S;
9331 ArrayRef<Expr *> Args;
9332 QualifiersAndAtomic VisibleTypeConversionsQuals;
9333 bool HasArithmeticOrEnumeralCandidateType;
9334 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9335 OverloadCandidateSet &CandidateSet;
9336
9337 static constexpr int ArithmeticTypesCap = 26;
9338 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9339
9340 // Define some indices used to iterate over the arithmetic types in
9341 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9342 // types are that preserved by promotion (C++ [over.built]p2).
9343 unsigned FirstIntegralType,
9344 LastIntegralType;
9345 unsigned FirstPromotedIntegralType,
9346 LastPromotedIntegralType;
9347 unsigned FirstPromotedArithmeticType,
9348 LastPromotedArithmeticType;
9349 unsigned NumArithmeticTypes;
9350
9351 void InitArithmeticTypes() {
9352 // Start of promoted types.
9353 FirstPromotedArithmeticType = 0;
9354 ArithmeticTypes.push_back(S.Context.FloatTy);
9355 ArithmeticTypes.push_back(S.Context.DoubleTy);
9356 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9357 if (S.Context.getTargetInfo().hasFloat128Type())
9358 ArithmeticTypes.push_back(S.Context.Float128Ty);
9359 if (S.Context.getTargetInfo().hasIbm128Type())
9360 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9361
9362 // Start of integral types.
9363 FirstIntegralType = ArithmeticTypes.size();
9364 FirstPromotedIntegralType = ArithmeticTypes.size();
9365 ArithmeticTypes.push_back(S.Context.IntTy);
9366 ArithmeticTypes.push_back(S.Context.LongTy);
9367 ArithmeticTypes.push_back(S.Context.LongLongTy);
9368 if (S.Context.getTargetInfo().hasInt128Type() ||
9369 (S.Context.getAuxTargetInfo() &&
9370 S.Context.getAuxTargetInfo()->hasInt128Type()))
9371 ArithmeticTypes.push_back(S.Context.Int128Ty);
9372 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9373 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9374 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9375 if (S.Context.getTargetInfo().hasInt128Type() ||
9376 (S.Context.getAuxTargetInfo() &&
9377 S.Context.getAuxTargetInfo()->hasInt128Type()))
9378 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9379
9380 /// We add candidates for the unique, unqualified _BitInt types present in
9381 /// the candidate type set. The candidate set already handled ensuring the
9382 /// type is unqualified and canonical, but because we're adding from N
9383 /// different sets, we need to do some extra work to unique things. Insert
9384 /// the candidates into a unique set, then move from that set into the list
9385 /// of arithmetic types.
9386 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9387 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9388 for (QualType BitTy : Candidate.bitint_types())
9389 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9390 }
9391 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9392 LastPromotedIntegralType = ArithmeticTypes.size();
9393 LastPromotedArithmeticType = ArithmeticTypes.size();
9394 // End of promoted types.
9395
9396 ArithmeticTypes.push_back(S.Context.BoolTy);
9397 ArithmeticTypes.push_back(S.Context.CharTy);
9398 ArithmeticTypes.push_back(S.Context.WCharTy);
9399 if (S.Context.getLangOpts().Char8)
9400 ArithmeticTypes.push_back(S.Context.Char8Ty);
9401 ArithmeticTypes.push_back(S.Context.Char16Ty);
9402 ArithmeticTypes.push_back(S.Context.Char32Ty);
9403 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9404 ArithmeticTypes.push_back(S.Context.ShortTy);
9405 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9406 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9407 LastIntegralType = ArithmeticTypes.size();
9408 NumArithmeticTypes = ArithmeticTypes.size();
9409 // End of integral types.
9410 // FIXME: What about complex? What about half?
9411
9412 // We don't know for sure how many bit-precise candidates were involved, so
9413 // we subtract those from the total when testing whether we're under the
9414 // cap or not.
9415 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9416 ArithmeticTypesCap &&
9417 "Enough inline storage for all arithmetic types.");
9418 }
9419
9420 /// Helper method to factor out the common pattern of adding overloads
9421 /// for '++' and '--' builtin operators.
9422 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9423 bool HasVolatile,
9424 bool HasRestrict) {
9425 QualType ParamTypes[2] = {
9426 S.Context.getLValueReferenceType(CandidateTy),
9427 S.Context.IntTy
9428 };
9429
9430 // Non-volatile version.
9431 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9432
9433 // Use a heuristic to reduce number of builtin candidates in the set:
9434 // add volatile version only if there are conversions to a volatile type.
9435 if (HasVolatile) {
9436 ParamTypes[0] =
9437 S.Context.getLValueReferenceType(
9438 S.Context.getVolatileType(CandidateTy));
9439 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9440 }
9441
9442 // Add restrict version only if there are conversions to a restrict type
9443 // and our candidate type is a non-restrict-qualified pointer.
9444 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9445 !CandidateTy.isRestrictQualified()) {
9446 ParamTypes[0]
9447 = S.Context.getLValueReferenceType(
9448 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
9449 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9450
9451 if (HasVolatile) {
9452 ParamTypes[0]
9453 = S.Context.getLValueReferenceType(
9454 S.Context.getCVRQualifiedType(CandidateTy,
9455 (Qualifiers::Volatile |
9456 Qualifiers::Restrict)));
9457 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9458 }
9459 }
9460
9461 }
9462
9463 /// Helper to add an overload candidate for a binary builtin with types \p L
9464 /// and \p R.
9465 void AddCandidate(QualType L, QualType R) {
9466 QualType LandR[2] = {L, R};
9467 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9468 }
9469
9470 public:
9471 BuiltinOperatorOverloadBuilder(
9472 Sema &S, ArrayRef<Expr *> Args,
9473 QualifiersAndAtomic VisibleTypeConversionsQuals,
9474 bool HasArithmeticOrEnumeralCandidateType,
9475 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9476 OverloadCandidateSet &CandidateSet)
9477 : S(S), Args(Args),
9478 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9479 HasArithmeticOrEnumeralCandidateType(
9480 HasArithmeticOrEnumeralCandidateType),
9481 CandidateTypes(CandidateTypes),
9482 CandidateSet(CandidateSet) {
9483
9484 InitArithmeticTypes();
9485 }
9486
9487 // Increment is deprecated for bool since C++17.
9488 //
9489 // C++ [over.built]p3:
9490 //
9491 // For every pair (T, VQ), where T is an arithmetic type other
9492 // than bool, and VQ is either volatile or empty, there exist
9493 // candidate operator functions of the form
9494 //
9495 // VQ T& operator++(VQ T&);
9496 // T operator++(VQ T&, int);
9497 //
9498 // C++ [over.built]p4:
9499 //
9500 // For every pair (T, VQ), where T is an arithmetic type other
9501 // than bool, and VQ is either volatile or empty, there exist
9502 // candidate operator functions of the form
9503 //
9504 // VQ T& operator--(VQ T&);
9505 // T operator--(VQ T&, int);
9506 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9507 if (!HasArithmeticOrEnumeralCandidateType)
9508 return;
9509
9510 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9511 const auto TypeOfT = ArithmeticTypes[Arith];
9512 if (TypeOfT == S.Context.BoolTy) {
9513 if (Op == OO_MinusMinus)
9514 continue;
9515 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9516 continue;
9517 }
9518 addPlusPlusMinusMinusStyleOverloads(
9519 TypeOfT,
9520 VisibleTypeConversionsQuals.hasVolatile(),
9521 VisibleTypeConversionsQuals.hasRestrict());
9522 }
9523 }
9524
9525 // C++ [over.built]p5:
9526 //
9527 // For every pair (T, VQ), where T is a cv-qualified or
9528 // cv-unqualified object type, and VQ is either volatile or
9529 // empty, there exist candidate operator functions of the form
9530 //
9531 // T*VQ& operator++(T*VQ&);
9532 // T*VQ& operator--(T*VQ&);
9533 // T* operator++(T*VQ&, int);
9534 // T* operator--(T*VQ&, int);
9535 void addPlusPlusMinusMinusPointerOverloads() {
9536 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9537 // Skip pointer types that aren't pointers to object types.
9538 if (!PtrTy->getPointeeType()->isObjectType())
9539 continue;
9540
9541 addPlusPlusMinusMinusStyleOverloads(
9542 PtrTy,
9543 (!PtrTy.isVolatileQualified() &&
9544 VisibleTypeConversionsQuals.hasVolatile()),
9545 (!PtrTy.isRestrictQualified() &&
9546 VisibleTypeConversionsQuals.hasRestrict()));
9547 }
9548 }
9549
9550 // C++ [over.built]p6:
9551 // For every cv-qualified or cv-unqualified object type T, there
9552 // exist candidate operator functions of the form
9553 //
9554 // T& operator*(T*);
9555 //
9556 // C++ [over.built]p7:
9557 // For every function type T that does not have cv-qualifiers or a
9558 // ref-qualifier, there exist candidate operator functions of the form
9559 // T& operator*(T*);
9560 void addUnaryStarPointerOverloads() {
9561 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9562 QualType PointeeTy = ParamTy->getPointeeType();
9563 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9564 continue;
9565
9566 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9567 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9568 continue;
9569
9570 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9571 }
9572 }
9573
9574 // C++ [over.built]p9:
9575 // For every promoted arithmetic type T, there exist candidate
9576 // operator functions of the form
9577 //
9578 // T operator+(T);
9579 // T operator-(T);
9580 void addUnaryPlusOrMinusArithmeticOverloads() {
9581 if (!HasArithmeticOrEnumeralCandidateType)
9582 return;
9583
9584 for (unsigned Arith = FirstPromotedArithmeticType;
9585 Arith < LastPromotedArithmeticType; ++Arith) {
9586 QualType ArithTy = ArithmeticTypes[Arith];
9587 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9588 }
9589
9590 // Extension: We also add these operators for vector types.
9591 for (QualType VecTy : CandidateTypes[0].vector_types())
9592 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9593 }
9594
9595 // C++ [over.built]p8:
9596 // For every type T, there exist candidate operator functions of
9597 // the form
9598 //
9599 // T* operator+(T*);
9600 void addUnaryPlusPointerOverloads() {
9601 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9602 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9603 }
9604
9605 // C++ [over.built]p10:
9606 // For every promoted integral type T, there exist candidate
9607 // operator functions of the form
9608 //
9609 // T operator~(T);
9610 void addUnaryTildePromotedIntegralOverloads() {
9611 if (!HasArithmeticOrEnumeralCandidateType)
9612 return;
9613
9614 for (unsigned Int = FirstPromotedIntegralType;
9615 Int < LastPromotedIntegralType; ++Int) {
9616 QualType IntTy = ArithmeticTypes[Int];
9617 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9618 }
9619
9620 // Extension: We also add this operator for vector types.
9621 for (QualType VecTy : CandidateTypes[0].vector_types())
9622 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9623 }
9624
9625 // C++ [over.match.oper]p16:
9626 // For every pointer to member type T or type std::nullptr_t, there
9627 // exist candidate operator functions of the form
9628 //
9629 // bool operator==(T,T);
9630 // bool operator!=(T,T);
9631 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9632 /// Set of (canonical) types that we've already handled.
9633 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9634
9635 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9636 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9637 // Don't add the same builtin candidate twice.
9638 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9639 continue;
9640
9641 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9642 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9643 }
9644
9645 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9646 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
9647 if (AddedTypes.insert(NullPtrTy).second) {
9648 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9650 }
9651 }
9652 }
9653 }
9654
9655 // C++ [over.built]p15:
9656 //
9657 // For every T, where T is an enumeration type or a pointer type,
9658 // there exist candidate operator functions of the form
9659 //
9660 // bool operator<(T, T);
9661 // bool operator>(T, T);
9662 // bool operator<=(T, T);
9663 // bool operator>=(T, T);
9664 // bool operator==(T, T);
9665 // bool operator!=(T, T);
9666 // R operator<=>(T, T)
9667 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9668 // C++ [over.match.oper]p3:
9669 // [...]the built-in candidates include all of the candidate operator
9670 // functions defined in 13.6 that, compared to the given operator, [...]
9671 // do not have the same parameter-type-list as any non-template non-member
9672 // candidate.
9673 //
9674 // Note that in practice, this only affects enumeration types because there
9675 // aren't any built-in candidates of record type, and a user-defined operator
9676 // must have an operand of record or enumeration type. Also, the only other
9677 // overloaded operator with enumeration arguments, operator=,
9678 // cannot be overloaded for enumeration types, so this is the only place
9679 // where we must suppress candidates like this.
9680 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9681 UserDefinedBinaryOperators;
9682
9683 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9684 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9685 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9686 CEnd = CandidateSet.end();
9687 C != CEnd; ++C) {
9688 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9689 continue;
9690
9691 if (C->Function->isFunctionTemplateSpecialization())
9692 continue;
9693
9694 // We interpret "same parameter-type-list" as applying to the
9695 // "synthesized candidate, with the order of the two parameters
9696 // reversed", not to the original function.
9697 bool Reversed = C->isReversed();
9698 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9699 ->getType()
9700 .getUnqualifiedType();
9701 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9702 ->getType()
9703 .getUnqualifiedType();
9704
9705 // Skip if either parameter isn't of enumeral type.
9706 if (!FirstParamType->isEnumeralType() ||
9707 !SecondParamType->isEnumeralType())
9708 continue;
9709
9710 // Add this operator to the set of known user-defined operators.
9711 UserDefinedBinaryOperators.insert(
9712 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9713 S.Context.getCanonicalType(SecondParamType)));
9714 }
9715 }
9716 }
9717
9718 /// Set of (canonical) types that we've already handled.
9719 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9720
9721 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9722 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9723 // Don't add the same builtin candidate twice.
9724 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9725 continue;
9726 if (IsSpaceship && PtrTy->isFunctionPointerType())
9727 continue;
9728
9729 QualType ParamTypes[2] = {PtrTy, PtrTy};
9730 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9731 }
9732 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9733 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9734
9735 // Don't add the same builtin candidate twice, or if a user defined
9736 // candidate exists.
9737 if (!AddedTypes.insert(CanonType).second ||
9738 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9739 CanonType)))
9740 continue;
9741 QualType ParamTypes[2] = {EnumTy, EnumTy};
9742 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9743 }
9744 }
9745 }
9746
9747 // C++ [over.built]p13:
9748 //
9749 // For every cv-qualified or cv-unqualified object type T
9750 // there exist candidate operator functions of the form
9751 //
9752 // T* operator+(T*, ptrdiff_t);
9753 // T& operator[](T*, ptrdiff_t); [BELOW]
9754 // T* operator-(T*, ptrdiff_t);
9755 // T* operator+(ptrdiff_t, T*);
9756 // T& operator[](ptrdiff_t, T*); [BELOW]
9757 //
9758 // C++ [over.built]p14:
9759 //
9760 // For every T, where T is a pointer to object type, there
9761 // exist candidate operator functions of the form
9762 //
9763 // ptrdiff_t operator-(T, T);
9764 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9765 /// Set of (canonical) types that we've already handled.
9766 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9767
9768 for (int Arg = 0; Arg < 2; ++Arg) {
9769 QualType AsymmetricParamTypes[2] = {
9770 S.Context.getPointerDiffType(),
9771 S.Context.getPointerDiffType(),
9772 };
9773 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9774 QualType PointeeTy = PtrTy->getPointeeType();
9775 if (!PointeeTy->isObjectType())
9776 continue;
9777
9778 AsymmetricParamTypes[Arg] = PtrTy;
9779 if (Arg == 0 || Op == OO_Plus) {
9780 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9781 // T* operator+(ptrdiff_t, T*);
9782 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9783 }
9784 if (Op == OO_Minus) {
9785 // ptrdiff_t operator-(T, T);
9786 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9787 continue;
9788
9789 QualType ParamTypes[2] = {PtrTy, PtrTy};
9790 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9791 }
9792 }
9793 }
9794 }
9795
9796 // C++ [over.built]p12:
9797 //
9798 // For every pair of promoted arithmetic types L and R, there
9799 // exist candidate operator functions of the form
9800 //
9801 // LR operator*(L, R);
9802 // LR operator/(L, R);
9803 // LR operator+(L, R);
9804 // LR operator-(L, R);
9805 // bool operator<(L, R);
9806 // bool operator>(L, R);
9807 // bool operator<=(L, R);
9808 // bool operator>=(L, R);
9809 // bool operator==(L, R);
9810 // bool operator!=(L, R);
9811 //
9812 // where LR is the result of the usual arithmetic conversions
9813 // between types L and R.
9814 //
9815 // C++ [over.built]p24:
9816 //
9817 // For every pair of promoted arithmetic types L and R, there exist
9818 // candidate operator functions of the form
9819 //
9820 // LR operator?(bool, L, R);
9821 //
9822 // where LR is the result of the usual arithmetic conversions
9823 // between types L and R.
9824 // Our candidates ignore the first parameter.
9825 void addGenericBinaryArithmeticOverloads() {
9826 if (!HasArithmeticOrEnumeralCandidateType)
9827 return;
9828
9829 for (unsigned Left = FirstPromotedArithmeticType;
9830 Left < LastPromotedArithmeticType; ++Left) {
9831 for (unsigned Right = FirstPromotedArithmeticType;
9832 Right < LastPromotedArithmeticType; ++Right) {
9833 QualType LandR[2] = { ArithmeticTypes[Left],
9834 ArithmeticTypes[Right] };
9835 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9836 }
9837 }
9838
9839 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9840 // conditional operator for vector types.
9841 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9842 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9843 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9844 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9845 }
9846 }
9847
9848 /// Add binary operator overloads for each candidate matrix type M1, M2:
9849 /// * (M1, M1) -> M1
9850 /// * (M1, M1.getElementType()) -> M1
9851 /// * (M2.getElementType(), M2) -> M2
9852 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9853 void addMatrixBinaryArithmeticOverloads() {
9854 if (!HasArithmeticOrEnumeralCandidateType)
9855 return;
9856
9857 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9858 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9859 AddCandidate(M1, M1);
9860 }
9861
9862 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9863 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9864 if (!CandidateTypes[0].containsMatrixType(M2))
9865 AddCandidate(M2, M2);
9866 }
9867 }
9868
9869 // C++2a [over.built]p14:
9870 //
9871 // For every integral type T there exists a candidate operator function
9872 // of the form
9873 //
9874 // std::strong_ordering operator<=>(T, T)
9875 //
9876 // C++2a [over.built]p15:
9877 //
9878 // For every pair of floating-point types L and R, there exists a candidate
9879 // operator function of the form
9880 //
9881 // std::partial_ordering operator<=>(L, R);
9882 //
9883 // FIXME: The current specification for integral types doesn't play nice with
9884 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9885 // comparisons. Under the current spec this can lead to ambiguity during
9886 // overload resolution. For example:
9887 //
9888 // enum A : int {a};
9889 // auto x = (a <=> (long)42);
9890 //
9891 // error: call is ambiguous for arguments 'A' and 'long'.
9892 // note: candidate operator<=>(int, int)
9893 // note: candidate operator<=>(long, long)
9894 //
9895 // To avoid this error, this function deviates from the specification and adds
9896 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9897 // arithmetic types (the same as the generic relational overloads).
9898 //
9899 // For now this function acts as a placeholder.
9900 void addThreeWayArithmeticOverloads() {
9901 addGenericBinaryArithmeticOverloads();
9902 }
9903
9904 // C++ [over.built]p17:
9905 //
9906 // For every pair of promoted integral types L and R, there
9907 // exist candidate operator functions of the form
9908 //
9909 // LR operator%(L, R);
9910 // LR operator&(L, R);
9911 // LR operator^(L, R);
9912 // LR operator|(L, R);
9913 // L operator<<(L, R);
9914 // L operator>>(L, R);
9915 //
9916 // where LR is the result of the usual arithmetic conversions
9917 // between types L and R.
9918 void addBinaryBitwiseArithmeticOverloads() {
9919 if (!HasArithmeticOrEnumeralCandidateType)
9920 return;
9921
9922 for (unsigned Left = FirstPromotedIntegralType;
9923 Left < LastPromotedIntegralType; ++Left) {
9924 for (unsigned Right = FirstPromotedIntegralType;
9925 Right < LastPromotedIntegralType; ++Right) {
9926 QualType LandR[2] = { ArithmeticTypes[Left],
9927 ArithmeticTypes[Right] };
9928 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9929 }
9930 }
9931 }
9932
9933 // C++ [over.built]p20:
9934 //
9935 // For every pair (T, VQ), where T is an enumeration or
9936 // pointer to member type and VQ is either volatile or
9937 // empty, there exist candidate operator functions of the form
9938 //
9939 // VQ T& operator=(VQ T&, T);
9940 void addAssignmentMemberPointerOrEnumeralOverloads() {
9941 /// Set of (canonical) types that we've already handled.
9942 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9943
9944 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9945 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9946 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9947 continue;
9948
9949 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9950 }
9951
9952 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9953 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9954 continue;
9955
9956 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9957 }
9958 }
9959 }
9960
9961 // C++ [over.built]p19:
9962 //
9963 // For every pair (T, VQ), where T is any type and VQ is either
9964 // volatile or empty, there exist candidate operator functions
9965 // of the form
9966 //
9967 // T*VQ& operator=(T*VQ&, T*);
9968 //
9969 // C++ [over.built]p21:
9970 //
9971 // For every pair (T, VQ), where T is a cv-qualified or
9972 // cv-unqualified object type and VQ is either volatile or
9973 // empty, there exist candidate operator functions of the form
9974 //
9975 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9976 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9977 void addAssignmentPointerOverloads(bool isEqualOp) {
9978 /// Set of (canonical) types that we've already handled.
9979 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9980
9981 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9982 // If this is operator=, keep track of the builtin candidates we added.
9983 if (isEqualOp)
9984 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9985 else if (!PtrTy->getPointeeType()->isObjectType())
9986 continue;
9987
9988 // non-volatile version
9989 QualType ParamTypes[2] = {
9990 S.Context.getLValueReferenceType(PtrTy),
9991 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9992 };
9993 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9994 /*IsAssignmentOperator=*/ isEqualOp);
9995
9996 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9997 VisibleTypeConversionsQuals.hasVolatile();
9998 if (NeedVolatile) {
9999 // volatile version
10000 ParamTypes[0] =
10001 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
10002 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10003 /*IsAssignmentOperator=*/isEqualOp);
10004 }
10005
10006 if (!PtrTy.isRestrictQualified() &&
10007 VisibleTypeConversionsQuals.hasRestrict()) {
10008 // restrict version
10009 ParamTypes[0] =
10010 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
10011 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10012 /*IsAssignmentOperator=*/isEqualOp);
10013
10014 if (NeedVolatile) {
10015 // volatile restrict version
10016 ParamTypes[0] =
10017 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
10018 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
10019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10020 /*IsAssignmentOperator=*/isEqualOp);
10021 }
10022 }
10023 }
10024
10025 if (isEqualOp) {
10026 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10027 // Make sure we don't add the same candidate twice.
10028 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10029 continue;
10030
10031 QualType ParamTypes[2] = {
10032 S.Context.getLValueReferenceType(PtrTy),
10033 PtrTy,
10034 };
10035
10036 // non-volatile version
10037 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10038 /*IsAssignmentOperator=*/true);
10039
10040 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10041 VisibleTypeConversionsQuals.hasVolatile();
10042 if (NeedVolatile) {
10043 // volatile version
10044 ParamTypes[0] = S.Context.getLValueReferenceType(
10045 S.Context.getVolatileType(PtrTy));
10046 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10047 /*IsAssignmentOperator=*/true);
10048 }
10049
10050 if (!PtrTy.isRestrictQualified() &&
10051 VisibleTypeConversionsQuals.hasRestrict()) {
10052 // restrict version
10053 ParamTypes[0] = S.Context.getLValueReferenceType(
10054 S.Context.getRestrictType(PtrTy));
10055 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10056 /*IsAssignmentOperator=*/true);
10057
10058 if (NeedVolatile) {
10059 // volatile restrict version
10060 ParamTypes[0] =
10061 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
10062 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
10063 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10064 /*IsAssignmentOperator=*/true);
10065 }
10066 }
10067 }
10068 }
10069 }
10070
10071 // C++ [over.built]p18:
10072 //
10073 // For every triple (L, VQ, R), where L is an arithmetic type,
10074 // VQ is either volatile or empty, and R is a promoted
10075 // arithmetic type, there exist candidate operator functions of
10076 // the form
10077 //
10078 // VQ L& operator=(VQ L&, R);
10079 // VQ L& operator*=(VQ L&, R);
10080 // VQ L& operator/=(VQ L&, R);
10081 // VQ L& operator+=(VQ L&, R);
10082 // VQ L& operator-=(VQ L&, R);
10083 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10084 if (!HasArithmeticOrEnumeralCandidateType)
10085 return;
10086
10087 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10088 for (unsigned Right = FirstPromotedArithmeticType;
10089 Right < LastPromotedArithmeticType; ++Right) {
10090 QualType ParamTypes[2];
10091 ParamTypes[1] = ArithmeticTypes[Right];
10092 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10093 S, ArithmeticTypes[Left], Args[0]);
10094
10095 forAllQualifierCombinations(
10096 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10097 ParamTypes[0] =
10098 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10099 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10100 /*IsAssignmentOperator=*/isEqualOp);
10101 });
10102 }
10103 }
10104
10105 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10106 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10107 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10108 QualType ParamTypes[2];
10109 ParamTypes[1] = Vec2Ty;
10110 // Add this built-in operator as a candidate (VQ is empty).
10111 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10112 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10113 /*IsAssignmentOperator=*/isEqualOp);
10114
10115 // Add this built-in operator as a candidate (VQ is 'volatile').
10116 if (VisibleTypeConversionsQuals.hasVolatile()) {
10117 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10118 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10119 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10120 /*IsAssignmentOperator=*/isEqualOp);
10121 }
10122 }
10123 }
10124
10125 // C++ [over.built]p22:
10126 //
10127 // For every triple (L, VQ, R), where L is an integral type, VQ
10128 // is either volatile or empty, and R is a promoted integral
10129 // type, there exist candidate operator functions of the form
10130 //
10131 // VQ L& operator%=(VQ L&, R);
10132 // VQ L& operator<<=(VQ L&, R);
10133 // VQ L& operator>>=(VQ L&, R);
10134 // VQ L& operator&=(VQ L&, R);
10135 // VQ L& operator^=(VQ L&, R);
10136 // VQ L& operator|=(VQ L&, R);
10137 void addAssignmentIntegralOverloads() {
10138 if (!HasArithmeticOrEnumeralCandidateType)
10139 return;
10140
10141 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10142 for (unsigned Right = FirstPromotedIntegralType;
10143 Right < LastPromotedIntegralType; ++Right) {
10144 QualType ParamTypes[2];
10145 ParamTypes[1] = ArithmeticTypes[Right];
10146 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10147 S, ArithmeticTypes[Left], Args[0]);
10148
10149 forAllQualifierCombinations(
10150 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10151 ParamTypes[0] =
10152 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10153 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10154 });
10155 }
10156 }
10157 }
10158
10159 // C++ [over.operator]p23:
10160 //
10161 // There also exist candidate operator functions of the form
10162 //
10163 // bool operator!(bool);
10164 // bool operator&&(bool, bool);
10165 // bool operator||(bool, bool);
10166 void addExclaimOverload() {
10167 QualType ParamTy = S.Context.BoolTy;
10168 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10169 /*IsAssignmentOperator=*/false,
10170 /*NumContextualBoolArguments=*/1);
10171 }
10172 void addAmpAmpOrPipePipeOverload() {
10173 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10174 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10175 /*IsAssignmentOperator=*/false,
10176 /*NumContextualBoolArguments=*/2);
10177 }
10178
10179 // C++ [over.built]p13:
10180 //
10181 // For every cv-qualified or cv-unqualified object type T there
10182 // exist candidate operator functions of the form
10183 //
10184 // T* operator+(T*, ptrdiff_t); [ABOVE]
10185 // T& operator[](T*, ptrdiff_t);
10186 // T* operator-(T*, ptrdiff_t); [ABOVE]
10187 // T* operator+(ptrdiff_t, T*); [ABOVE]
10188 // T& operator[](ptrdiff_t, T*);
10189 void addSubscriptOverloads() {
10190 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10191 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10192 QualType PointeeType = PtrTy->getPointeeType();
10193 if (!PointeeType->isObjectType())
10194 continue;
10195
10196 // T& operator[](T*, ptrdiff_t)
10197 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10198 }
10199
10200 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10201 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10202 QualType PointeeType = PtrTy->getPointeeType();
10203 if (!PointeeType->isObjectType())
10204 continue;
10205
10206 // T& operator[](ptrdiff_t, T*)
10207 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10208 }
10209 }
10210
10211 // C++ [over.built]p11:
10212 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10213 // C1 is the same type as C2 or is a derived class of C2, T is an object
10214 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10215 // there exist candidate operator functions of the form
10216 //
10217 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10218 //
10219 // where CV12 is the union of CV1 and CV2.
10220 void addArrowStarOverloads() {
10221 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10222 QualType C1Ty = PtrTy;
10223 QualType C1;
10224 QualifierCollector Q1;
10225 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10226 if (!isa<RecordType>(C1))
10227 continue;
10228 // heuristic to reduce number of builtin candidates in the set.
10229 // Add volatile/restrict version only if there are conversions to a
10230 // volatile/restrict type.
10231 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10232 continue;
10233 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10234 continue;
10235 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10236 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10237 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10238 *D2 = mptr->getMostRecentCXXRecordDecl();
10239 if (!declaresSameEntity(D1, D2) &&
10240 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10241 break;
10242 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10243 // build CV12 T&
10244 QualType T = mptr->getPointeeType();
10245 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10246 T.isVolatileQualified())
10247 continue;
10248 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10249 T.isRestrictQualified())
10250 continue;
10251 T = Q1.apply(S.Context, T);
10252 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10253 }
10254 }
10255 }
10256
10257 // Note that we don't consider the first argument, since it has been
10258 // contextually converted to bool long ago. The candidates below are
10259 // therefore added as binary.
10260 //
10261 // C++ [over.built]p25:
10262 // For every type T, where T is a pointer, pointer-to-member, or scoped
10263 // enumeration type, there exist candidate operator functions of the form
10264 //
10265 // T operator?(bool, T, T);
10266 //
10267 void addConditionalOperatorOverloads() {
10268 /// Set of (canonical) types that we've already handled.
10269 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10270
10271 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10272 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10273 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10274 continue;
10275
10276 QualType ParamTypes[2] = {PtrTy, PtrTy};
10277 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10278 }
10279
10280 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10281 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10282 continue;
10283
10284 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10285 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10286 }
10287
10288 if (S.getLangOpts().CPlusPlus11) {
10289 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10290 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10291 continue;
10292
10293 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10294 continue;
10295
10296 QualType ParamTypes[2] = {EnumTy, EnumTy};
10297 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10298 }
10299 }
10300 }
10301 }
10302 };
10303
10304 } // end anonymous namespace
10305
10306 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10307 SourceLocation OpLoc,
10308 ArrayRef<Expr *> Args,
10309 OverloadCandidateSet &CandidateSet) {
10310 // Find all of the types that the arguments can convert to, but only
10311 // if the operator we're looking at has built-in operator candidates
10312 // that make use of these types. Also record whether we encounter non-record
10313 // candidate types or either arithmetic or enumeral candidate types.
10314 QualifiersAndAtomic VisibleTypeConversionsQuals;
10315 VisibleTypeConversionsQuals.addConst();
10316 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10317 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10318 if (Args[ArgIdx]->getType()->isAtomicType())
10319 VisibleTypeConversionsQuals.addAtomic();
10320 }
10321
10322 bool HasNonRecordCandidateType = false;
10323 bool HasArithmeticOrEnumeralCandidateType = false;
10324 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10325 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10326 CandidateTypes.emplace_back(*this);
10327 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10328 OpLoc,
10329 true,
10330 (Op == OO_Exclaim ||
10331 Op == OO_AmpAmp ||
10332 Op == OO_PipePipe),
10333 VisibleTypeConversionsQuals);
10334 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10335 CandidateTypes[ArgIdx].hasNonRecordTypes();
10336 HasArithmeticOrEnumeralCandidateType =
10337 HasArithmeticOrEnumeralCandidateType ||
10338 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10339 }
10340
10341 // Exit early when no non-record types have been added to the candidate set
10342 // for any of the arguments to the operator.
10343 //
10344 // We can't exit early for !, ||, or &&, since there we have always have
10345 // 'bool' overloads.
10346 if (!HasNonRecordCandidateType &&
10347 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10348 return;
10349
10350 // Setup an object to manage the common state for building overloads.
10351 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10352 VisibleTypeConversionsQuals,
10353 HasArithmeticOrEnumeralCandidateType,
10354 CandidateTypes, CandidateSet);
10355
10356 // Dispatch over the operation to add in only those overloads which apply.
10357 switch (Op) {
10358 case OO_None:
10359 case NUM_OVERLOADED_OPERATORS:
10360 llvm_unreachable("Expected an overloaded operator");
10361
10362 case OO_New:
10363 case OO_Delete:
10364 case OO_Array_New:
10365 case OO_Array_Delete:
10366 case OO_Call:
10367 llvm_unreachable(
10368 "Special operators don't use AddBuiltinOperatorCandidates");
10369
10370 case OO_Comma:
10371 case OO_Arrow:
10372 case OO_Coawait:
10373 // C++ [over.match.oper]p3:
10374 // -- For the operator ',', the unary operator '&', the
10375 // operator '->', or the operator 'co_await', the
10376 // built-in candidates set is empty.
10377 break;
10378
10379 case OO_Plus: // '+' is either unary or binary
10380 if (Args.size() == 1)
10381 OpBuilder.addUnaryPlusPointerOverloads();
10382 [[fallthrough]];
10383
10384 case OO_Minus: // '-' is either unary or binary
10385 if (Args.size() == 1) {
10386 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10387 } else {
10388 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10389 OpBuilder.addGenericBinaryArithmeticOverloads();
10390 OpBuilder.addMatrixBinaryArithmeticOverloads();
10391 }
10392 break;
10393
10394 case OO_Star: // '*' is either unary or binary
10395 if (Args.size() == 1)
10396 OpBuilder.addUnaryStarPointerOverloads();
10397 else {
10398 OpBuilder.addGenericBinaryArithmeticOverloads();
10399 OpBuilder.addMatrixBinaryArithmeticOverloads();
10400 }
10401 break;
10402
10403 case OO_Slash:
10404 OpBuilder.addGenericBinaryArithmeticOverloads();
10405 break;
10406
10407 case OO_PlusPlus:
10408 case OO_MinusMinus:
10409 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10410 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10411 break;
10412
10413 case OO_EqualEqual:
10414 case OO_ExclaimEqual:
10415 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10416 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10417 OpBuilder.addGenericBinaryArithmeticOverloads();
10418 break;
10419
10420 case OO_Less:
10421 case OO_Greater:
10422 case OO_LessEqual:
10423 case OO_GreaterEqual:
10424 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10425 OpBuilder.addGenericBinaryArithmeticOverloads();
10426 break;
10427
10428 case OO_Spaceship:
10429 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10430 OpBuilder.addThreeWayArithmeticOverloads();
10431 break;
10432
10433 case OO_Percent:
10434 case OO_Caret:
10435 case OO_Pipe:
10436 case OO_LessLess:
10437 case OO_GreaterGreater:
10438 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10439 break;
10440
10441 case OO_Amp: // '&' is either unary or binary
10442 if (Args.size() == 1)
10443 // C++ [over.match.oper]p3:
10444 // -- For the operator ',', the unary operator '&', or the
10445 // operator '->', the built-in candidates set is empty.
10446 break;
10447
10448 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10449 break;
10450
10451 case OO_Tilde:
10452 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10453 break;
10454
10455 case OO_Equal:
10456 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10457 [[fallthrough]];
10458
10459 case OO_PlusEqual:
10460 case OO_MinusEqual:
10461 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10462 [[fallthrough]];
10463
10464 case OO_StarEqual:
10465 case OO_SlashEqual:
10466 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10467 break;
10468
10469 case OO_PercentEqual:
10470 case OO_LessLessEqual:
10471 case OO_GreaterGreaterEqual:
10472 case OO_AmpEqual:
10473 case OO_CaretEqual:
10474 case OO_PipeEqual:
10475 OpBuilder.addAssignmentIntegralOverloads();
10476 break;
10477
10478 case OO_Exclaim:
10479 OpBuilder.addExclaimOverload();
10480 break;
10481
10482 case OO_AmpAmp:
10483 case OO_PipePipe:
10484 OpBuilder.addAmpAmpOrPipePipeOverload();
10485 break;
10486
10487 case OO_Subscript:
10488 if (Args.size() == 2)
10489 OpBuilder.addSubscriptOverloads();
10490 break;
10491
10492 case OO_ArrowStar:
10493 OpBuilder.addArrowStarOverloads();
10494 break;
10495
10496 case OO_Conditional:
10497 OpBuilder.addConditionalOperatorOverloads();
10498 OpBuilder.addGenericBinaryArithmeticOverloads();
10499 break;
10500 }
10501 }
10502
10503 void
10504 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10505 SourceLocation Loc,
10506 ArrayRef<Expr *> Args,
10507 TemplateArgumentListInfo *ExplicitTemplateArgs,
10508 OverloadCandidateSet& CandidateSet,
10509 bool PartialOverloading) {
10510 ADLResult Fns;
10511
10512 // FIXME: This approach for uniquing ADL results (and removing
10513 // redundant candidates from the set) relies on pointer-equality,
10514 // which means we need to key off the canonical decl. However,
10515 // always going back to the canonical decl might not get us the
10516 // right set of default arguments. What default arguments are
10517 // we supposed to consider on ADL candidates, anyway?
10518
10519 // FIXME: Pass in the explicit template arguments?
10520 ArgumentDependentLookup(Name, Loc, Args, Fns);
10521
10522 ArrayRef<Expr *> ReversedArgs;
10523
10524 // Erase all of the candidates we already knew about.
10525 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10526 CandEnd = CandidateSet.end();
10527 Cand != CandEnd; ++Cand)
10528 if (Cand->Function) {
10529 FunctionDecl *Fn = Cand->Function;
10530 Fns.erase(Fn);
10531 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10532 Fns.erase(FunTmpl);
10533 }
10534
10535 // For each of the ADL candidates we found, add it to the overload
10536 // set.
10537 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10538 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
10539
10540 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10541 if (ExplicitTemplateArgs)
10542 continue;
10543
10544 AddOverloadCandidate(
10545 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10546 PartialOverloading, /*AllowExplicit=*/true,
10547 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10548 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10549 AddOverloadCandidate(
10550 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10551 /*SuppressUserConversions=*/false, PartialOverloading,
10552 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10553 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10554 }
10555 } else {
10556 auto *FTD = cast<FunctionTemplateDecl>(*I);
10557 AddTemplateOverloadCandidate(
10558 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10559 /*SuppressUserConversions=*/false, PartialOverloading,
10560 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10561 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10562 *this, Args, FTD->getTemplatedDecl())) {
10563
10564 // As template candidates are not deduced immediately,
10565 // persist the array in the overload set.
10566 if (ReversedArgs.empty())
10567 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10568
10569 AddTemplateOverloadCandidate(
10570 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10571 /*SuppressUserConversions=*/false, PartialOverloading,
10572 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10573 OverloadCandidateParamOrder::Reversed);
10574 }
10575 }
10576 }
10577 }
10578
10579 namespace {
10580 enum class Comparison { Equal, Better, Worse };
10581 }
10582
10583 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10584 /// overload resolution.
10585 ///
10586 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10587 /// Cand1's first N enable_if attributes have precisely the same conditions as
10588 /// Cand2's first N enable_if attributes (where N = the number of enable_if
10589 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10590 ///
10591 /// Note that you can have a pair of candidates such that Cand1's enable_if
10592 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10593 /// worse than Cand1's.
10594 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10595 const FunctionDecl *Cand2) {
10596 // Common case: One (or both) decls don't have enable_if attrs.
10597 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10598 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10599 if (!Cand1Attr || !Cand2Attr) {
10600 if (Cand1Attr == Cand2Attr)
10601 return Comparison::Equal;
10602 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10603 }
10604
10605 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10606 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10607
10608 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10609 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10610 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10611 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10612
10613 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10614 // has fewer enable_if attributes than Cand2, and vice versa.
10615 if (!Cand1A)
10616 return Comparison::Worse;
10617 if (!Cand2A)
10618 return Comparison::Better;
10619
10620 Cand1ID.clear();
10621 Cand2ID.clear();
10622
10623 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10624 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10625 if (Cand1ID != Cand2ID)
10626 return Comparison::Worse;
10627 }
10628
10629 return Comparison::Equal;
10630 }
10631
10632 static Comparison
10633 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10634 const OverloadCandidate &Cand2) {
10635 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10636 !Cand2.Function->isMultiVersion())
10637 return Comparison::Equal;
10638
10639 // If both are invalid, they are equal. If one of them is invalid, the other
10640 // is better.
10641 if (Cand1.Function->isInvalidDecl()) {
10642 if (Cand2.Function->isInvalidDecl())
10643 return Comparison::Equal;
10644 return Comparison::Worse;
10645 }
10646 if (Cand2.Function->isInvalidDecl())
10647 return Comparison::Better;
10648
10649 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10650 // cpu_dispatch, else arbitrarily based on the identifiers.
10651 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10652 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10653 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10654 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10655
10656 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10657 return Comparison::Equal;
10658
10659 if (Cand1CPUDisp && !Cand2CPUDisp)
10660 return Comparison::Better;
10661 if (Cand2CPUDisp && !Cand1CPUDisp)
10662 return Comparison::Worse;
10663
10664 if (Cand1CPUSpec && Cand2CPUSpec) {
10665 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10666 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10667 ? Comparison::Better
10668 : Comparison::Worse;
10669
10670 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10671 FirstDiff = std::mismatch(
10672 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10673 Cand2CPUSpec->cpus_begin(),
10674 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10675 return LHS->getName() == RHS->getName();
10676 });
10677
10678 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10679 "Two different cpu-specific versions should not have the same "
10680 "identifier list, otherwise they'd be the same decl!");
10681 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10682 ? Comparison::Better
10683 : Comparison::Worse;
10684 }
10685 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10686 }
10687
10688 /// Compute the type of the implicit object parameter for the given function,
10689 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10690 /// null QualType if there is a 'matches anything' implicit object parameter.
10691 static std::optional<QualType>
10692 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10693 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10694 return std::nullopt;
10695
10696 auto *M = cast<CXXMethodDecl>(F);
10697 // Static member functions' object parameters match all types.
10698 if (M->isStatic())
10699 return QualType();
10700 return M->getFunctionObjectParameterReferenceType();
10701 }
10702
10703 // As a Clang extension, allow ambiguity among F1 and F2 if they represent
10704 // represent the same entity.
10705 static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10706 const FunctionDecl *F2) {
10707 if (declaresSameEntity(F1, F2))
10708 return true;
10709 auto PT1 = F1->getPrimaryTemplate();
10710 auto PT2 = F2->getPrimaryTemplate();
10711 if (PT1 && PT2) {
10712 if (declaresSameEntity(PT1, PT2) ||
10713 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10714 PT2->getInstantiatedFromMemberTemplate()))
10715 return true;
10716 }
10717 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10718 // different functions with same params). Consider removing this (as no test
10719 // fail w/o it).
10720 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10721 if (First) {
10722 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10723 return *T;
10724 }
10725 assert(I < F->getNumParams());
10726 return F->getParamDecl(I++)->getType();
10727 };
10728
10729 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10730 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10731
10732 if (F1NumParams != F2NumParams)
10733 return false;
10734
10735 unsigned I1 = 0, I2 = 0;
10736 for (unsigned I = 0; I != F1NumParams; ++I) {
10737 QualType T1 = NextParam(F1, I1, I == 0);
10738 QualType T2 = NextParam(F2, I2, I == 0);
10739 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10740 if (!Context.hasSameUnqualifiedType(T1, T2))
10741 return false;
10742 }
10743 return true;
10744 }
10745
10746 /// We're allowed to use constraints partial ordering only if the candidates
10747 /// have the same parameter types:
10748 /// [over.match.best.general]p2.6
10749 /// F1 and F2 are non-template functions with the same
10750 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10751 static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10752 FunctionDecl *Fn2,
10753 bool IsFn1Reversed,
10754 bool IsFn2Reversed) {
10755 assert(Fn1 && Fn2);
10756 if (Fn1->isVariadic() != Fn2->isVariadic())
10757 return false;
10758
10759 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10760 IsFn1Reversed ^ IsFn2Reversed))
10761 return false;
10762
10763 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10764 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10765 if (Mem1 && Mem2) {
10766 // if they are member functions, both are direct members of the same class,
10767 // and
10768 if (Mem1->getParent() != Mem2->getParent())
10769 return false;
10770 // if both are non-static member functions, they have the same types for
10771 // their object parameters
10772 if (Mem1->isInstance() && Mem2->isInstance() &&
10773 !S.getASTContext().hasSameType(
10774 Mem1->getFunctionObjectParameterReferenceType(),
10775 Mem1->getFunctionObjectParameterReferenceType()))
10776 return false;
10777 }
10778 return true;
10779 }
10780
10781 static FunctionDecl *
10782 getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10783 bool IsFn1Reversed, bool IsFn2Reversed) {
10784 if (!Fn1 || !Fn2)
10785 return nullptr;
10786
10787 // C++ [temp.constr.order]:
10788 // A non-template function F1 is more partial-ordering-constrained than a
10789 // non-template function F2 if:
10790 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10791 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10792
10793 if (Cand1IsSpecialization || Cand2IsSpecialization)
10794 return nullptr;
10795
10796 // - they have the same non-object-parameter-type-lists, and [...]
10797 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10798 IsFn2Reversed))
10799 return nullptr;
10800
10801 // - the declaration of F1 is more constrained than the declaration of F2.
10802 return S.getMoreConstrainedFunction(Fn1, Fn2);
10803 }
10804
10805 /// isBetterOverloadCandidate - Determines whether the first overload
10806 /// candidate is a better candidate than the second (C++ 13.3.3p1).
10807 bool clang::isBetterOverloadCandidate(
10808 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10809 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10810 bool PartialOverloading) {
10811 // Define viable functions to be better candidates than non-viable
10812 // functions.
10813 if (!Cand2.Viable)
10814 return Cand1.Viable;
10815 else if (!Cand1.Viable)
10816 return false;
10817
10818 // [CUDA] A function with 'never' preference is marked not viable, therefore
10819 // is never shown up here. The worst preference shown up here is 'wrong side',
10820 // e.g. an H function called by a HD function in device compilation. This is
10821 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10822 // function which is called only by an H function. A deferred diagnostic will
10823 // be triggered if it is emitted. However a wrong-sided function is still
10824 // a viable candidate here.
10825 //
10826 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10827 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10828 // can be emitted, Cand1 is not better than Cand2. This rule should have
10829 // precedence over other rules.
10830 //
10831 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10832 // other rules should be used to determine which is better. This is because
10833 // host/device based overloading resolution is mostly for determining
10834 // viability of a function. If two functions are both viable, other factors
10835 // should take precedence in preference, e.g. the standard-defined preferences
10836 // like argument conversion ranks or enable_if partial-ordering. The
10837 // preference for pass-object-size parameters is probably most similar to a
10838 // type-based-overloading decision and so should take priority.
10839 //
10840 // If other rules cannot determine which is better, CUDA preference will be
10841 // used again to determine which is better.
10842 //
10843 // TODO: Currently IdentifyPreference does not return correct values
10844 // for functions called in global variable initializers due to missing
10845 // correct context about device/host. Therefore we can only enforce this
10846 // rule when there is a caller. We should enforce this rule for functions
10847 // in global variable initializers once proper context is added.
10848 //
10849 // TODO: We can only enable the hostness based overloading resolution when
10850 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10851 // overloading resolution diagnostics.
10852 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10853 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10854 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10855 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10856 bool IsCand1ImplicitHD =
10857 SemaCUDA::isImplicitHostDeviceFunction(Cand1.Function);
10858 bool IsCand2ImplicitHD =
10859 SemaCUDA::isImplicitHostDeviceFunction(Cand2.Function);
10860 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10861 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10862 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10863 // The implicit HD function may be a function in a system header which
10864 // is forced by pragma. In device compilation, if we prefer HD candidates
10865 // over wrong-sided candidates, overloading resolution may change, which
10866 // may result in non-deferrable diagnostics. As a workaround, we let
10867 // implicit HD candidates take equal preference as wrong-sided candidates.
10868 // This will preserve the overloading resolution.
10869 // TODO: We still need special handling of implicit HD functions since
10870 // they may incur other diagnostics to be deferred. We should make all
10871 // host/device related diagnostics deferrable and remove special handling
10872 // of implicit HD functions.
10873 auto EmitThreshold =
10874 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10875 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10876 ? SemaCUDA::CFP_Never
10877 : SemaCUDA::CFP_WrongSide;
10878 auto Cand1Emittable = P1 > EmitThreshold;
10879 auto Cand2Emittable = P2 > EmitThreshold;
10880 if (Cand1Emittable && !Cand2Emittable)
10881 return true;
10882 if (!Cand1Emittable && Cand2Emittable)
10883 return false;
10884 }
10885 }
10886
10887 // C++ [over.match.best]p1: (Changed in C++23)
10888 //
10889 // -- if F is a static member function, ICS1(F) is defined such
10890 // that ICS1(F) is neither better nor worse than ICS1(G) for
10891 // any function G, and, symmetrically, ICS1(G) is neither
10892 // better nor worse than ICS1(F).
10893 unsigned StartArg = 0;
10894 if (!Cand1.TookAddressOfOverload &&
10895 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
10896 StartArg = 1;
10897
10898 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10899 // We don't allow incompatible pointer conversions in C++.
10900 if (!S.getLangOpts().CPlusPlus)
10901 return ICS.isStandard() &&
10902 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10903
10904 // The only ill-formed conversion we allow in C++ is the string literal to
10905 // char* conversion, which is only considered ill-formed after C++11.
10906 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10907 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10908 };
10909
10910 // Define functions that don't require ill-formed conversions for a given
10911 // argument to be better candidates than functions that do.
10912 unsigned NumArgs = Cand1.Conversions.size();
10913 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10914 bool HasBetterConversion = false;
10915 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10916 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10917 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10918 if (Cand1Bad != Cand2Bad) {
10919 if (Cand1Bad)
10920 return false;
10921 HasBetterConversion = true;
10922 }
10923 }
10924
10925 if (HasBetterConversion)
10926 return true;
10927
10928 // C++ [over.match.best]p1:
10929 // A viable function F1 is defined to be a better function than another
10930 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10931 // conversion sequence than ICSi(F2), and then...
10932 bool HasWorseConversion = false;
10933 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10934 switch (CompareImplicitConversionSequences(S, Loc,
10935 Cand1.Conversions[ArgIdx],
10936 Cand2.Conversions[ArgIdx])) {
10937 case ImplicitConversionSequence::Better:
10938 // Cand1 has a better conversion sequence.
10939 HasBetterConversion = true;
10940 break;
10941
10942 case ImplicitConversionSequence::Worse:
10943 if (Cand1.Function && Cand2.Function &&
10944 Cand1.isReversed() != Cand2.isReversed() &&
10945 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10946 // Work around large-scale breakage caused by considering reversed
10947 // forms of operator== in C++20:
10948 //
10949 // When comparing a function against a reversed function, if we have a
10950 // better conversion for one argument and a worse conversion for the
10951 // other, the implicit conversion sequences are treated as being equally
10952 // good.
10953 //
10954 // This prevents a comparison function from being considered ambiguous
10955 // with a reversed form that is written in the same way.
10956 //
10957 // We diagnose this as an extension from CreateOverloadedBinOp.
10958 HasWorseConversion = true;
10959 break;
10960 }
10961
10962 // Cand1 can't be better than Cand2.
10963 return false;
10964
10965 case ImplicitConversionSequence::Indistinguishable:
10966 // Do nothing.
10967 break;
10968 }
10969 }
10970
10971 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10972 // ICSj(F2), or, if not that,
10973 if (HasBetterConversion && !HasWorseConversion)
10974 return true;
10975
10976 // -- the context is an initialization by user-defined conversion
10977 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10978 // from the return type of F1 to the destination type (i.e.,
10979 // the type of the entity being initialized) is a better
10980 // conversion sequence than the standard conversion sequence
10981 // from the return type of F2 to the destination type.
10982 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10983 Cand1.Function && Cand2.Function &&
10984 isa<CXXConversionDecl>(Cand1.Function) &&
10985 isa<CXXConversionDecl>(Cand2.Function)) {
10986
10987 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10988 // First check whether we prefer one of the conversion functions over the
10989 // other. This only distinguishes the results in non-standard, extension
10990 // cases such as the conversion from a lambda closure type to a function
10991 // pointer or block.
10992 ImplicitConversionSequence::CompareKind Result =
10993 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10994 if (Result == ImplicitConversionSequence::Indistinguishable)
10995 Result = CompareStandardConversionSequences(S, Loc,
10996 Cand1.FinalConversion,
10997 Cand2.FinalConversion);
10998
10999 if (Result != ImplicitConversionSequence::Indistinguishable)
11000 return Result == ImplicitConversionSequence::Better;
11001
11002 // FIXME: Compare kind of reference binding if conversion functions
11003 // convert to a reference type used in direct reference binding, per
11004 // C++14 [over.match.best]p1 section 2 bullet 3.
11005 }
11006
11007 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11008 // as combined with the resolution to CWG issue 243.
11009 //
11010 // When the context is initialization by constructor ([over.match.ctor] or
11011 // either phase of [over.match.list]), a constructor is preferred over
11012 // a conversion function.
11013 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11014 Cand1.Function && Cand2.Function &&
11015 isa<CXXConstructorDecl>(Cand1.Function) !=
11016 isa<CXXConstructorDecl>(Cand2.Function))
11017 return isa<CXXConstructorDecl>(Cand1.Function);
11018
11019 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11020 return Cand2.StrictPackMatch;
11021
11022 // -- F1 is a non-template function and F2 is a function template
11023 // specialization, or, if not that,
11024 bool Cand1IsSpecialization = Cand1.Function &&
11025 Cand1.Function->getPrimaryTemplate();
11026 bool Cand2IsSpecialization = Cand2.Function &&
11027 Cand2.Function->getPrimaryTemplate();
11028 if (Cand1IsSpecialization != Cand2IsSpecialization)
11029 return Cand2IsSpecialization;
11030
11031 // -- F1 and F2 are function template specializations, and the function
11032 // template for F1 is more specialized than the template for F2
11033 // according to the partial ordering rules described in 14.5.5.2, or,
11034 // if not that,
11035 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11036 const auto *Obj1Context =
11037 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11038 const auto *Obj2Context =
11039 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11040 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11041 Cand1.Function->getPrimaryTemplate(),
11042 Cand2.Function->getPrimaryTemplate(), Loc,
11043 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
11044 : TPOC_Call,
11045 Cand1.ExplicitCallArguments,
11046 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11047 : QualType{},
11048 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11049 : QualType{},
11050 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11051 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11052 }
11053 }
11054
11055 // -— F1 and F2 are non-template functions and F1 is more
11056 // partial-ordering-constrained than F2 [...],
11057 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11058 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11059 Cand2.isReversed());
11060 F && F == Cand1.Function)
11061 return true;
11062
11063 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11064 // class B of D, and for all arguments the corresponding parameters of
11065 // F1 and F2 have the same type.
11066 // FIXME: Implement the "all parameters have the same type" check.
11067 bool Cand1IsInherited =
11068 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11069 bool Cand2IsInherited =
11070 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11071 if (Cand1IsInherited != Cand2IsInherited)
11072 return Cand2IsInherited;
11073 else if (Cand1IsInherited) {
11074 assert(Cand2IsInherited);
11075 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11076 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11077 if (Cand1Class->isDerivedFrom(Cand2Class))
11078 return true;
11079 if (Cand2Class->isDerivedFrom(Cand1Class))
11080 return false;
11081 // Inherited from sibling base classes: still ambiguous.
11082 }
11083
11084 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11085 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11086 // with reversed order of parameters and F1 is not
11087 //
11088 // We rank reversed + different operator as worse than just reversed, but
11089 // that comparison can never happen, because we only consider reversing for
11090 // the maximally-rewritten operator (== or <=>).
11091 if (Cand1.RewriteKind != Cand2.RewriteKind)
11092 return Cand1.RewriteKind < Cand2.RewriteKind;
11093
11094 // Check C++17 tie-breakers for deduction guides.
11095 {
11096 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11097 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11098 if (Guide1 && Guide2) {
11099 // -- F1 is generated from a deduction-guide and F2 is not
11100 if (Guide1->isImplicit() != Guide2->isImplicit())
11101 return Guide2->isImplicit();
11102
11103 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11104 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11105 return true;
11106 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11107 return false;
11108
11109 // --F1 is generated from a non-template constructor and F2 is generated
11110 // from a constructor template
11111 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11112 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11113 if (Constructor1 && Constructor2) {
11114 bool isC1Templated = Constructor1->getTemplatedKind() !=
11115 FunctionDecl::TemplatedKind::TK_NonTemplate;
11116 bool isC2Templated = Constructor2->getTemplatedKind() !=
11117 FunctionDecl::TemplatedKind::TK_NonTemplate;
11118 if (isC1Templated != isC2Templated)
11119 return isC2Templated;
11120 }
11121 }
11122 }
11123
11124 // Check for enable_if value-based overload resolution.
11125 if (Cand1.Function && Cand2.Function) {
11126 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11127 if (Cmp != Comparison::Equal)
11128 return Cmp == Comparison::Better;
11129 }
11130
11131 bool HasPS1 = Cand1.Function != nullptr &&
11132 functionHasPassObjectSizeParams(Cand1.Function);
11133 bool HasPS2 = Cand2.Function != nullptr &&
11134 functionHasPassObjectSizeParams(Cand2.Function);
11135 if (HasPS1 != HasPS2 && HasPS1)
11136 return true;
11137
11138 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11139 if (MV == Comparison::Better)
11140 return true;
11141 if (MV == Comparison::Worse)
11142 return false;
11143
11144 // If other rules cannot determine which is better, CUDA preference is used
11145 // to determine which is better.
11146 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11147 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11148 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11149 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11150 }
11151
11152 // General member function overloading is handled above, so this only handles
11153 // constructors with address spaces.
11154 // This only handles address spaces since C++ has no other
11155 // qualifier that can be used with constructors.
11156 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11157 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11158 if (CD1 && CD2) {
11159 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11160 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11161 if (AS1 != AS2) {
11162 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1, S.getASTContext()))
11163 return true;
11164 if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2, S.getASTContext()))
11165 return false;
11166 }
11167 }
11168
11169 return false;
11170 }
11171
11172 /// Determine whether two declarations are "equivalent" for the purposes of
11173 /// name lookup and overload resolution. This applies when the same internal/no
11174 /// linkage entity is defined by two modules (probably by textually including
11175 /// the same header). In such a case, we don't consider the declarations to
11176 /// declare the same entity, but we also don't want lookups with both
11177 /// declarations visible to be ambiguous in some cases (this happens when using
11178 /// a modularized libstdc++).
11179 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11180 const NamedDecl *B) {
11181 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11182 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11183 if (!VA || !VB)
11184 return false;
11185
11186 // The declarations must be declaring the same name as an internal linkage
11187 // entity in different modules.
11188 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11189 VB->getDeclContext()->getRedeclContext()) ||
11190 getOwningModule(VA) == getOwningModule(VB) ||
11191 VA->isExternallyVisible() || VB->isExternallyVisible())
11192 return false;
11193
11194 // Check that the declarations appear to be equivalent.
11195 //
11196 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11197 // For constants and functions, we should check the initializer or body is
11198 // the same. For non-constant variables, we shouldn't allow it at all.
11199 if (Context.hasSameType(VA->getType(), VB->getType()))
11200 return true;
11201
11202 // Enum constants within unnamed enumerations will have different types, but
11203 // may still be similar enough to be interchangeable for our purposes.
11204 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11205 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11206 // Only handle anonymous enums. If the enumerations were named and
11207 // equivalent, they would have been merged to the same type.
11208 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11209 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11210 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11211 !Context.hasSameType(EnumA->getIntegerType(),
11212 EnumB->getIntegerType()))
11213 return false;
11214 // Allow this only if the value is the same for both enumerators.
11215 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11216 }
11217 }
11218
11219 // Nothing else is sufficiently similar.
11220 return false;
11221 }
11222
11223 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11224 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11225 assert(D && "Unknown declaration");
11226 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11227
11228 Module *M = getOwningModule(D);
11229 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11230 << !M << (M ? M->getFullModuleName() : "");
11231
11232 for (auto *E : Equiv) {
11233 Module *M = getOwningModule(E);
11234 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11235 << !M << (M ? M->getFullModuleName() : "");
11236 }
11237 }
11238
11239 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11240 return FailureKind == ovl_fail_bad_deduction &&
11241 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11242 TemplateDeductionResult::ConstraintsNotSatisfied &&
11243 static_cast<CNSInfo *>(DeductionFailure.Data)
11244 ->Satisfaction.ContainsErrors;
11245 }
11246
11247 void OverloadCandidateSet::AddDeferredTemplateCandidate(
11248 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11249 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11250 bool PartialOverloading, bool AllowExplicit,
11251 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11252 bool AggregateCandidateDeduction) {
11253
11254 auto *C =
11255 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11256
11257 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11258 {nullptr, DeferredFunctionTemplateOverloadCandidate::Function,
11259 /*AllowObjCConversionOnExplicit=*/false,
11260 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11261 PartialOverloading, AggregateCandidateDeduction},
11262 FunctionTemplate,
11263 FoundDecl,
11264 Args,
11265 IsADLCandidate,
11266 PO};
11267
11268 HasDeferredTemplateConstructors |=
11269 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11270 }
11271
11272 void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11273 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11274 CXXRecordDecl *ActingContext, QualType ObjectType,
11275 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11276 bool SuppressUserConversions, bool PartialOverloading,
11277 OverloadCandidateParamOrder PO) {
11278
11279 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11280
11281 auto *C =
11282 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11283
11284 C = new (C) DeferredMethodTemplateOverloadCandidate{
11285 {nullptr, DeferredFunctionTemplateOverloadCandidate::Method,
11286 /*AllowObjCConversionOnExplicit=*/false,
11287 /*AllowResultConversion=*/false,
11288 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11289 /*AggregateCandidateDeduction=*/false},
11290 MethodTmpl,
11291 FoundDecl,
11292 Args,
11293 ActingContext,
11294 ObjectClassification,
11295 ObjectType,
11296 PO};
11297 }
11298
11299 void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11300 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11301 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11302 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11303 bool AllowResultConversion) {
11304
11305 auto *C =
11306 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11307
11308 C = new (C) DeferredConversionTemplateOverloadCandidate{
11309 {nullptr, DeferredFunctionTemplateOverloadCandidate::Conversion,
11310 AllowObjCConversionOnExplicit, AllowResultConversion,
11311 /*AllowExplicit=*/false,
11312 /*SuppressUserConversions=*/false,
11313 /*PartialOverloading*/ false,
11314 /*AggregateCandidateDeduction=*/false},
11315 FunctionTemplate,
11316 FoundDecl,
11317 ActingContext,
11318 From,
11319 ToType};
11320 }
11321
11322 static void
11323 AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11324 DeferredMethodTemplateOverloadCandidate &C) {
11325
11326 AddMethodTemplateCandidateImmediately(
11327 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11328 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11329 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11330 }
11331
11332 static void
11333 AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11334 DeferredFunctionTemplateOverloadCandidate &C) {
11335 AddTemplateOverloadCandidateImmediately(
11336 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11337 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11338 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11339 C.AggregateCandidateDeduction);
11340 }
11341
11342 static void
11343 AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11344 DeferredConversionTemplateOverloadCandidate &C) {
11345 return AddTemplateConversionCandidateImmediately(
11346 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11347 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11348 C.AllowResultConversion);
11349 }
11350
11351 void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11352 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11353 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11354 while (Cand) {
11355 switch (Cand->Kind) {
11356 case DeferredTemplateOverloadCandidate::Function:
11357 AddTemplateOverloadCandidate(
11358 S, *this,
11359 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11360 break;
11361 case DeferredTemplateOverloadCandidate::Method:
11362 AddTemplateOverloadCandidate(
11363 S, *this,
11364 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11365 break;
11366 case DeferredTemplateOverloadCandidate::Conversion:
11367 AddTemplateOverloadCandidate(
11368 S, *this,
11369 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11370 break;
11371 }
11372 Cand = Cand->Next;
11373 }
11374 FirstDeferredCandidate = nullptr;
11375 DeferredCandidatesCount = 0;
11376 }
11377
11378 OverloadingResult
11379 OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11380 Best->Best = true;
11381 if (Best->Function && Best->Function->isDeleted())
11382 return OR_Deleted;
11383 return OR_Success;
11384 }
11385
11386 void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11387 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11388 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11389 // are accepted by both clang and NVCC. However, during a particular
11390 // compilation mode only one call variant is viable. We need to
11391 // exclude non-viable overload candidates from consideration based
11392 // only on their host/device attributes. Specifically, if one
11393 // candidate call is WrongSide and the other is SameSide, we ignore
11394 // the WrongSide candidate.
11395 // We only need to remove wrong-sided candidates here if
11396 // -fgpu-exclude-wrong-side-overloads is off. When
11397 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11398 // uniformly in isBetterOverloadCandidate.
11399 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11400 return;
11401 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11402
11403 bool ContainsSameSideCandidate =
11404 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11405 // Check viable function only.
11406 return Cand->Viable && Cand->Function &&
11407 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11408 SemaCUDA::CFP_SameSide;
11409 });
11410
11411 if (!ContainsSameSideCandidate)
11412 return;
11413
11414 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11415 // Check viable function only to avoid unnecessary data copying/moving.
11416 return Cand->Viable && Cand->Function &&
11417 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11418 SemaCUDA::CFP_WrongSide;
11419 };
11420 llvm::erase_if(Candidates, IsWrongSideCandidate);
11421 }
11422
11423 /// Computes the best viable function (C++ 13.3.3)
11424 /// within an overload candidate set.
11425 ///
11426 /// \param Loc The location of the function name (or operator symbol) for
11427 /// which overload resolution occurs.
11428 ///
11429 /// \param Best If overload resolution was successful or found a deleted
11430 /// function, \p Best points to the candidate function found.
11431 ///
11432 /// \returns The result of overload resolution.
11433 OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11434 SourceLocation Loc,
11435 iterator &Best) {
11436
11437 assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11438 DeferredCandidatesCount == 0) &&
11439 "Unexpected deferred template candidates");
11440
11441 bool TwoPhaseResolution =
11442 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11443
11444 if (TwoPhaseResolution) {
11445 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11446 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11447 if (!(HasDeferredTemplateConstructors &&
11448 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11449 return Res;
11450 }
11451 }
11452
11453 InjectNonDeducedTemplateCandidates(S);
11454 return BestViableFunctionImpl(S, Loc, Best);
11455 }
11456
11457 OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11458 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11459
11460 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11461 Candidates.reserve(this->Candidates.size());
11462 std::transform(this->Candidates.begin(), this->Candidates.end(),
11463 std::back_inserter(Candidates),
11464 [](OverloadCandidate &Cand) { return &Cand; });
11465
11466 if (S.getLangOpts().CUDA)
11467 CudaExcludeWrongSideCandidates(S, Candidates);
11468
11469 Best = end();
11470 for (auto *Cand : Candidates) {
11471 Cand->Best = false;
11472 if (Cand->Viable) {
11473 if (Best == end() ||
11474 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11475 Best = Cand;
11476 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11477 // This candidate has constraint that we were unable to evaluate because
11478 // it referenced an expression that contained an error. Rather than fall
11479 // back onto a potentially unintended candidate (made worse by
11480 // subsuming constraints), treat this as 'no viable candidate'.
11481 Best = end();
11482 return OR_No_Viable_Function;
11483 }
11484 }
11485
11486 // If we didn't find any viable functions, abort.
11487 if (Best == end())
11488 return OR_No_Viable_Function;
11489
11490 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11491 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11492 PendingBest.push_back(&*Best);
11493 Best->Best = true;
11494
11495 // Make sure that this function is better than every other viable
11496 // function. If not, we have an ambiguity.
11497 while (!PendingBest.empty()) {
11498 auto *Curr = PendingBest.pop_back_val();
11499 for (auto *Cand : Candidates) {
11500 if (Cand->Viable && !Cand->Best &&
11501 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11502 PendingBest.push_back(Cand);
11503 Cand->Best = true;
11504
11505 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
11506 Curr->Function))
11507 EquivalentCands.push_back(Cand->Function);
11508 else
11509 Best = end();
11510 }
11511 }
11512 }
11513
11514 if (Best == end())
11515 return OR_Ambiguous;
11516
11517 OverloadingResult R = ResultForBestCandidate(Best);
11518
11519 if (!EquivalentCands.empty())
11520 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
11521 EquivalentCands);
11522 return R;
11523 }
11524
11525 namespace {
11526
11527 enum OverloadCandidateKind {
11528 oc_function,
11529 oc_method,
11530 oc_reversed_binary_operator,
11531 oc_constructor,
11532 oc_implicit_default_constructor,
11533 oc_implicit_copy_constructor,
11534 oc_implicit_move_constructor,
11535 oc_implicit_copy_assignment,
11536 oc_implicit_move_assignment,
11537 oc_implicit_equality_comparison,
11538 oc_inherited_constructor
11539 };
11540
11541 enum OverloadCandidateSelect {
11542 ocs_non_template,
11543 ocs_template,
11544 ocs_described_template,
11545 };
11546
11547 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11548 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11549 const FunctionDecl *Fn,
11550 OverloadCandidateRewriteKind CRK,
11551 std::string &Description) {
11552
11553 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11554 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11555 isTemplate = true;
11556 Description = S.getTemplateArgumentBindingsText(
11557 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11558 }
11559
11560 OverloadCandidateSelect Select = [&]() {
11561 if (!Description.empty())
11562 return ocs_described_template;
11563 return isTemplate ? ocs_template : ocs_non_template;
11564 }();
11565
11566 OverloadCandidateKind Kind = [&]() {
11567 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11568 return oc_implicit_equality_comparison;
11569
11570 if (CRK & CRK_Reversed)
11571 return oc_reversed_binary_operator;
11572
11573 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11574 if (!Ctor->isImplicit()) {
11575 if (isa<ConstructorUsingShadowDecl>(Found))
11576 return oc_inherited_constructor;
11577 else
11578 return oc_constructor;
11579 }
11580
11581 if (Ctor->isDefaultConstructor())
11582 return oc_implicit_default_constructor;
11583
11584 if (Ctor->isMoveConstructor())
11585 return oc_implicit_move_constructor;
11586
11587 assert(Ctor->isCopyConstructor() &&
11588 "unexpected sort of implicit constructor");
11589 return oc_implicit_copy_constructor;
11590 }
11591
11592 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11593 // This actually gets spelled 'candidate function' for now, but
11594 // it doesn't hurt to split it out.
11595 if (!Meth->isImplicit())
11596 return oc_method;
11597
11598 if (Meth->isMoveAssignmentOperator())
11599 return oc_implicit_move_assignment;
11600
11601 if (Meth->isCopyAssignmentOperator())
11602 return oc_implicit_copy_assignment;
11603
11604 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11605 return oc_method;
11606 }
11607
11608 return oc_function;
11609 }();
11610
11611 return std::make_pair(Kind, Select);
11612 }
11613
11614 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11615 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11616 // set.
11617 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11618 S.Diag(FoundDecl->getLocation(),
11619 diag::note_ovl_candidate_inherited_constructor)
11620 << Shadow->getNominatedBaseClass();
11621 }
11622
11623 } // end anonymous namespace
11624
11625 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11626 const FunctionDecl *FD) {
11627 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11628 bool AlwaysTrue;
11629 if (EnableIf->getCond()->isValueDependent() ||
11630 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11631 return false;
11632 if (!AlwaysTrue)
11633 return false;
11634 }
11635 return true;
11636 }
11637
11638 /// Returns true if we can take the address of the function.
11639 ///
11640 /// \param Complain - If true, we'll emit a diagnostic
11641 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11642 /// we in overload resolution?
11643 /// \param Loc - The location of the statement we're complaining about. Ignored
11644 /// if we're not complaining, or if we're in overload resolution.
11645 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11646 bool Complain,
11647 bool InOverloadResolution,
11648 SourceLocation Loc) {
11649 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11650 if (Complain) {
11651 if (InOverloadResolution)
11652 S.Diag(FD->getBeginLoc(),
11653 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11654 else
11655 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11656 }
11657 return false;
11658 }
11659
11660 if (FD->getTrailingRequiresClause()) {
11661 ConstraintSatisfaction Satisfaction;
11662 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11663 return false;
11664 if (!Satisfaction.IsSatisfied) {
11665 if (Complain) {
11666 if (InOverloadResolution) {
11667 SmallString<128> TemplateArgString;
11668 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11669 TemplateArgString += " ";
11670 TemplateArgString += S.getTemplateArgumentBindingsText(
11671 FunTmpl->getTemplateParameters(),
11672 *FD->getTemplateSpecializationArgs());
11673 }
11674
11675 S.Diag(FD->getBeginLoc(),
11676 diag::note_ovl_candidate_unsatisfied_constraints)
11677 << TemplateArgString;
11678 } else
11679 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11680 << FD;
11681 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11682 }
11683 return false;
11684 }
11685 }
11686
11687 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11688 return P->hasAttr<PassObjectSizeAttr>();
11689 });
11690 if (I == FD->param_end())
11691 return true;
11692
11693 if (Complain) {
11694 // Add one to ParamNo because it's user-facing
11695 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11696 if (InOverloadResolution)
11697 S.Diag(FD->getLocation(),
11698 diag::note_ovl_candidate_has_pass_object_size_params)
11699 << ParamNo;
11700 else
11701 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11702 << FD << ParamNo;
11703 }
11704 return false;
11705 }
11706
11707 static bool checkAddressOfCandidateIsAvailable(Sema &S,
11708 const FunctionDecl *FD) {
11709 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11710 /*InOverloadResolution=*/true,
11711 /*Loc=*/SourceLocation());
11712 }
11713
11714 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11715 bool Complain,
11716 SourceLocation Loc) {
11717 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11718 /*InOverloadResolution=*/false,
11719 Loc);
11720 }
11721
11722 // Don't print candidates other than the one that matches the calling
11723 // convention of the call operator, since that is guaranteed to exist.
11724 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11725 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11726
11727 if (!ConvD)
11728 return false;
11729 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11730 if (!RD->isLambda())
11731 return false;
11732
11733 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11734 CallingConv CallOpCC =
11735 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11736 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11737 CallingConv ConvToCC =
11738 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11739
11740 return ConvToCC != CallOpCC;
11741 }
11742
11743 // Notes the location of an overload candidate.
11744 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11745 OverloadCandidateRewriteKind RewriteKind,
11746 QualType DestType, bool TakingAddress) {
11747 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11748 return;
11749 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11750 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11751 return;
11752 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11753 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11754 return;
11755 if (shouldSkipNotingLambdaConversionDecl(Fn))
11756 return;
11757
11758 std::string FnDesc;
11759 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11760 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11761 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11762 << (unsigned)KSPair.first << (unsigned)KSPair.second
11763 << Fn << FnDesc;
11764
11765 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11766 Diag(Fn->getLocation(), PD);
11767 MaybeEmitInheritedConstructorNote(*this, Found);
11768 }
11769
11770 static void
11771 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11772 // Perhaps the ambiguity was caused by two atomic constraints that are
11773 // 'identical' but not equivalent:
11774 //
11775 // void foo() requires (sizeof(T) > 4) { } // #1
11776 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11777 //
11778 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11779 // #2 to subsume #1, but these constraint are not considered equivalent
11780 // according to the subsumption rules because they are not the same
11781 // source-level construct. This behavior is quite confusing and we should try
11782 // to help the user figure out what happened.
11783
11784 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11785 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11786 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11787 if (!I->Function)
11788 continue;
11789 SmallVector<AssociatedConstraint, 3> AC;
11790 if (auto *Template = I->Function->getPrimaryTemplate())
11791 Template->getAssociatedConstraints(AC);
11792 else
11793 I->Function->getAssociatedConstraints(AC);
11794 if (AC.empty())
11795 continue;
11796 if (FirstCand == nullptr) {
11797 FirstCand = I->Function;
11798 FirstAC = AC;
11799 } else if (SecondCand == nullptr) {
11800 SecondCand = I->Function;
11801 SecondAC = AC;
11802 } else {
11803 // We have more than one pair of constrained functions - this check is
11804 // expensive and we'd rather not try to diagnose it.
11805 return;
11806 }
11807 }
11808 if (!SecondCand)
11809 return;
11810 // The diagnostic can only happen if there are associated constraints on
11811 // both sides (there needs to be some identical atomic constraint).
11812 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11813 SecondCand, SecondAC))
11814 // Just show the user one diagnostic, they'll probably figure it out
11815 // from here.
11816 return;
11817 }
11818
11819 // Notes the location of all overload candidates designated through
11820 // OverloadedExpr
11821 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11822 bool TakingAddress) {
11823 assert(OverloadedExpr->getType() == Context.OverloadTy);
11824
11825 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11826 OverloadExpr *OvlExpr = Ovl.Expression;
11827
11828 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11829 IEnd = OvlExpr->decls_end();
11830 I != IEnd; ++I) {
11831 if (FunctionTemplateDecl *FunTmpl =
11832 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11833 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11834 TakingAddress);
11835 } else if (FunctionDecl *Fun
11836 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11837 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11838 }
11839 }
11840 }
11841
11842 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
11843 /// "lead" diagnostic; it will be given two arguments, the source and
11844 /// target types of the conversion.
11845 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11846 Sema &S,
11847 SourceLocation CaretLoc,
11848 const PartialDiagnostic &PDiag) const {
11849 S.Diag(CaretLoc, PDiag)
11850 << Ambiguous.getFromType() << Ambiguous.getToType();
11851 unsigned CandsShown = 0;
11852 AmbiguousConversionSequence::const_iterator I, E;
11853 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11854 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11855 break;
11856 ++CandsShown;
11857 S.NoteOverloadCandidate(I->first, I->second);
11858 }
11859 S.Diags.overloadCandidatesShown(CandsShown);
11860 if (I != E)
11861 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11862 }
11863
11864 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11865 unsigned I, bool TakingCandidateAddress) {
11866 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11867 assert(Conv.isBad());
11868 assert(Cand->Function && "for now, candidate must be a function");
11869 FunctionDecl *Fn = Cand->Function;
11870
11871 // There's a conversion slot for the object argument if this is a
11872 // non-constructor method. Note that 'I' corresponds the
11873 // conversion-slot index.
11874 bool isObjectArgument = false;
11875 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11876 !isa<CXXConstructorDecl>(Fn)) {
11877 if (I == 0)
11878 isObjectArgument = true;
11879 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11880 I--;
11881 }
11882
11883 std::string FnDesc;
11884 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11885 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11886 FnDesc);
11887
11888 Expr *FromExpr = Conv.Bad.FromExpr;
11889 QualType FromTy = Conv.Bad.getFromType();
11890 QualType ToTy = Conv.Bad.getToType();
11891 SourceRange ToParamRange;
11892
11893 // FIXME: In presence of parameter packs we can't determine parameter range
11894 // reliably, as we don't have access to instantiation.
11895 bool HasParamPack =
11896 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11897 return Parm->isParameterPack();
11898 });
11899 if (!isObjectArgument && !HasParamPack)
11900 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11901
11902 if (FromTy == S.Context.OverloadTy) {
11903 assert(FromExpr && "overload set argument came from implicit argument?");
11904 Expr *E = FromExpr->IgnoreParens();
11905 if (isa<UnaryOperator>(E))
11906 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11907 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11908
11909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11910 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11911 << ToParamRange << ToTy << Name << I + 1;
11912 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11913 return;
11914 }
11915
11916 // Do some hand-waving analysis to see if the non-viability is due
11917 // to a qualifier mismatch.
11918 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11919 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11920 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11921 CToTy = RT->getPointeeType();
11922 else {
11923 // TODO: detect and diagnose the full richness of const mismatches.
11924 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11925 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11926 CFromTy = FromPT->getPointeeType();
11927 CToTy = ToPT->getPointeeType();
11928 }
11929 }
11930
11931 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11932 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11933 Qualifiers FromQs = CFromTy.getQualifiers();
11934 Qualifiers ToQs = CToTy.getQualifiers();
11935
11936 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11937 if (isObjectArgument)
11938 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11939 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11940 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11941 else
11942 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11943 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11944 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11945 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11946 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11947 return;
11948 }
11949
11950 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11951 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11952 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11953 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11954 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11955 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11956 return;
11957 }
11958
11959 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11960 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11961 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11962 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11963 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11964 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11965 return;
11966 }
11967
11968 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11969 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11970 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11971 << FromTy << !!FromQs.getPointerAuth()
11972 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11973 << ToQs.getPointerAuth().getAsString() << I + 1
11974 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11975 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11976 return;
11977 }
11978
11979 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11980 assert(CVR && "expected qualifiers mismatch");
11981
11982 if (isObjectArgument) {
11983 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11984 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11985 << FromTy << (CVR - 1);
11986 } else {
11987 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11988 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11989 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11990 }
11991 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11992 return;
11993 }
11994
11995 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11996 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11997 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11998 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11999 << (unsigned)isObjectArgument << I + 1
12000 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12001 << ToParamRange;
12002 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12003 return;
12004 }
12005
12006 // Special diagnostic for failure to convert an initializer list, since
12007 // telling the user that it has type void is not useful.
12008 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12009 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12010 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12011 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12012 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12013 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12014 ? 2
12015 : 0);
12016 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12017 return;
12018 }
12019
12020 // Diagnose references or pointers to incomplete types differently,
12021 // since it's far from impossible that the incompleteness triggered
12022 // the failure.
12023 QualType TempFromTy = FromTy.getNonReferenceType();
12024 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12025 TempFromTy = PTy->getPointeeType();
12026 if (TempFromTy->isIncompleteType()) {
12027 // Emit the generic diagnostic and, optionally, add the hints to it.
12028 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12029 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12030 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12031 << (unsigned)(Cand->Fix.Kind);
12032
12033 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12034 return;
12035 }
12036
12037 // Diagnose base -> derived pointer conversions.
12038 unsigned BaseToDerivedConversion = 0;
12039 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12040 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12041 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12042 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12043 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12044 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12045 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12046 FromPtrTy->getPointeeType()))
12047 BaseToDerivedConversion = 1;
12048 }
12049 } else if (const ObjCObjectPointerType *FromPtrTy
12050 = FromTy->getAs<ObjCObjectPointerType>()) {
12051 if (const ObjCObjectPointerType *ToPtrTy
12052 = ToTy->getAs<ObjCObjectPointerType>())
12053 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12054 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12055 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12056 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12057 FromIface->isSuperClassOf(ToIface))
12058 BaseToDerivedConversion = 2;
12059 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12060 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12061 S.getASTContext()) &&
12062 !FromTy->isIncompleteType() &&
12063 !ToRefTy->getPointeeType()->isIncompleteType() &&
12064 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12065 BaseToDerivedConversion = 3;
12066 }
12067 }
12068
12069 if (BaseToDerivedConversion) {
12070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12071 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12072 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12073 << I + 1;
12074 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12075 return;
12076 }
12077
12078 if (isa<ObjCObjectPointerType>(CFromTy) &&
12079 isa<PointerType>(CToTy)) {
12080 Qualifiers FromQs = CFromTy.getQualifiers();
12081 Qualifiers ToQs = CToTy.getQualifiers();
12082 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12083 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12084 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12085 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12086 << I + 1;
12087 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12088 return;
12089 }
12090 }
12091
12092 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12093 return;
12094
12095 // Emit the generic diagnostic and, optionally, add the hints to it.
12096 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12097 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12098 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12099 << (unsigned)(Cand->Fix.Kind);
12100
12101 // Check that location of Fn is not in system header.
12102 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12103 // If we can fix the conversion, suggest the FixIts.
12104 for (const FixItHint &HI : Cand->Fix.Hints)
12105 FDiag << HI;
12106 }
12107
12108 S.Diag(Fn->getLocation(), FDiag);
12109
12110 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12111 }
12112
12113 /// Additional arity mismatch diagnosis specific to a function overload
12114 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
12115 /// over a candidate in any candidate set.
12116 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12117 unsigned NumArgs, bool IsAddressOf = false) {
12118 assert(Cand->Function && "Candidate is required to be a function.");
12119 FunctionDecl *Fn = Cand->Function;
12120 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12121 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12122
12123 // With invalid overloaded operators, it's possible that we think we
12124 // have an arity mismatch when in fact it looks like we have the
12125 // right number of arguments, because only overloaded operators have
12126 // the weird behavior of overloading member and non-member functions.
12127 // Just don't report anything.
12128 if (Fn->isInvalidDecl() &&
12129 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12130 return true;
12131
12132 if (NumArgs < MinParams) {
12133 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12134 (Cand->FailureKind == ovl_fail_bad_deduction &&
12135 Cand->DeductionFailure.getResult() ==
12136 TemplateDeductionResult::TooFewArguments));
12137 } else {
12138 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12139 (Cand->FailureKind == ovl_fail_bad_deduction &&
12140 Cand->DeductionFailure.getResult() ==
12141 TemplateDeductionResult::TooManyArguments));
12142 }
12143
12144 return false;
12145 }
12146
12147 /// General arity mismatch diagnosis over a candidate in a candidate set.
12148 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12149 unsigned NumFormalArgs,
12150 bool IsAddressOf = false) {
12151 assert(isa<FunctionDecl>(D) &&
12152 "The templated declaration should at least be a function"
12153 " when diagnosing bad template argument deduction due to too many"
12154 " or too few arguments");
12155
12156 FunctionDecl *Fn = cast<FunctionDecl>(D);
12157
12158 // TODO: treat calls to a missing default constructor as a special case
12159 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12160 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12161 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12162
12163 // at least / at most / exactly
12164 bool HasExplicitObjectParam =
12165 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12166
12167 unsigned ParamCount =
12168 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12169 unsigned mode, modeCount;
12170
12171 if (NumFormalArgs < MinParams) {
12172 if (MinParams != ParamCount || FnTy->isVariadic() ||
12173 FnTy->isTemplateVariadic())
12174 mode = 0; // "at least"
12175 else
12176 mode = 2; // "exactly"
12177 modeCount = MinParams;
12178 } else {
12179 if (MinParams != ParamCount)
12180 mode = 1; // "at most"
12181 else
12182 mode = 2; // "exactly"
12183 modeCount = ParamCount;
12184 }
12185
12186 std::string Description;
12187 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12188 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12189
12190 if (modeCount == 1 && !IsAddressOf &&
12191 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12193 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12194 << Description << mode
12195 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12196 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12197 else
12198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12200 << Description << mode << modeCount << NumFormalArgs
12201 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12202
12203 MaybeEmitInheritedConstructorNote(S, Found);
12204 }
12205
12206 /// Arity mismatch diagnosis specific to a function overload candidate.
12207 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12208 unsigned NumFormalArgs) {
12209 assert(Cand->Function && "Candidate must be a function");
12210 FunctionDecl *Fn = Cand->Function;
12211 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12212 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12213 Cand->TookAddressOfOverload);
12214 }
12215
12216 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12217 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12218 return TD;
12219 llvm_unreachable("Unsupported: Getting the described template declaration"
12220 " for bad deduction diagnosis");
12221 }
12222
12223 /// Diagnose a failed template-argument deduction.
12224 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12225 DeductionFailureInfo &DeductionFailure,
12226 unsigned NumArgs,
12227 bool TakingCandidateAddress) {
12228 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12229 NamedDecl *ParamD;
12230 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12231 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12232 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12233 switch (DeductionFailure.getResult()) {
12234 case TemplateDeductionResult::Success:
12235 llvm_unreachable(
12236 "TemplateDeductionResult::Success while diagnosing bad deduction");
12237 case TemplateDeductionResult::NonDependentConversionFailure:
12238 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12239 "while diagnosing bad deduction");
12240 case TemplateDeductionResult::Invalid:
12241 case TemplateDeductionResult::AlreadyDiagnosed:
12242 return;
12243
12244 case TemplateDeductionResult::Incomplete: {
12245 assert(ParamD && "no parameter found for incomplete deduction result");
12246 S.Diag(Templated->getLocation(),
12247 diag::note_ovl_candidate_incomplete_deduction)
12248 << ParamD->getDeclName();
12249 MaybeEmitInheritedConstructorNote(S, Found);
12250 return;
12251 }
12252
12253 case TemplateDeductionResult::IncompletePack: {
12254 assert(ParamD && "no parameter found for incomplete deduction result");
12255 S.Diag(Templated->getLocation(),
12256 diag::note_ovl_candidate_incomplete_deduction_pack)
12257 << ParamD->getDeclName()
12258 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12259 << *DeductionFailure.getFirstArg();
12260 MaybeEmitInheritedConstructorNote(S, Found);
12261 return;
12262 }
12263
12264 case TemplateDeductionResult::Underqualified: {
12265 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12266 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
12267
12268 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12269
12270 // Param will have been canonicalized, but it should just be a
12271 // qualified version of ParamD, so move the qualifiers to that.
12272 QualifierCollector Qs;
12273 Qs.strip(Param);
12274 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12275 assert(S.Context.hasSameType(Param, NonCanonParam));
12276
12277 // Arg has also been canonicalized, but there's nothing we can do
12278 // about that. It also doesn't matter as much, because it won't
12279 // have any template parameters in it (because deduction isn't
12280 // done on dependent types).
12281 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12282
12283 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12284 << ParamD->getDeclName() << Arg << NonCanonParam;
12285 MaybeEmitInheritedConstructorNote(S, Found);
12286 return;
12287 }
12288
12289 case TemplateDeductionResult::Inconsistent: {
12290 assert(ParamD && "no parameter found for inconsistent deduction result");
12291 int which = 0;
12292 if (isa<TemplateTypeParmDecl>(ParamD))
12293 which = 0;
12294 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12295 // Deduction might have failed because we deduced arguments of two
12296 // different types for a non-type template parameter.
12297 // FIXME: Use a different TDK value for this.
12298 QualType T1 =
12299 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12300 QualType T2 =
12301 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12302 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12303 S.Diag(Templated->getLocation(),
12304 diag::note_ovl_candidate_inconsistent_deduction_types)
12305 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12306 << *DeductionFailure.getSecondArg() << T2;
12307 MaybeEmitInheritedConstructorNote(S, Found);
12308 return;
12309 }
12310
12311 which = 1;
12312 } else {
12313 which = 2;
12314 }
12315
12316 // Tweak the diagnostic if the problem is that we deduced packs of
12317 // different arities. We'll print the actual packs anyway in case that
12318 // includes additional useful information.
12319 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12320 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12321 DeductionFailure.getFirstArg()->pack_size() !=
12322 DeductionFailure.getSecondArg()->pack_size()) {
12323 which = 3;
12324 }
12325
12326 S.Diag(Templated->getLocation(),
12327 diag::note_ovl_candidate_inconsistent_deduction)
12328 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12329 << *DeductionFailure.getSecondArg();
12330 MaybeEmitInheritedConstructorNote(S, Found);
12331 return;
12332 }
12333
12334 case TemplateDeductionResult::InvalidExplicitArguments:
12335 assert(ParamD && "no parameter found for invalid explicit arguments");
12336 if (ParamD->getDeclName())
12337 S.Diag(Templated->getLocation(),
12338 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12339 << ParamD->getDeclName();
12340 else {
12341 int index = 0;
12342 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12343 index = TTP->getIndex();
12344 else if (NonTypeTemplateParmDecl *NTTP
12345 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12346 index = NTTP->getIndex();
12347 else
12348 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12349 S.Diag(Templated->getLocation(),
12350 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12351 << (index + 1);
12352 }
12353 MaybeEmitInheritedConstructorNote(S, Found);
12354 return;
12355
12356 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12357 // Format the template argument list into the argument string.
12358 SmallString<128> TemplateArgString;
12359 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12360 TemplateArgString = " ";
12361 TemplateArgString += S.getTemplateArgumentBindingsText(
12362 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12363 if (TemplateArgString.size() == 1)
12364 TemplateArgString.clear();
12365 S.Diag(Templated->getLocation(),
12366 diag::note_ovl_candidate_unsatisfied_constraints)
12367 << TemplateArgString;
12368
12369 S.DiagnoseUnsatisfiedConstraint(
12370 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12371 return;
12372 }
12373 case TemplateDeductionResult::TooManyArguments:
12374 case TemplateDeductionResult::TooFewArguments:
12375 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12376 return;
12377
12378 case TemplateDeductionResult::InstantiationDepth:
12379 S.Diag(Templated->getLocation(),
12380 diag::note_ovl_candidate_instantiation_depth);
12381 MaybeEmitInheritedConstructorNote(S, Found);
12382 return;
12383
12384 case TemplateDeductionResult::SubstitutionFailure: {
12385 // Format the template argument list into the argument string.
12386 SmallString<128> TemplateArgString;
12387 if (TemplateArgumentList *Args =
12388 DeductionFailure.getTemplateArgumentList()) {
12389 TemplateArgString = " ";
12390 TemplateArgString += S.getTemplateArgumentBindingsText(
12391 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12392 if (TemplateArgString.size() == 1)
12393 TemplateArgString.clear();
12394 }
12395
12396 // If this candidate was disabled by enable_if, say so.
12397 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12398 if (PDiag && PDiag->second.getDiagID() ==
12399 diag::err_typename_nested_not_found_enable_if) {
12400 // FIXME: Use the source range of the condition, and the fully-qualified
12401 // name of the enable_if template. These are both present in PDiag.
12402 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12403 << "'enable_if'" << TemplateArgString;
12404 return;
12405 }
12406
12407 // We found a specific requirement that disabled the enable_if.
12408 if (PDiag && PDiag->second.getDiagID() ==
12409 diag::err_typename_nested_not_found_requirement) {
12410 S.Diag(Templated->getLocation(),
12411 diag::note_ovl_candidate_disabled_by_requirement)
12412 << PDiag->second.getStringArg(0) << TemplateArgString;
12413 return;
12414 }
12415
12416 // Format the SFINAE diagnostic into the argument string.
12417 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12418 // formatted message in another diagnostic.
12419 SmallString<128> SFINAEArgString;
12420 SourceRange R;
12421 if (PDiag) {
12422 SFINAEArgString = ": ";
12423 R = SourceRange(PDiag->first, PDiag->first);
12424 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12425 }
12426
12427 S.Diag(Templated->getLocation(),
12428 diag::note_ovl_candidate_substitution_failure)
12429 << TemplateArgString << SFINAEArgString << R;
12430 MaybeEmitInheritedConstructorNote(S, Found);
12431 return;
12432 }
12433
12434 case TemplateDeductionResult::DeducedMismatch:
12435 case TemplateDeductionResult::DeducedMismatchNested: {
12436 // Format the template argument list into the argument string.
12437 SmallString<128> TemplateArgString;
12438 if (TemplateArgumentList *Args =
12439 DeductionFailure.getTemplateArgumentList()) {
12440 TemplateArgString = " ";
12441 TemplateArgString += S.getTemplateArgumentBindingsText(
12442 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12443 if (TemplateArgString.size() == 1)
12444 TemplateArgString.clear();
12445 }
12446
12447 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12448 << (*DeductionFailure.getCallArgIndex() + 1)
12449 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12450 << TemplateArgString
12451 << (DeductionFailure.getResult() ==
12452 TemplateDeductionResult::DeducedMismatchNested);
12453 break;
12454 }
12455
12456 case TemplateDeductionResult::NonDeducedMismatch: {
12457 // FIXME: Provide a source location to indicate what we couldn't match.
12458 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12459 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12460 if (FirstTA.getKind() == TemplateArgument::Template &&
12461 SecondTA.getKind() == TemplateArgument::Template) {
12462 TemplateName FirstTN = FirstTA.getAsTemplate();
12463 TemplateName SecondTN = SecondTA.getAsTemplate();
12464 if (FirstTN.getKind() == TemplateName::Template &&
12465 SecondTN.getKind() == TemplateName::Template) {
12466 if (FirstTN.getAsTemplateDecl()->getName() ==
12467 SecondTN.getAsTemplateDecl()->getName()) {
12468 // FIXME: This fixes a bad diagnostic where both templates are named
12469 // the same. This particular case is a bit difficult since:
12470 // 1) It is passed as a string to the diagnostic printer.
12471 // 2) The diagnostic printer only attempts to find a better
12472 // name for types, not decls.
12473 // Ideally, this should folded into the diagnostic printer.
12474 S.Diag(Templated->getLocation(),
12475 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12476 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12477 return;
12478 }
12479 }
12480 }
12481
12482 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12483 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
12484 return;
12485
12486 // FIXME: For generic lambda parameters, check if the function is a lambda
12487 // call operator, and if so, emit a prettier and more informative
12488 // diagnostic that mentions 'auto' and lambda in addition to
12489 // (or instead of?) the canonical template type parameters.
12490 S.Diag(Templated->getLocation(),
12491 diag::note_ovl_candidate_non_deduced_mismatch)
12492 << FirstTA << SecondTA;
12493 return;
12494 }
12495 // TODO: diagnose these individually, then kill off
12496 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12497 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12498 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12499 MaybeEmitInheritedConstructorNote(S, Found);
12500 return;
12501 case TemplateDeductionResult::CUDATargetMismatch:
12502 S.Diag(Templated->getLocation(),
12503 diag::note_cuda_ovl_candidate_target_mismatch);
12504 return;
12505 }
12506 }
12507
12508 /// Diagnose a failed template-argument deduction, for function calls.
12509 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12510 unsigned NumArgs,
12511 bool TakingCandidateAddress) {
12512 assert(Cand->Function && "Candidate must be a function");
12513 FunctionDecl *Fn = Cand->Function;
12514 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12515 if (TDK == TemplateDeductionResult::TooFewArguments ||
12516 TDK == TemplateDeductionResult::TooManyArguments) {
12517 if (CheckArityMismatch(S, Cand, NumArgs))
12518 return;
12519 }
12520 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12521 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12522 }
12523
12524 /// CUDA: diagnose an invalid call across targets.
12525 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12526 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12527 assert(Cand->Function && "Candidate must be a Function.");
12528 FunctionDecl *Callee = Cand->Function;
12529
12530 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12531 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12532
12533 std::string FnDesc;
12534 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12535 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12536 Cand->getRewriteKind(), FnDesc);
12537
12538 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12539 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12540 << FnDesc /* Ignored */
12541 << CalleeTarget << CallerTarget;
12542
12543 // This could be an implicit constructor for which we could not infer the
12544 // target due to a collsion. Diagnose that case.
12545 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12546 if (Meth != nullptr && Meth->isImplicit()) {
12547 CXXRecordDecl *ParentClass = Meth->getParent();
12548 CXXSpecialMemberKind CSM;
12549
12550 switch (FnKindPair.first) {
12551 default:
12552 return;
12553 case oc_implicit_default_constructor:
12554 CSM = CXXSpecialMemberKind::DefaultConstructor;
12555 break;
12556 case oc_implicit_copy_constructor:
12557 CSM = CXXSpecialMemberKind::CopyConstructor;
12558 break;
12559 case oc_implicit_move_constructor:
12560 CSM = CXXSpecialMemberKind::MoveConstructor;
12561 break;
12562 case oc_implicit_copy_assignment:
12563 CSM = CXXSpecialMemberKind::CopyAssignment;
12564 break;
12565 case oc_implicit_move_assignment:
12566 CSM = CXXSpecialMemberKind::MoveAssignment;
12567 break;
12568 };
12569
12570 bool ConstRHS = false;
12571 if (Meth->getNumParams()) {
12572 if (const ReferenceType *RT =
12573 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12574 ConstRHS = RT->getPointeeType().isConstQualified();
12575 }
12576 }
12577
12578 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12579 /* ConstRHS */ ConstRHS,
12580 /* Diagnose */ true);
12581 }
12582 }
12583
12584 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12585 assert(Cand->Function && "Candidate must be a function");
12586 FunctionDecl *Callee = Cand->Function;
12587 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12588
12589 S.Diag(Callee->getLocation(),
12590 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12591 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12592 }
12593
12594 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12595 assert(Cand->Function && "Candidate must be a function");
12596 FunctionDecl *Fn = Cand->Function;
12597 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Fn);
12598 assert(ES.isExplicit() && "not an explicit candidate");
12599
12600 unsigned Kind;
12601 switch (Fn->getDeclKind()) {
12602 case Decl::Kind::CXXConstructor:
12603 Kind = 0;
12604 break;
12605 case Decl::Kind::CXXConversion:
12606 Kind = 1;
12607 break;
12608 case Decl::Kind::CXXDeductionGuide:
12609 Kind = Fn->isImplicit() ? 0 : 2;
12610 break;
12611 default:
12612 llvm_unreachable("invalid Decl");
12613 }
12614
12615 // Note the location of the first (in-class) declaration; a redeclaration
12616 // (particularly an out-of-class definition) will typically lack the
12617 // 'explicit' specifier.
12618 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12619 FunctionDecl *First = Fn->getFirstDecl();
12620 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12621 First = Pattern->getFirstDecl();
12622
12623 S.Diag(First->getLocation(),
12624 diag::note_ovl_candidate_explicit)
12625 << Kind << (ES.getExpr() ? 1 : 0)
12626 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12627 }
12628
12629 static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12630 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12631 if (!DG)
12632 return;
12633 TemplateDecl *OriginTemplate =
12634 DG->getDeclName().getCXXDeductionGuideTemplate();
12635 // We want to always print synthesized deduction guides for type aliases.
12636 // They would retain the explicit bit of the corresponding constructor.
12637 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12638 return;
12639 std::string FunctionProto;
12640 llvm::raw_string_ostream OS(FunctionProto);
12641 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12642 if (!Template) {
12643 // This also could be an instantiation. Find out the primary template.
12644 FunctionDecl *Pattern =
12645 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12646 if (!Pattern) {
12647 // The implicit deduction guide is built on an explicit non-template
12648 // deduction guide. Currently, this might be the case only for type
12649 // aliases.
12650 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12651 // gets merged.
12652 assert(OriginTemplate->isTypeAlias() &&
12653 "Non-template implicit deduction guides are only possible for "
12654 "type aliases");
12655 DG->print(OS);
12656 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12657 << FunctionProto;
12658 return;
12659 }
12660 Template = Pattern->getDescribedFunctionTemplate();
12661 assert(Template && "Cannot find the associated function template of "
12662 "CXXDeductionGuideDecl?");
12663 }
12664 Template->print(OS);
12665 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12666 << FunctionProto;
12667 }
12668
12669 /// Generates a 'note' diagnostic for an overload candidate. We've
12670 /// already generated a primary error at the call site.
12671 ///
12672 /// It really does need to be a single diagnostic with its caret
12673 /// pointed at the candidate declaration. Yes, this creates some
12674 /// major challenges of technical writing. Yes, this makes pointing
12675 /// out problems with specific arguments quite awkward. It's still
12676 /// better than generating twenty screens of text for every failed
12677 /// overload.
12678 ///
12679 /// It would be great to be able to express per-candidate problems
12680 /// more richly for those diagnostic clients that cared, but we'd
12681 /// still have to be just as careful with the default diagnostics.
12682 /// \param CtorDestAS Addr space of object being constructed (for ctor
12683 /// candidates only).
12684 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12685 unsigned NumArgs,
12686 bool TakingCandidateAddress,
12687 LangAS CtorDestAS = LangAS::Default) {
12688 assert(Cand->Function && "Candidate must be a function");
12689 FunctionDecl *Fn = Cand->Function;
12690 if (shouldSkipNotingLambdaConversionDecl(Fn))
12691 return;
12692
12693 // There is no physical candidate declaration to point to for OpenCL builtins.
12694 // Except for failed conversions, the notes are identical for each candidate,
12695 // so do not generate such notes.
12696 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12697 Cand->FailureKind != ovl_fail_bad_conversion)
12698 return;
12699
12700 // Skip implicit member functions when trying to resolve
12701 // the address of a an overload set for a function pointer.
12702 if (Cand->TookAddressOfOverload &&
12703 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12704 return;
12705
12706 // Note deleted candidates, but only if they're viable.
12707 if (Cand->Viable) {
12708 if (Fn->isDeleted()) {
12709 std::string FnDesc;
12710 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12711 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12712 Cand->getRewriteKind(), FnDesc);
12713
12714 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12715 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12716 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12717 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12718 return;
12719 }
12720
12721 // We don't really have anything else to say about viable candidates.
12722 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12723 return;
12724 }
12725
12726 // If this is a synthesized deduction guide we're deducing against, add a note
12727 // for it. These deduction guides are not explicitly spelled in the source
12728 // code, so simply printing a deduction failure note mentioning synthesized
12729 // template parameters or pointing to the header of the surrounding RecordDecl
12730 // would be confusing.
12731 //
12732 // We prefer adding such notes at the end of the deduction failure because
12733 // duplicate code snippets appearing in the diagnostic would likely become
12734 // noisy.
12735 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12736
12737 switch (Cand->FailureKind) {
12738 case ovl_fail_too_many_arguments:
12739 case ovl_fail_too_few_arguments:
12740 return DiagnoseArityMismatch(S, Cand, NumArgs);
12741
12742 case ovl_fail_bad_deduction:
12743 return DiagnoseBadDeduction(S, Cand, NumArgs,
12744 TakingCandidateAddress);
12745
12746 case ovl_fail_illegal_constructor: {
12747 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12748 << (Fn->getPrimaryTemplate() ? 1 : 0);
12749 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12750 return;
12751 }
12752
12753 case ovl_fail_object_addrspace_mismatch: {
12754 Qualifiers QualsForPrinting;
12755 QualsForPrinting.setAddressSpace(CtorDestAS);
12756 S.Diag(Fn->getLocation(),
12757 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12758 << QualsForPrinting;
12759 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12760 return;
12761 }
12762
12763 case ovl_fail_trivial_conversion:
12764 case ovl_fail_bad_final_conversion:
12765 case ovl_fail_final_conversion_not_exact:
12766 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12767
12768 case ovl_fail_bad_conversion: {
12769 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12770 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12771 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12772 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12773
12774 // FIXME: this currently happens when we're called from SemaInit
12775 // when user-conversion overload fails. Figure out how to handle
12776 // those conditions and diagnose them well.
12777 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12778 }
12779
12780 case ovl_fail_bad_target:
12781 return DiagnoseBadTarget(S, Cand);
12782
12783 case ovl_fail_enable_if:
12784 return DiagnoseFailedEnableIfAttr(S, Cand);
12785
12786 case ovl_fail_explicit:
12787 return DiagnoseFailedExplicitSpec(S, Cand);
12788
12789 case ovl_fail_inhctor_slice:
12790 // It's generally not interesting to note copy/move constructors here.
12791 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12792 return;
12793 S.Diag(Fn->getLocation(),
12794 diag::note_ovl_candidate_inherited_constructor_slice)
12795 << (Fn->getPrimaryTemplate() ? 1 : 0)
12796 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12797 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12798 return;
12799
12800 case ovl_fail_addr_not_available: {
12801 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12802 (void)Available;
12803 assert(!Available);
12804 break;
12805 }
12806 case ovl_non_default_multiversion_function:
12807 // Do nothing, these should simply be ignored.
12808 break;
12809
12810 case ovl_fail_constraints_not_satisfied: {
12811 std::string FnDesc;
12812 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12813 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12814 Cand->getRewriteKind(), FnDesc);
12815
12816 S.Diag(Fn->getLocation(),
12817 diag::note_ovl_candidate_constraints_not_satisfied)
12818 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12819 << FnDesc /* Ignored */;
12820 ConstraintSatisfaction Satisfaction;
12821 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12822 /*ForOverloadResolution=*/true))
12823 break;
12824 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12825 }
12826 }
12827 }
12828
12829 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12830 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
12831 return;
12832
12833 // Desugar the type of the surrogate down to a function type,
12834 // retaining as many typedefs as possible while still showing
12835 // the function type (and, therefore, its parameter types).
12836 QualType FnType = Cand->Surrogate->getConversionType();
12837 bool isLValueReference = false;
12838 bool isRValueReference = false;
12839 bool isPointer = false;
12840 if (const LValueReferenceType *FnTypeRef =
12841 FnType->getAs<LValueReferenceType>()) {
12842 FnType = FnTypeRef->getPointeeType();
12843 isLValueReference = true;
12844 } else if (const RValueReferenceType *FnTypeRef =
12845 FnType->getAs<RValueReferenceType>()) {
12846 FnType = FnTypeRef->getPointeeType();
12847 isRValueReference = true;
12848 }
12849 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12850 FnType = FnTypePtr->getPointeeType();
12851 isPointer = true;
12852 }
12853 // Desugar down to a function type.
12854 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12855 // Reconstruct the pointer/reference as appropriate.
12856 if (isPointer) FnType = S.Context.getPointerType(FnType);
12857 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12858 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12859
12860 if (!Cand->Viable &&
12861 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12862 S.Diag(Cand->Surrogate->getLocation(),
12863 diag::note_ovl_surrogate_constraints_not_satisfied)
12864 << Cand->Surrogate;
12865 ConstraintSatisfaction Satisfaction;
12866 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12867 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12868 } else {
12869 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12870 << FnType;
12871 }
12872 }
12873
12874 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12875 SourceLocation OpLoc,
12876 OverloadCandidate *Cand) {
12877 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12878 std::string TypeStr("operator");
12879 TypeStr += Opc;
12880 TypeStr += "(";
12881 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12882 if (Cand->Conversions.size() == 1) {
12883 TypeStr += ")";
12884 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12885 } else {
12886 TypeStr += ", ";
12887 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12888 TypeStr += ")";
12889 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12890 }
12891 }
12892
12893 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12894 OverloadCandidate *Cand) {
12895 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12896 if (ICS.isBad()) break; // all meaningless after first invalid
12897 if (!ICS.isAmbiguous()) continue;
12898
12899 ICS.DiagnoseAmbiguousConversion(
12900 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12901 }
12902 }
12903
12904 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12905 if (Cand->Function)
12906 return Cand->Function->getLocation();
12907 if (Cand->IsSurrogate)
12908 return Cand->Surrogate->getLocation();
12909 return SourceLocation();
12910 }
12911
12912 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12913 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12914 case TemplateDeductionResult::Success:
12915 case TemplateDeductionResult::NonDependentConversionFailure:
12916 case TemplateDeductionResult::AlreadyDiagnosed:
12917 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12918
12919 case TemplateDeductionResult::Invalid:
12920 case TemplateDeductionResult::Incomplete:
12921 case TemplateDeductionResult::IncompletePack:
12922 return 1;
12923
12924 case TemplateDeductionResult::Underqualified:
12925 case TemplateDeductionResult::Inconsistent:
12926 return 2;
12927
12928 case TemplateDeductionResult::SubstitutionFailure:
12929 case TemplateDeductionResult::DeducedMismatch:
12930 case TemplateDeductionResult::ConstraintsNotSatisfied:
12931 case TemplateDeductionResult::DeducedMismatchNested:
12932 case TemplateDeductionResult::NonDeducedMismatch:
12933 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12934 case TemplateDeductionResult::CUDATargetMismatch:
12935 return 3;
12936
12937 case TemplateDeductionResult::InstantiationDepth:
12938 return 4;
12939
12940 case TemplateDeductionResult::InvalidExplicitArguments:
12941 return 5;
12942
12943 case TemplateDeductionResult::TooManyArguments:
12944 case TemplateDeductionResult::TooFewArguments:
12945 return 6;
12946 }
12947 llvm_unreachable("Unhandled deduction result");
12948 }
12949
12950 namespace {
12951
12952 struct CompareOverloadCandidatesForDisplay {
12953 Sema &S;
12954 SourceLocation Loc;
12955 size_t NumArgs;
12956 OverloadCandidateSet::CandidateSetKind CSK;
12957
12958 CompareOverloadCandidatesForDisplay(
12959 Sema &S, SourceLocation Loc, size_t NArgs,
12960 OverloadCandidateSet::CandidateSetKind CSK)
12961 : S(S), NumArgs(NArgs), CSK(CSK) {}
12962
12963 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12964 // If there are too many or too few arguments, that's the high-order bit we
12965 // want to sort by, even if the immediate failure kind was something else.
12966 if (C->FailureKind == ovl_fail_too_many_arguments ||
12967 C->FailureKind == ovl_fail_too_few_arguments)
12968 return static_cast<OverloadFailureKind>(C->FailureKind);
12969
12970 if (C->Function) {
12971 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12972 return ovl_fail_too_many_arguments;
12973 if (NumArgs < C->Function->getMinRequiredArguments())
12974 return ovl_fail_too_few_arguments;
12975 }
12976
12977 return static_cast<OverloadFailureKind>(C->FailureKind);
12978 }
12979
12980 bool operator()(const OverloadCandidate *L,
12981 const OverloadCandidate *R) {
12982 // Fast-path this check.
12983 if (L == R) return false;
12984
12985 // Order first by viability.
12986 if (L->Viable) {
12987 if (!R->Viable) return true;
12988
12989 if (int Ord = CompareConversions(*L, *R))
12990 return Ord < 0;
12991 // Use other tie breakers.
12992 } else if (R->Viable)
12993 return false;
12994
12995 assert(L->Viable == R->Viable);
12996
12997 // Criteria by which we can sort non-viable candidates:
12998 if (!L->Viable) {
12999 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13000 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13001
13002 // 1. Arity mismatches come after other candidates.
13003 if (LFailureKind == ovl_fail_too_many_arguments ||
13004 LFailureKind == ovl_fail_too_few_arguments) {
13005 if (RFailureKind == ovl_fail_too_many_arguments ||
13006 RFailureKind == ovl_fail_too_few_arguments) {
13007 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13008 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13009 if (LDist == RDist) {
13010 if (LFailureKind == RFailureKind)
13011 // Sort non-surrogates before surrogates.
13012 return !L->IsSurrogate && R->IsSurrogate;
13013 // Sort candidates requiring fewer parameters than there were
13014 // arguments given after candidates requiring more parameters
13015 // than there were arguments given.
13016 return LFailureKind == ovl_fail_too_many_arguments;
13017 }
13018 return LDist < RDist;
13019 }
13020 return false;
13021 }
13022 if (RFailureKind == ovl_fail_too_many_arguments ||
13023 RFailureKind == ovl_fail_too_few_arguments)
13024 return true;
13025
13026 // 2. Bad conversions come first and are ordered by the number
13027 // of bad conversions and quality of good conversions.
13028 if (LFailureKind == ovl_fail_bad_conversion) {
13029 if (RFailureKind != ovl_fail_bad_conversion)
13030 return true;
13031
13032 // The conversion that can be fixed with a smaller number of changes,
13033 // comes first.
13034 unsigned numLFixes = L->Fix.NumConversionsFixed;
13035 unsigned numRFixes = R->Fix.NumConversionsFixed;
13036 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13037 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13038 if (numLFixes != numRFixes) {
13039 return numLFixes < numRFixes;
13040 }
13041
13042 // If there's any ordering between the defined conversions...
13043 if (int Ord = CompareConversions(*L, *R))
13044 return Ord < 0;
13045 } else if (RFailureKind == ovl_fail_bad_conversion)
13046 return false;
13047
13048 if (LFailureKind == ovl_fail_bad_deduction) {
13049 if (RFailureKind != ovl_fail_bad_deduction)
13050 return true;
13051
13052 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13053 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13054 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13055 if (LRank != RRank)
13056 return LRank < RRank;
13057 }
13058 } else if (RFailureKind == ovl_fail_bad_deduction)
13059 return false;
13060
13061 // TODO: others?
13062 }
13063
13064 // Sort everything else by location.
13065 SourceLocation LLoc = GetLocationForCandidate(L);
13066 SourceLocation RLoc = GetLocationForCandidate(R);
13067
13068 // Put candidates without locations (e.g. builtins) at the end.
13069 if (LLoc.isValid() && RLoc.isValid())
13070 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13071 if (LLoc.isValid() && !RLoc.isValid())
13072 return true;
13073 if (RLoc.isValid() && !LLoc.isValid())
13074 return false;
13075 assert(!LLoc.isValid() && !RLoc.isValid());
13076 // For builtins and other functions without locations, fallback to the order
13077 // in which they were added into the candidate set.
13078 return L < R;
13079 }
13080
13081 private:
13082 struct ConversionSignals {
13083 unsigned KindRank = 0;
13084 ImplicitConversionRank Rank = ICR_Exact_Match;
13085
13086 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13087 ConversionSignals Sig;
13088 Sig.KindRank = Seq.getKindRank();
13089 if (Seq.isStandard())
13090 Sig.Rank = Seq.Standard.getRank();
13091 else if (Seq.isUserDefined())
13092 Sig.Rank = Seq.UserDefined.After.getRank();
13093 // We intend StaticObjectArgumentConversion to compare the same as
13094 // StandardConversion with ICR_ExactMatch rank.
13095 return Sig;
13096 }
13097
13098 static ConversionSignals ForObjectArgument() {
13099 // We intend StaticObjectArgumentConversion to compare the same as
13100 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13101 return {};
13102 }
13103 };
13104
13105 // Returns -1 if conversions in L are considered better.
13106 // 0 if they are considered indistinguishable.
13107 // 1 if conversions in R are better.
13108 int CompareConversions(const OverloadCandidate &L,
13109 const OverloadCandidate &R) {
13110 // We cannot use `isBetterOverloadCandidate` because it is defined
13111 // according to the C++ standard and provides a partial order, but we need
13112 // a total order as this function is used in sort.
13113 assert(L.Conversions.size() == R.Conversions.size());
13114 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13115 auto LS = L.IgnoreObjectArgument && I == 0
13116 ? ConversionSignals::ForObjectArgument()
13117 : ConversionSignals::ForSequence(L.Conversions[I]);
13118 auto RS = R.IgnoreObjectArgument
13119 ? ConversionSignals::ForObjectArgument()
13120 : ConversionSignals::ForSequence(R.Conversions[I]);
13121 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13122 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13123 ? -1
13124 : 1;
13125 }
13126 // FIXME: find a way to compare templates for being more or less
13127 // specialized that provides a strict weak ordering.
13128 return 0;
13129 }
13130 };
13131 }
13132
13133 /// CompleteNonViableCandidate - Normally, overload resolution only
13134 /// computes up to the first bad conversion. Produces the FixIt set if
13135 /// possible.
13136 static void
13137 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13138 ArrayRef<Expr *> Args,
13139 OverloadCandidateSet::CandidateSetKind CSK) {
13140 assert(!Cand->Viable);
13141
13142 // Don't do anything on failures other than bad conversion.
13143 if (Cand->FailureKind != ovl_fail_bad_conversion)
13144 return;
13145
13146 // We only want the FixIts if all the arguments can be corrected.
13147 bool Unfixable = false;
13148 // Use a implicit copy initialization to check conversion fixes.
13149 Cand->Fix.setConversionChecker(TryCopyInitialization);
13150
13151 // Attempt to fix the bad conversion.
13152 unsigned ConvCount = Cand->Conversions.size();
13153 for (unsigned ConvIdx =
13154 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13155 : 0);
13156 /**/; ++ConvIdx) {
13157 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13158 if (Cand->Conversions[ConvIdx].isInitialized() &&
13159 Cand->Conversions[ConvIdx].isBad()) {
13160 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13161 break;
13162 }
13163 }
13164
13165 // FIXME: this should probably be preserved from the overload
13166 // operation somehow.
13167 bool SuppressUserConversions = false;
13168
13169 unsigned ConvIdx = 0;
13170 unsigned ArgIdx = 0;
13171 ArrayRef<QualType> ParamTypes;
13172 bool Reversed = Cand->isReversed();
13173
13174 if (Cand->IsSurrogate) {
13175 QualType ConvType
13176 = Cand->Surrogate->getConversionType().getNonReferenceType();
13177 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13178 ConvType = ConvPtrType->getPointeeType();
13179 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13180 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13181 ConvIdx = 1;
13182 } else if (Cand->Function) {
13183 ParamTypes =
13184 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13185 if (isa<CXXMethodDecl>(Cand->Function) &&
13186 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed &&
13187 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13188 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13189 ConvIdx = 1;
13190 if (CSK == OverloadCandidateSet::CSK_Operator &&
13191 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13192 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13193 OO_Subscript)
13194 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13195 ArgIdx = 1;
13196 }
13197 } else {
13198 // Builtin operator.
13199 assert(ConvCount <= 3);
13200 ParamTypes = Cand->BuiltinParamTypes;
13201 }
13202
13203 // Fill in the rest of the conversions.
13204 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13205 ConvIdx != ConvCount && ArgIdx < Args.size();
13206 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13207 if (Cand->Conversions[ConvIdx].isInitialized()) {
13208 // We've already checked this conversion.
13209 } else if (ParamIdx < ParamTypes.size()) {
13210 if (ParamTypes[ParamIdx]->isDependentType())
13211 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13212 Args[ArgIdx]->getType());
13213 else {
13214 Cand->Conversions[ConvIdx] =
13215 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13216 SuppressUserConversions,
13217 /*InOverloadResolution=*/true,
13218 /*AllowObjCWritebackConversion=*/
13219 S.getLangOpts().ObjCAutoRefCount);
13220 // Store the FixIt in the candidate if it exists.
13221 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13222 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13223 }
13224 } else
13225 Cand->Conversions[ConvIdx].setEllipsis();
13226 }
13227 }
13228
13229 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13230 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13231 SourceLocation OpLoc,
13232 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13233
13234 InjectNonDeducedTemplateCandidates(S);
13235
13236 // Sort the candidates by viability and position. Sorting directly would
13237 // be prohibitive, so we make a set of pointers and sort those.
13238 SmallVector<OverloadCandidate*, 32> Cands;
13239 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13240 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13241 Cand != LastCand; ++Cand) {
13242 if (!Filter(*Cand))
13243 continue;
13244 switch (OCD) {
13245 case OCD_AllCandidates:
13246 if (!Cand->Viable) {
13247 if (!Cand->Function && !Cand->IsSurrogate) {
13248 // This a non-viable builtin candidate. We do not, in general,
13249 // want to list every possible builtin candidate.
13250 continue;
13251 }
13252 CompleteNonViableCandidate(S, Cand, Args, Kind);
13253 }
13254 break;
13255
13256 case OCD_ViableCandidates:
13257 if (!Cand->Viable)
13258 continue;
13259 break;
13260
13261 case OCD_AmbiguousCandidates:
13262 if (!Cand->Best)
13263 continue;
13264 break;
13265 }
13266
13267 Cands.push_back(Cand);
13268 }
13269
13270 llvm::stable_sort(
13271 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13272
13273 return Cands;
13274 }
13275
13276 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13277 SourceLocation OpLoc) {
13278 bool DeferHint = false;
13279 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13280 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13281 // host device candidates.
13282 auto WrongSidedCands =
13283 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13284 return (Cand.Viable == false &&
13285 Cand.FailureKind == ovl_fail_bad_target) ||
13286 (Cand.Function &&
13287 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13288 Cand.Function->template hasAttr<CUDADeviceAttr>());
13289 });
13290 DeferHint = !WrongSidedCands.empty();
13291 }
13292 return DeferHint;
13293 }
13294
13295 /// When overload resolution fails, prints diagnostic messages containing the
13296 /// candidates in the candidate set.
13297 void OverloadCandidateSet::NoteCandidates(
13298 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13299 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13300 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13301
13302 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13303
13304 {
13305 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13306 S.Diag(PD.first, PD.second);
13307 }
13308
13309 // In WebAssembly we don't want to emit further diagnostics if a table is
13310 // passed as an argument to a function.
13311 bool NoteCands = true;
13312 for (const Expr *Arg : Args) {
13313 if (Arg->getType()->isWebAssemblyTableType())
13314 NoteCands = false;
13315 }
13316
13317 if (NoteCands)
13318 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13319
13320 if (OCD == OCD_AmbiguousCandidates)
13321 MaybeDiagnoseAmbiguousConstraints(S,
13322 {Candidates.begin(), Candidates.end()});
13323 }
13324
13325 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13326 ArrayRef<OverloadCandidate *> Cands,
13327 StringRef Opc, SourceLocation OpLoc) {
13328 bool ReportedAmbiguousConversions = false;
13329
13330 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13331 unsigned CandsShown = 0;
13332 auto I = Cands.begin(), E = Cands.end();
13333 for (; I != E; ++I) {
13334 OverloadCandidate *Cand = *I;
13335
13336 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13337 ShowOverloads == Ovl_Best) {
13338 break;
13339 }
13340 ++CandsShown;
13341
13342 if (Cand->Function)
13343 NoteFunctionCandidate(S, Cand, Args.size(),
13344 Kind == CSK_AddressOfOverloadSet, DestAS);
13345 else if (Cand->IsSurrogate)
13346 NoteSurrogateCandidate(S, Cand);
13347 else {
13348 assert(Cand->Viable &&
13349 "Non-viable built-in candidates are not added to Cands.");
13350 // Generally we only see ambiguities including viable builtin
13351 // operators if overload resolution got screwed up by an
13352 // ambiguous user-defined conversion.
13353 //
13354 // FIXME: It's quite possible for different conversions to see
13355 // different ambiguities, though.
13356 if (!ReportedAmbiguousConversions) {
13357 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13358 ReportedAmbiguousConversions = true;
13359 }
13360
13361 // If this is a viable builtin, print it.
13362 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13363 }
13364 }
13365
13366 // Inform S.Diags that we've shown an overload set with N elements. This may
13367 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13368 S.Diags.overloadCandidatesShown(CandsShown);
13369
13370 if (I != E) {
13371 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13372 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13373 }
13374 }
13375
13376 static SourceLocation
13377 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13378 return Cand->Specialization ? Cand->Specialization->getLocation()
13379 : SourceLocation();
13380 }
13381
13382 namespace {
13383 struct CompareTemplateSpecCandidatesForDisplay {
13384 Sema &S;
13385 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13386
13387 bool operator()(const TemplateSpecCandidate *L,
13388 const TemplateSpecCandidate *R) {
13389 // Fast-path this check.
13390 if (L == R)
13391 return false;
13392
13393 // Assuming that both candidates are not matches...
13394
13395 // Sort by the ranking of deduction failures.
13396 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13397 return RankDeductionFailure(L->DeductionFailure) <
13398 RankDeductionFailure(R->DeductionFailure);
13399
13400 // Sort everything else by location.
13401 SourceLocation LLoc = GetLocationForCandidate(L);
13402 SourceLocation RLoc = GetLocationForCandidate(R);
13403
13404 // Put candidates without locations (e.g. builtins) at the end.
13405 if (LLoc.isInvalid())
13406 return false;
13407 if (RLoc.isInvalid())
13408 return true;
13409
13410 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13411 }
13412 };
13413 }
13414
13415 /// Diagnose a template argument deduction failure.
13416 /// We are treating these failures as overload failures due to bad
13417 /// deductions.
13418 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13419 bool ForTakingAddress) {
13420 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
13421 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13422 }
13423
13424 void TemplateSpecCandidateSet::destroyCandidates() {
13425 for (iterator i = begin(), e = end(); i != e; ++i) {
13426 i->DeductionFailure.Destroy();
13427 }
13428 }
13429
13430 void TemplateSpecCandidateSet::clear() {
13431 destroyCandidates();
13432 Candidates.clear();
13433 }
13434
13435 /// NoteCandidates - When no template specialization match is found, prints
13436 /// diagnostic messages containing the non-matching specializations that form
13437 /// the candidate set.
13438 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13439 /// OCD == OCD_AllCandidates and Cand->Viable == false.
13440 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13441 // Sort the candidates by position (assuming no candidate is a match).
13442 // Sorting directly would be prohibitive, so we make a set of pointers
13443 // and sort those.
13444 SmallVector<TemplateSpecCandidate *, 32> Cands;
13445 Cands.reserve(size());
13446 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13447 if (Cand->Specialization)
13448 Cands.push_back(Cand);
13449 // Otherwise, this is a non-matching builtin candidate. We do not,
13450 // in general, want to list every possible builtin candidate.
13451 }
13452
13453 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13454
13455 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13456 // for generalization purposes (?).
13457 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13458
13459 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13460 unsigned CandsShown = 0;
13461 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13462 TemplateSpecCandidate *Cand = *I;
13463
13464 // Set an arbitrary limit on the number of candidates we'll spam
13465 // the user with. FIXME: This limit should depend on details of the
13466 // candidate list.
13467 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13468 break;
13469 ++CandsShown;
13470
13471 assert(Cand->Specialization &&
13472 "Non-matching built-in candidates are not added to Cands.");
13473 Cand->NoteDeductionFailure(S, ForTakingAddress);
13474 }
13475
13476 if (I != E)
13477 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13478 }
13479
13480 // [PossiblyAFunctionType] --> [Return]
13481 // NonFunctionType --> NonFunctionType
13482 // R (A) --> R(A)
13483 // R (*)(A) --> R (A)
13484 // R (&)(A) --> R (A)
13485 // R (S::*)(A) --> R (A)
13486 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13487 QualType Ret = PossiblyAFunctionType;
13488 if (const PointerType *ToTypePtr =
13489 PossiblyAFunctionType->getAs<PointerType>())
13490 Ret = ToTypePtr->getPointeeType();
13491 else if (const ReferenceType *ToTypeRef =
13492 PossiblyAFunctionType->getAs<ReferenceType>())
13493 Ret = ToTypeRef->getPointeeType();
13494 else if (const MemberPointerType *MemTypePtr =
13495 PossiblyAFunctionType->getAs<MemberPointerType>())
13496 Ret = MemTypePtr->getPointeeType();
13497 Ret =
13498 Context.getCanonicalType(Ret).getUnqualifiedType();
13499 return Ret;
13500 }
13501
13502 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13503 bool Complain = true) {
13504 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13505 S.DeduceReturnType(FD, Loc, Complain))
13506 return true;
13507
13508 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13509 if (S.getLangOpts().CPlusPlus17 &&
13510 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13511 !S.ResolveExceptionSpec(Loc, FPT))
13512 return true;
13513
13514 return false;
13515 }
13516
13517 namespace {
13518 // A helper class to help with address of function resolution
13519 // - allows us to avoid passing around all those ugly parameters
13520 class AddressOfFunctionResolver {
13521 Sema& S;
13522 Expr* SourceExpr;
13523 const QualType& TargetType;
13524 QualType TargetFunctionType; // Extracted function type from target type
13525
13526 bool Complain;
13527 //DeclAccessPair& ResultFunctionAccessPair;
13528 ASTContext& Context;
13529
13530 bool TargetTypeIsNonStaticMemberFunction;
13531 bool FoundNonTemplateFunction;
13532 bool StaticMemberFunctionFromBoundPointer;
13533 bool HasComplained;
13534
13535 OverloadExpr::FindResult OvlExprInfo;
13536 OverloadExpr *OvlExpr;
13537 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13538 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13539 TemplateSpecCandidateSet FailedCandidates;
13540
13541 public:
13542 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13543 const QualType &TargetType, bool Complain)
13544 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13545 Complain(Complain), Context(S.getASTContext()),
13546 TargetTypeIsNonStaticMemberFunction(
13547 !!TargetType->getAs<MemberPointerType>()),
13548 FoundNonTemplateFunction(false),
13549 StaticMemberFunctionFromBoundPointer(false),
13550 HasComplained(false),
13551 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13552 OvlExpr(OvlExprInfo.Expression),
13553 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13554 ExtractUnqualifiedFunctionTypeFromTargetType();
13555
13556 if (TargetFunctionType->isFunctionType()) {
13557 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13558 if (!UME->isImplicitAccess() &&
13559 !S.ResolveSingleFunctionTemplateSpecialization(UME))
13560 StaticMemberFunctionFromBoundPointer = true;
13561 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13562 DeclAccessPair dap;
13563 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13564 OvlExpr, false, &dap)) {
13565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13566 if (!Method->isStatic()) {
13567 // If the target type is a non-function type and the function found
13568 // is a non-static member function, pretend as if that was the
13569 // target, it's the only possible type to end up with.
13570 TargetTypeIsNonStaticMemberFunction = true;
13571
13572 // And skip adding the function if its not in the proper form.
13573 // We'll diagnose this due to an empty set of functions.
13574 if (!OvlExprInfo.HasFormOfMemberPointer)
13575 return;
13576 }
13577
13578 Matches.push_back(std::make_pair(dap, Fn));
13579 }
13580 return;
13581 }
13582
13583 if (OvlExpr->hasExplicitTemplateArgs())
13584 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13585
13586 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13587 // C++ [over.over]p4:
13588 // If more than one function is selected, [...]
13589 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13590 if (FoundNonTemplateFunction) {
13591 EliminateAllTemplateMatches();
13592 EliminateLessPartialOrderingConstrainedMatches();
13593 } else
13594 EliminateAllExceptMostSpecializedTemplate();
13595 }
13596 }
13597
13598 if (S.getLangOpts().CUDA && Matches.size() > 1)
13599 EliminateSuboptimalCudaMatches();
13600 }
13601
13602 bool hasComplained() const { return HasComplained; }
13603
13604 private:
13605 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13606 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13607 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13608 }
13609
13610 /// \return true if A is considered a better overload candidate for the
13611 /// desired type than B.
13612 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13613 // If A doesn't have exactly the correct type, we don't want to classify it
13614 // as "better" than anything else. This way, the user is required to
13615 // disambiguate for us if there are multiple candidates and no exact match.
13616 return candidateHasExactlyCorrectType(A) &&
13617 (!candidateHasExactlyCorrectType(B) ||
13618 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13619 }
13620
13621 /// \return true if we were able to eliminate all but one overload candidate,
13622 /// false otherwise.
13623 bool eliminiateSuboptimalOverloadCandidates() {
13624 // Same algorithm as overload resolution -- one pass to pick the "best",
13625 // another pass to be sure that nothing is better than the best.
13626 auto Best = Matches.begin();
13627 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13628 if (isBetterCandidate(I->second, Best->second))
13629 Best = I;
13630
13631 const FunctionDecl *BestFn = Best->second;
13632 auto IsBestOrInferiorToBest = [this, BestFn](
13633 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13634 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13635 };
13636
13637 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13638 // option, so we can potentially give the user a better error
13639 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13640 return false;
13641 Matches[0] = *Best;
13642 Matches.resize(1);
13643 return true;
13644 }
13645
13646 bool isTargetTypeAFunction() const {
13647 return TargetFunctionType->isFunctionType();
13648 }
13649
13650 // [ToType] [Return]
13651
13652 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13653 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13654 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13655 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13656 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13657 }
13658
13659 // return true if any matching specializations were found
13660 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13661 const DeclAccessPair& CurAccessFunPair) {
13662 if (CXXMethodDecl *Method
13663 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13664 // Skip non-static function templates when converting to pointer, and
13665 // static when converting to member pointer.
13666 bool CanConvertToFunctionPointer =
13667 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13668 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13669 return false;
13670 }
13671 else if (TargetTypeIsNonStaticMemberFunction)
13672 return false;
13673
13674 // C++ [over.over]p2:
13675 // If the name is a function template, template argument deduction is
13676 // done (14.8.2.2), and if the argument deduction succeeds, the
13677 // resulting template argument list is used to generate a single
13678 // function template specialization, which is added to the set of
13679 // overloaded functions considered.
13680 FunctionDecl *Specialization = nullptr;
13681 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13682 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13683 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13684 Specialization, Info, /*IsAddressOfFunction*/ true);
13685 Result != TemplateDeductionResult::Success) {
13686 // Make a note of the failed deduction for diagnostics.
13687 FailedCandidates.addCandidate()
13688 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13689 MakeDeductionFailureInfo(Context, Result, Info));
13690 return false;
13691 }
13692
13693 // Template argument deduction ensures that we have an exact match or
13694 // compatible pointer-to-function arguments that would be adjusted by ICS.
13695 // This function template specicalization works.
13696 assert(S.isSameOrCompatibleFunctionType(
13697 Context.getCanonicalType(Specialization->getType()),
13698 Context.getCanonicalType(TargetFunctionType)));
13699
13700 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
13701 return false;
13702
13703 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13704 return true;
13705 }
13706
13707 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13708 const DeclAccessPair& CurAccessFunPair) {
13709 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13710 // Skip non-static functions when converting to pointer, and static
13711 // when converting to member pointer.
13712 bool CanConvertToFunctionPointer =
13713 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13714 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13715 return false;
13716 }
13717 else if (TargetTypeIsNonStaticMemberFunction)
13718 return false;
13719
13720 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13721 if (S.getLangOpts().CUDA) {
13722 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13723 if (!(Caller && Caller->isImplicit()) &&
13724 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13725 return false;
13726 }
13727 if (FunDecl->isMultiVersion()) {
13728 const auto *TA = FunDecl->getAttr<TargetAttr>();
13729 if (TA && !TA->isDefaultVersion())
13730 return false;
13731 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13732 if (TVA && !TVA->isDefaultVersion())
13733 return false;
13734 }
13735
13736 // If any candidate has a placeholder return type, trigger its deduction
13737 // now.
13738 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13739 Complain)) {
13740 HasComplained |= Complain;
13741 return false;
13742 }
13743
13744 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13745 return false;
13746
13747 // If we're in C, we need to support types that aren't exactly identical.
13748 if (!S.getLangOpts().CPlusPlus ||
13749 candidateHasExactlyCorrectType(FunDecl)) {
13750 Matches.push_back(std::make_pair(
13751 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13752 FoundNonTemplateFunction = true;
13753 return true;
13754 }
13755 }
13756
13757 return false;
13758 }
13759
13760 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13761 bool Ret = false;
13762
13763 // If the overload expression doesn't have the form of a pointer to
13764 // member, don't try to convert it to a pointer-to-member type.
13765 if (IsInvalidFormOfPointerToMemberFunction())
13766 return false;
13767
13768 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13769 E = OvlExpr->decls_end();
13770 I != E; ++I) {
13771 // Look through any using declarations to find the underlying function.
13772 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13773
13774 // C++ [over.over]p3:
13775 // Non-member functions and static member functions match
13776 // targets of type "pointer-to-function" or "reference-to-function."
13777 // Nonstatic member functions match targets of
13778 // type "pointer-to-member-function."
13779 // Note that according to DR 247, the containing class does not matter.
13780 if (FunctionTemplateDecl *FunctionTemplate
13781 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13782 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13783 Ret = true;
13784 }
13785 // If we have explicit template arguments supplied, skip non-templates.
13786 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13787 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13788 Ret = true;
13789 }
13790 assert(Ret || Matches.empty());
13791 return Ret;
13792 }
13793
13794 void EliminateAllExceptMostSpecializedTemplate() {
13795 // [...] and any given function template specialization F1 is
13796 // eliminated if the set contains a second function template
13797 // specialization whose function template is more specialized
13798 // than the function template of F1 according to the partial
13799 // ordering rules of 14.5.5.2.
13800
13801 // The algorithm specified above is quadratic. We instead use a
13802 // two-pass algorithm (similar to the one used to identify the
13803 // best viable function in an overload set) that identifies the
13804 // best function template (if it exists).
13805
13806 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13807 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13808 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13809
13810 // TODO: It looks like FailedCandidates does not serve much purpose
13811 // here, since the no_viable diagnostic has index 0.
13812 UnresolvedSetIterator Result = S.getMostSpecialized(
13813 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13814 SourceExpr->getBeginLoc(), S.PDiag(),
13815 S.PDiag(diag::err_addr_ovl_ambiguous)
13816 << Matches[0].second->getDeclName(),
13817 S.PDiag(diag::note_ovl_candidate)
13818 << (unsigned)oc_function << (unsigned)ocs_described_template,
13819 Complain, TargetFunctionType);
13820
13821 if (Result != MatchesCopy.end()) {
13822 // Make it the first and only element
13823 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13824 Matches[0].second = cast<FunctionDecl>(*Result);
13825 Matches.resize(1);
13826 } else
13827 HasComplained |= Complain;
13828 }
13829
13830 void EliminateAllTemplateMatches() {
13831 // [...] any function template specializations in the set are
13832 // eliminated if the set also contains a non-template function, [...]
13833 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13834 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13835 ++I;
13836 else {
13837 Matches[I] = Matches[--N];
13838 Matches.resize(N);
13839 }
13840 }
13841 }
13842
13843 void EliminateLessPartialOrderingConstrainedMatches() {
13844 // C++ [over.over]p5:
13845 // [...] Any given non-template function F0 is eliminated if the set
13846 // contains a second non-template function that is more
13847 // partial-ordering-constrained than F0. [...]
13848 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13849 "Call EliminateAllTemplateMatches() first");
13850 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13851 Results.push_back(Matches[0]);
13852 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13853 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13854 FunctionDecl *F = getMorePartialOrderingConstrained(
13855 S, Matches[I].second, Results[0].second,
13856 /*IsFn1Reversed=*/false,
13857 /*IsFn2Reversed=*/false);
13858 if (!F) {
13859 Results.push_back(Matches[I]);
13860 continue;
13861 }
13862 if (F == Matches[I].second) {
13863 Results.clear();
13864 Results.push_back(Matches[I]);
13865 }
13866 }
13867 std::swap(Matches, Results);
13868 }
13869
13870 void EliminateSuboptimalCudaMatches() {
13871 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13872 Matches);
13873 }
13874
13875 public:
13876 void ComplainNoMatchesFound() const {
13877 assert(Matches.empty());
13878 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13879 << OvlExpr->getName() << TargetFunctionType
13880 << OvlExpr->getSourceRange();
13881 if (FailedCandidates.empty())
13882 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13883 /*TakingAddress=*/true);
13884 else {
13885 // We have some deduction failure messages. Use them to diagnose
13886 // the function templates, and diagnose the non-template candidates
13887 // normally.
13888 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13889 IEnd = OvlExpr->decls_end();
13890 I != IEnd; ++I)
13891 if (FunctionDecl *Fun =
13892 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13893 if (!functionHasPassObjectSizeParams(Fun))
13894 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13895 /*TakingAddress=*/true);
13896 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13897 }
13898 }
13899
13900 bool IsInvalidFormOfPointerToMemberFunction() const {
13901 return TargetTypeIsNonStaticMemberFunction &&
13902 !OvlExprInfo.HasFormOfMemberPointer;
13903 }
13904
13905 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13906 // TODO: Should we condition this on whether any functions might
13907 // have matched, or is it more appropriate to do that in callers?
13908 // TODO: a fixit wouldn't hurt.
13909 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13910 << TargetType << OvlExpr->getSourceRange();
13911 }
13912
13913 bool IsStaticMemberFunctionFromBoundPointer() const {
13914 return StaticMemberFunctionFromBoundPointer;
13915 }
13916
13917 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13918 S.Diag(OvlExpr->getBeginLoc(),
13919 diag::err_invalid_form_pointer_member_function)
13920 << OvlExpr->getSourceRange();
13921 }
13922
13923 void ComplainOfInvalidConversion() const {
13924 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13925 << OvlExpr->getName() << TargetType;
13926 }
13927
13928 void ComplainMultipleMatchesFound() const {
13929 assert(Matches.size() > 1);
13930 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13931 << OvlExpr->getName() << OvlExpr->getSourceRange();
13932 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13933 /*TakingAddress=*/true);
13934 }
13935
13936 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13937
13938 int getNumMatches() const { return Matches.size(); }
13939
13940 FunctionDecl* getMatchingFunctionDecl() const {
13941 if (Matches.size() != 1) return nullptr;
13942 return Matches[0].second;
13943 }
13944
13945 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13946 if (Matches.size() != 1) return nullptr;
13947 return &Matches[0].first;
13948 }
13949 };
13950 }
13951
13952 FunctionDecl *
13953 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13954 QualType TargetType,
13955 bool Complain,
13956 DeclAccessPair &FoundResult,
13957 bool *pHadMultipleCandidates) {
13958 assert(AddressOfExpr->getType() == Context.OverloadTy);
13959
13960 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13961 Complain);
13962 int NumMatches = Resolver.getNumMatches();
13963 FunctionDecl *Fn = nullptr;
13964 bool ShouldComplain = Complain && !Resolver.hasComplained();
13965 if (NumMatches == 0 && ShouldComplain) {
13966 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13967 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13968 else
13969 Resolver.ComplainNoMatchesFound();
13970 }
13971 else if (NumMatches > 1 && ShouldComplain)
13972 Resolver.ComplainMultipleMatchesFound();
13973 else if (NumMatches == 1) {
13974 Fn = Resolver.getMatchingFunctionDecl();
13975 assert(Fn);
13976 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13977 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13978 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13979 if (Complain) {
13980 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13981 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13982 else
13983 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13984 }
13985 }
13986
13987 if (pHadMultipleCandidates)
13988 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13989 return Fn;
13990 }
13991
13992 FunctionDecl *
13993 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13994 OverloadExpr::FindResult R = OverloadExpr::find(E);
13995 OverloadExpr *Ovl = R.Expression;
13996 bool IsResultAmbiguous = false;
13997 FunctionDecl *Result = nullptr;
13998 DeclAccessPair DAP;
13999 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14000
14001 // Return positive for better, negative for worse, 0 for equal preference.
14002 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14003 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14004 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14005 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14006 };
14007
14008 // Don't use the AddressOfResolver because we're specifically looking for
14009 // cases where we have one overload candidate that lacks
14010 // enable_if/pass_object_size/...
14011 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14012 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14013 if (!FD)
14014 return nullptr;
14015
14016 if (!checkAddressOfFunctionIsAvailable(FD))
14017 continue;
14018
14019 // If we found a better result, update Result.
14020 auto FoundBetter = [&]() {
14021 IsResultAmbiguous = false;
14022 DAP = I.getPair();
14023 Result = FD;
14024 };
14025
14026 // We have more than one result - see if it is more
14027 // partial-ordering-constrained than the previous one.
14028 if (Result) {
14029 // Check CUDA preference first. If the candidates have differennt CUDA
14030 // preference, choose the one with higher CUDA preference. Otherwise,
14031 // choose the one with more constraints.
14032 if (getLangOpts().CUDA) {
14033 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14034 // FD has different preference than Result.
14035 if (PreferenceByCUDA != 0) {
14036 // FD is more preferable than Result.
14037 if (PreferenceByCUDA > 0)
14038 FoundBetter();
14039 continue;
14040 }
14041 }
14042 // FD has the same CUDA preference than Result. Continue to check
14043 // constraints.
14044
14045 // C++ [over.over]p5:
14046 // [...] Any given non-template function F0 is eliminated if the set
14047 // contains a second non-template function that is more
14048 // partial-ordering-constrained than F0 [...]
14049 FunctionDecl *MoreConstrained =
14050 getMorePartialOrderingConstrained(*this, FD, Result,
14051 /*IsFn1Reversed=*/false,
14052 /*IsFn2Reversed=*/false);
14053 if (MoreConstrained != FD) {
14054 if (!MoreConstrained) {
14055 IsResultAmbiguous = true;
14056 AmbiguousDecls.push_back(FD);
14057 }
14058 continue;
14059 }
14060 // FD is more constrained - replace Result with it.
14061 }
14062 FoundBetter();
14063 }
14064
14065 if (IsResultAmbiguous)
14066 return nullptr;
14067
14068 if (Result) {
14069 // We skipped over some ambiguous declarations which might be ambiguous with
14070 // the selected result.
14071 for (FunctionDecl *Skipped : AmbiguousDecls) {
14072 // If skipped candidate has different CUDA preference than the result,
14073 // there is no ambiguity. Otherwise check whether they have different
14074 // constraints.
14075 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14076 continue;
14077 if (!getMoreConstrainedFunction(Skipped, Result))
14078 return nullptr;
14079 }
14080 Pair = DAP;
14081 }
14082 return Result;
14083 }
14084
14085 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14086 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14087 Expr *E = SrcExpr.get();
14088 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14089
14090 DeclAccessPair DAP;
14091 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
14092 if (!Found || Found->isCPUDispatchMultiVersion() ||
14093 Found->isCPUSpecificMultiVersion())
14094 return false;
14095
14096 // Emitting multiple diagnostics for a function that is both inaccessible and
14097 // unavailable is consistent with our behavior elsewhere. So, always check
14098 // for both.
14099 DiagnoseUseOfDecl(Found, E->getExprLoc());
14100 CheckAddressOfMemberAccess(E, DAP);
14101 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
14102 if (Res.isInvalid())
14103 return false;
14104 Expr *Fixed = Res.get();
14105 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14106 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14107 else
14108 SrcExpr = Fixed;
14109 return true;
14110 }
14111
14112 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14113 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14114 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14115 // C++ [over.over]p1:
14116 // [...] [Note: any redundant set of parentheses surrounding the
14117 // overloaded function name is ignored (5.1). ]
14118 // C++ [over.over]p1:
14119 // [...] The overloaded function name can be preceded by the &
14120 // operator.
14121
14122 // If we didn't actually find any template-ids, we're done.
14123 if (!ovl->hasExplicitTemplateArgs())
14124 return nullptr;
14125
14126 TemplateArgumentListInfo ExplicitTemplateArgs;
14127 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14128
14129 // Look through all of the overloaded functions, searching for one
14130 // whose type matches exactly.
14131 FunctionDecl *Matched = nullptr;
14132 for (UnresolvedSetIterator I = ovl->decls_begin(),
14133 E = ovl->decls_end(); I != E; ++I) {
14134 // C++0x [temp.arg.explicit]p3:
14135 // [...] In contexts where deduction is done and fails, or in contexts
14136 // where deduction is not done, if a template argument list is
14137 // specified and it, along with any default template arguments,
14138 // identifies a single function template specialization, then the
14139 // template-id is an lvalue for the function template specialization.
14140 FunctionTemplateDecl *FunctionTemplate =
14141 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14142 if (!FunctionTemplate)
14143 continue;
14144
14145 // C++ [over.over]p2:
14146 // If the name is a function template, template argument deduction is
14147 // done (14.8.2.2), and if the argument deduction succeeds, the
14148 // resulting template argument list is used to generate a single
14149 // function template specialization, which is added to the set of
14150 // overloaded functions considered.
14151 FunctionDecl *Specialization = nullptr;
14152 TemplateDeductionInfo Info(ovl->getNameLoc());
14153 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14154 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14155 /*IsAddressOfFunction*/ true);
14156 Result != TemplateDeductionResult::Success) {
14157 // Make a note of the failed deduction for diagnostics.
14158 if (FailedTSC)
14159 FailedTSC->addCandidate().set(
14160 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14161 MakeDeductionFailureInfo(Context, Result, Info));
14162 continue;
14163 }
14164
14165 assert(Specialization && "no specialization and no error?");
14166
14167 // C++ [temp.deduct.call]p6:
14168 // [...] If all successful deductions yield the same deduced A, that
14169 // deduced A is the result of deduction; otherwise, the parameter is
14170 // treated as a non-deduced context.
14171 if (Matched) {
14172 if (ForTypeDeduction &&
14173 isSameOrCompatibleFunctionType(Matched->getType(),
14174 Specialization->getType()))
14175 continue;
14176 // Multiple matches; we can't resolve to a single declaration.
14177 if (Complain) {
14178 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14179 << ovl->getName();
14180 NoteAllOverloadCandidates(ovl);
14181 }
14182 return nullptr;
14183 }
14184
14185 Matched = Specialization;
14186 if (FoundResult) *FoundResult = I.getPair();
14187 }
14188
14189 if (Matched &&
14190 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14191 return nullptr;
14192
14193 return Matched;
14194 }
14195
14196 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14197 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14198 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14199 unsigned DiagIDForComplaining) {
14200 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14201
14202 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
14203
14204 DeclAccessPair found;
14205 ExprResult SingleFunctionExpression;
14206 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14207 ovl.Expression, /*complain*/ false, &found)) {
14208 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14209 SrcExpr = ExprError();
14210 return true;
14211 }
14212
14213 // It is only correct to resolve to an instance method if we're
14214 // resolving a form that's permitted to be a pointer to member.
14215 // Otherwise we'll end up making a bound member expression, which
14216 // is illegal in all the contexts we resolve like this.
14217 if (!ovl.HasFormOfMemberPointer &&
14218 isa<CXXMethodDecl>(fn) &&
14219 cast<CXXMethodDecl>(fn)->isInstance()) {
14220 if (!complain) return false;
14221
14222 Diag(ovl.Expression->getExprLoc(),
14223 diag::err_bound_member_function)
14224 << 0 << ovl.Expression->getSourceRange();
14225
14226 // TODO: I believe we only end up here if there's a mix of
14227 // static and non-static candidates (otherwise the expression
14228 // would have 'bound member' type, not 'overload' type).
14229 // Ideally we would note which candidate was chosen and why
14230 // the static candidates were rejected.
14231 SrcExpr = ExprError();
14232 return true;
14233 }
14234
14235 // Fix the expression to refer to 'fn'.
14236 SingleFunctionExpression =
14237 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14238
14239 // If desired, do function-to-pointer decay.
14240 if (doFunctionPointerConversion) {
14241 SingleFunctionExpression =
14242 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14243 if (SingleFunctionExpression.isInvalid()) {
14244 SrcExpr = ExprError();
14245 return true;
14246 }
14247 }
14248 }
14249
14250 if (!SingleFunctionExpression.isUsable()) {
14251 if (complain) {
14252 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14253 << ovl.Expression->getName()
14254 << DestTypeForComplaining
14255 << OpRangeForComplaining
14256 << ovl.Expression->getQualifierLoc().getSourceRange();
14257 NoteAllOverloadCandidates(SrcExpr.get());
14258
14259 SrcExpr = ExprError();
14260 return true;
14261 }
14262
14263 return false;
14264 }
14265
14266 SrcExpr = SingleFunctionExpression;
14267 return true;
14268 }
14269
14270 /// Add a single candidate to the overload set.
14271 static void AddOverloadedCallCandidate(Sema &S,
14272 DeclAccessPair FoundDecl,
14273 TemplateArgumentListInfo *ExplicitTemplateArgs,
14274 ArrayRef<Expr *> Args,
14275 OverloadCandidateSet &CandidateSet,
14276 bool PartialOverloading,
14277 bool KnownValid) {
14278 NamedDecl *Callee = FoundDecl.getDecl();
14279 if (isa<UsingShadowDecl>(Callee))
14280 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14281
14282 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14283 if (ExplicitTemplateArgs) {
14284 assert(!KnownValid && "Explicit template arguments?");
14285 return;
14286 }
14287 // Prevent ill-formed function decls to be added as overload candidates.
14288 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14289 return;
14290
14291 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14292 /*SuppressUserConversions=*/false,
14293 PartialOverloading);
14294 return;
14295 }
14296
14297 if (FunctionTemplateDecl *FuncTemplate
14298 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14299 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14300 ExplicitTemplateArgs, Args, CandidateSet,
14301 /*SuppressUserConversions=*/false,
14302 PartialOverloading);
14303 return;
14304 }
14305
14306 assert(!KnownValid && "unhandled case in overloaded call candidate");
14307 }
14308
14309 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14310 ArrayRef<Expr *> Args,
14311 OverloadCandidateSet &CandidateSet,
14312 bool PartialOverloading) {
14313
14314 #ifndef NDEBUG
14315 // Verify that ArgumentDependentLookup is consistent with the rules
14316 // in C++0x [basic.lookup.argdep]p3:
14317 //
14318 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14319 // and let Y be the lookup set produced by argument dependent
14320 // lookup (defined as follows). If X contains
14321 //
14322 // -- a declaration of a class member, or
14323 //
14324 // -- a block-scope function declaration that is not a
14325 // using-declaration, or
14326 //
14327 // -- a declaration that is neither a function or a function
14328 // template
14329 //
14330 // then Y is empty.
14331
14332 if (ULE->requiresADL()) {
14333 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14334 E = ULE->decls_end(); I != E; ++I) {
14335 assert(!(*I)->getDeclContext()->isRecord());
14336 assert(isa<UsingShadowDecl>(*I) ||
14337 !(*I)->getDeclContext()->isFunctionOrMethod());
14338 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14339 }
14340 }
14341 #endif
14342
14343 // It would be nice to avoid this copy.
14344 TemplateArgumentListInfo TABuffer;
14345 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14346 if (ULE->hasExplicitTemplateArgs()) {
14347 ULE->copyTemplateArgumentsInto(TABuffer);
14348 ExplicitTemplateArgs = &TABuffer;
14349 }
14350
14351 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14352 E = ULE->decls_end(); I != E; ++I)
14353 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14354 CandidateSet, PartialOverloading,
14355 /*KnownValid*/ true);
14356
14357 if (ULE->requiresADL())
14358 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
14359 Args, ExplicitTemplateArgs,
14360 CandidateSet, PartialOverloading);
14361 }
14362
14363 void Sema::AddOverloadedCallCandidates(
14364 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14365 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14366 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14367 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14368 CandidateSet, false, /*KnownValid*/ false);
14369 }
14370
14371 /// Determine whether a declaration with the specified name could be moved into
14372 /// a different namespace.
14373 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14374 switch (Name.getCXXOverloadedOperator()) {
14375 case OO_New: case OO_Array_New:
14376 case OO_Delete: case OO_Array_Delete:
14377 return false;
14378
14379 default:
14380 return true;
14381 }
14382 }
14383
14384 /// Attempt to recover from an ill-formed use of a non-dependent name in a
14385 /// template, where the non-dependent name was declared after the template
14386 /// was defined. This is common in code written for a compilers which do not
14387 /// correctly implement two-stage name lookup.
14388 ///
14389 /// Returns true if a viable candidate was found and a diagnostic was issued.
14390 static bool DiagnoseTwoPhaseLookup(
14391 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14392 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14393 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14394 CXXRecordDecl **FoundInClass = nullptr) {
14395 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14396 return false;
14397
14398 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14399 if (DC->isTransparentContext())
14400 continue;
14401
14402 SemaRef.LookupQualifiedName(R, DC);
14403
14404 if (!R.empty()) {
14405 R.suppressDiagnostics();
14406
14407 OverloadCandidateSet Candidates(FnLoc, CSK);
14408 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14409 Candidates);
14410
14411 OverloadCandidateSet::iterator Best;
14412 OverloadingResult OR =
14413 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14414
14415 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14416 // We either found non-function declarations or a best viable function
14417 // at class scope. A class-scope lookup result disables ADL. Don't
14418 // look past this, but let the caller know that we found something that
14419 // either is, or might be, usable in this class.
14420 if (FoundInClass) {
14421 *FoundInClass = RD;
14422 if (OR == OR_Success) {
14423 R.clear();
14424 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14425 R.resolveKind();
14426 }
14427 }
14428 return false;
14429 }
14430
14431 if (OR != OR_Success) {
14432 // There wasn't a unique best function or function template.
14433 return false;
14434 }
14435
14436 // Find the namespaces where ADL would have looked, and suggest
14437 // declaring the function there instead.
14438 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14439 Sema::AssociatedClassSet AssociatedClasses;
14440 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14441 AssociatedNamespaces,
14442 AssociatedClasses);
14443 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14444 if (canBeDeclaredInNamespace(R.getLookupName())) {
14445 DeclContext *Std = SemaRef.getStdNamespace();
14446 for (Sema::AssociatedNamespaceSet::iterator
14447 it = AssociatedNamespaces.begin(),
14448 end = AssociatedNamespaces.end(); it != end; ++it) {
14449 // Never suggest declaring a function within namespace 'std'.
14450 if (Std && Std->Encloses(*it))
14451 continue;
14452
14453 // Never suggest declaring a function within a namespace with a
14454 // reserved name, like __gnu_cxx.
14455 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14456 if (NS &&
14457 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14458 continue;
14459
14460 SuggestedNamespaces.insert(*it);
14461 }
14462 }
14463
14464 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14465 << R.getLookupName();
14466 if (SuggestedNamespaces.empty()) {
14467 SemaRef.Diag(Best->Function->getLocation(),
14468 diag::note_not_found_by_two_phase_lookup)
14469 << R.getLookupName() << 0;
14470 } else if (SuggestedNamespaces.size() == 1) {
14471 SemaRef.Diag(Best->Function->getLocation(),
14472 diag::note_not_found_by_two_phase_lookup)
14473 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14474 } else {
14475 // FIXME: It would be useful to list the associated namespaces here,
14476 // but the diagnostics infrastructure doesn't provide a way to produce
14477 // a localized representation of a list of items.
14478 SemaRef.Diag(Best->Function->getLocation(),
14479 diag::note_not_found_by_two_phase_lookup)
14480 << R.getLookupName() << 2;
14481 }
14482
14483 // Try to recover by calling this function.
14484 return true;
14485 }
14486
14487 R.clear();
14488 }
14489
14490 return false;
14491 }
14492
14493 /// Attempt to recover from ill-formed use of a non-dependent operator in a
14494 /// template, where the non-dependent operator was declared after the template
14495 /// was defined.
14496 ///
14497 /// Returns true if a viable candidate was found and a diagnostic was issued.
14498 static bool
14499 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14500 SourceLocation OpLoc,
14501 ArrayRef<Expr *> Args) {
14502 DeclarationName OpName =
14503 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14504 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14505 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14506 OverloadCandidateSet::CSK_Operator,
14507 /*ExplicitTemplateArgs=*/nullptr, Args);
14508 }
14509
14510 namespace {
14511 class BuildRecoveryCallExprRAII {
14512 Sema &SemaRef;
14513 Sema::SatisfactionStackResetRAII SatStack;
14514
14515 public:
14516 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14517 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14518 SemaRef.IsBuildingRecoveryCallExpr = true;
14519 }
14520
14521 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14522 };
14523 }
14524
14525 /// Attempts to recover from a call where no functions were found.
14526 ///
14527 /// This function will do one of three things:
14528 /// * Diagnose, recover, and return a recovery expression.
14529 /// * Diagnose, fail to recover, and return ExprError().
14530 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14531 /// expected to diagnose as appropriate.
14532 static ExprResult
14533 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14534 UnresolvedLookupExpr *ULE,
14535 SourceLocation LParenLoc,
14536 MutableArrayRef<Expr *> Args,
14537 SourceLocation RParenLoc,
14538 bool EmptyLookup, bool AllowTypoCorrection) {
14539 // Do not try to recover if it is already building a recovery call.
14540 // This stops infinite loops for template instantiations like
14541 //
14542 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14543 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14544 if (SemaRef.IsBuildingRecoveryCallExpr)
14545 return ExprResult();
14546 BuildRecoveryCallExprRAII RCE(SemaRef);
14547
14548 CXXScopeSpec SS;
14549 SS.Adopt(ULE->getQualifierLoc());
14550 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14551
14552 TemplateArgumentListInfo TABuffer;
14553 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14554 if (ULE->hasExplicitTemplateArgs()) {
14555 ULE->copyTemplateArgumentsInto(TABuffer);
14556 ExplicitTemplateArgs = &TABuffer;
14557 }
14558
14559 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14560 Sema::LookupOrdinaryName);
14561 CXXRecordDecl *FoundInClass = nullptr;
14562 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14563 OverloadCandidateSet::CSK_Normal,
14564 ExplicitTemplateArgs, Args, &FoundInClass)) {
14565 // OK, diagnosed a two-phase lookup issue.
14566 } else if (EmptyLookup) {
14567 // Try to recover from an empty lookup with typo correction.
14568 R.clear();
14569 NoTypoCorrectionCCC NoTypoValidator{};
14570 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14571 ExplicitTemplateArgs != nullptr,
14572 dyn_cast<MemberExpr>(Fn));
14573 CorrectionCandidateCallback &Validator =
14574 AllowTypoCorrection
14575 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14576 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14577 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14578 Args))
14579 return ExprError();
14580 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14581 // We found a usable declaration of the name in a dependent base of some
14582 // enclosing class.
14583 // FIXME: We should also explain why the candidates found by name lookup
14584 // were not viable.
14585 if (SemaRef.DiagnoseDependentMemberLookup(R))
14586 return ExprError();
14587 } else {
14588 // We had viable candidates and couldn't recover; let the caller diagnose
14589 // this.
14590 return ExprResult();
14591 }
14592
14593 // If we get here, we should have issued a diagnostic and formed a recovery
14594 // lookup result.
14595 assert(!R.empty() && "lookup results empty despite recovery");
14596
14597 // If recovery created an ambiguity, just bail out.
14598 if (R.isAmbiguous()) {
14599 R.suppressDiagnostics();
14600 return ExprError();
14601 }
14602
14603 // Build an implicit member call if appropriate. Just drop the
14604 // casts and such from the call, we don't really care.
14605 ExprResult NewFn = ExprError();
14606 if ((*R.begin())->isCXXClassMember())
14607 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14608 ExplicitTemplateArgs, S);
14609 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14610 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14611 ExplicitTemplateArgs);
14612 else
14613 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14614
14615 if (NewFn.isInvalid())
14616 return ExprError();
14617
14618 // This shouldn't cause an infinite loop because we're giving it
14619 // an expression with viable lookup results, which should never
14620 // end up here.
14621 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14622 MultiExprArg(Args.data(), Args.size()),
14623 RParenLoc);
14624 }
14625
14626 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14627 UnresolvedLookupExpr *ULE,
14628 MultiExprArg Args,
14629 SourceLocation RParenLoc,
14630 OverloadCandidateSet *CandidateSet,
14631 ExprResult *Result) {
14632 #ifndef NDEBUG
14633 if (ULE->requiresADL()) {
14634 // To do ADL, we must have found an unqualified name.
14635 assert(!ULE->getQualifier() && "qualified name with ADL");
14636
14637 // We don't perform ADL for implicit declarations of builtins.
14638 // Verify that this was correctly set up.
14639 FunctionDecl *F;
14640 if (ULE->decls_begin() != ULE->decls_end() &&
14641 ULE->decls_begin() + 1 == ULE->decls_end() &&
14642 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14643 F->getBuiltinID() && F->isImplicit())
14644 llvm_unreachable("performing ADL for builtin");
14645
14646 // We don't perform ADL in C.
14647 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14648 }
14649 #endif
14650
14651 UnbridgedCastsSet UnbridgedCasts;
14652 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14653 *Result = ExprError();
14654 return true;
14655 }
14656
14657 // Add the functions denoted by the callee to the set of candidate
14658 // functions, including those from argument-dependent lookup.
14659 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14660
14661 if (getLangOpts().MSVCCompat &&
14662 CurContext->isDependentContext() && !isSFINAEContext() &&
14663 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14664
14665 OverloadCandidateSet::iterator Best;
14666 if (CandidateSet->empty() ||
14667 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14668 OR_No_Viable_Function) {
14669 // In Microsoft mode, if we are inside a template class member function
14670 // then create a type dependent CallExpr. The goal is to postpone name
14671 // lookup to instantiation time to be able to search into type dependent
14672 // base classes.
14673 CallExpr *CE =
14674 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14675 RParenLoc, CurFPFeatureOverrides());
14676 CE->markDependentForPostponedNameLookup();
14677 *Result = CE;
14678 return true;
14679 }
14680 }
14681
14682 if (CandidateSet->empty())
14683 return false;
14684
14685 UnbridgedCasts.restore();
14686 return false;
14687 }
14688
14689 // Guess at what the return type for an unresolvable overload should be.
14690 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14691 OverloadCandidateSet::iterator *Best) {
14692 std::optional<QualType> Result;
14693 // Adjust Type after seeing a candidate.
14694 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14695 if (!Candidate.Function)
14696 return;
14697 if (Candidate.Function->isInvalidDecl())
14698 return;
14699 QualType T = Candidate.Function->getReturnType();
14700 if (T.isNull())
14701 return;
14702 if (!Result)
14703 Result = T;
14704 else if (Result != T)
14705 Result = QualType();
14706 };
14707
14708 // Look for an unambiguous type from a progressively larger subset.
14709 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14710 //
14711 // First, consider only the best candidate.
14712 if (Best && *Best != CS.end())
14713 ConsiderCandidate(**Best);
14714 // Next, consider only viable candidates.
14715 if (!Result)
14716 for (const auto &C : CS)
14717 if (C.Viable)
14718 ConsiderCandidate(C);
14719 // Finally, consider all candidates.
14720 if (!Result)
14721 for (const auto &C : CS)
14722 ConsiderCandidate(C);
14723
14724 if (!Result)
14725 return QualType();
14726 auto Value = *Result;
14727 if (Value.isNull() || Value->isUndeducedType())
14728 return QualType();
14729 return Value;
14730 }
14731
14732 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14733 /// the completed call expression. If overload resolution fails, emits
14734 /// diagnostics and returns ExprError()
14735 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14736 UnresolvedLookupExpr *ULE,
14737 SourceLocation LParenLoc,
14738 MultiExprArg Args,
14739 SourceLocation RParenLoc,
14740 Expr *ExecConfig,
14741 OverloadCandidateSet *CandidateSet,
14742 OverloadCandidateSet::iterator *Best,
14743 OverloadingResult OverloadResult,
14744 bool AllowTypoCorrection) {
14745 switch (OverloadResult) {
14746 case OR_Success: {
14747 FunctionDecl *FDecl = (*Best)->Function;
14748 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14749 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14750 return ExprError();
14751 ExprResult Res =
14752 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14753 if (Res.isInvalid())
14754 return ExprError();
14755 return SemaRef.BuildResolvedCallExpr(
14756 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14757 /*IsExecConfig=*/false,
14758 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14759 }
14760
14761 case OR_No_Viable_Function: {
14762 if (*Best != CandidateSet->end() &&
14763 CandidateSet->getKind() ==
14764 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14765 if (CXXMethodDecl *M =
14766 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14767 M && M->isImplicitObjectMemberFunction()) {
14768 CandidateSet->NoteCandidates(
14769 PartialDiagnosticAt(
14770 Fn->getBeginLoc(),
14771 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14772 SemaRef, OCD_AmbiguousCandidates, Args);
14773 return ExprError();
14774 }
14775 }
14776
14777 // Try to recover by looking for viable functions which the user might
14778 // have meant to call.
14779 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14780 Args, RParenLoc,
14781 CandidateSet->empty(),
14782 AllowTypoCorrection);
14783 if (Recovery.isInvalid() || Recovery.isUsable())
14784 return Recovery;
14785
14786 // If the user passes in a function that we can't take the address of, we
14787 // generally end up emitting really bad error messages. Here, we attempt to
14788 // emit better ones.
14789 for (const Expr *Arg : Args) {
14790 if (!Arg->getType()->isFunctionType())
14791 continue;
14792 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14793 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14794 if (FD &&
14795 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14796 Arg->getExprLoc()))
14797 return ExprError();
14798 }
14799 }
14800
14801 CandidateSet->NoteCandidates(
14802 PartialDiagnosticAt(
14803 Fn->getBeginLoc(),
14804 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14805 << ULE->getName() << Fn->getSourceRange()),
14806 SemaRef, OCD_AllCandidates, Args);
14807 break;
14808 }
14809
14810 case OR_Ambiguous:
14811 CandidateSet->NoteCandidates(
14812 PartialDiagnosticAt(Fn->getBeginLoc(),
14813 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14814 << ULE->getName() << Fn->getSourceRange()),
14815 SemaRef, OCD_AmbiguousCandidates, Args);
14816 break;
14817
14818 case OR_Deleted: {
14819 FunctionDecl *FDecl = (*Best)->Function;
14820 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14821 Fn->getSourceRange(), ULE->getName(),
14822 *CandidateSet, FDecl, Args);
14823
14824 // We emitted an error for the unavailable/deleted function call but keep
14825 // the call in the AST.
14826 ExprResult Res =
14827 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14828 if (Res.isInvalid())
14829 return ExprError();
14830 return SemaRef.BuildResolvedCallExpr(
14831 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14832 /*IsExecConfig=*/false,
14833 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14834 }
14835 }
14836
14837 // Overload resolution failed, try to recover.
14838 SmallVector<Expr *, 8> SubExprs = {Fn};
14839 SubExprs.append(Args.begin(), Args.end());
14840 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14841 chooseRecoveryType(*CandidateSet, Best));
14842 }
14843
14844 static void markUnaddressableCandidatesUnviable(Sema &S,
14845 OverloadCandidateSet &CS) {
14846 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14847 if (I->Viable &&
14848 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14849 I->Viable = false;
14850 I->FailureKind = ovl_fail_addr_not_available;
14851 }
14852 }
14853 }
14854
14855 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14856 UnresolvedLookupExpr *ULE,
14857 SourceLocation LParenLoc,
14858 MultiExprArg Args,
14859 SourceLocation RParenLoc,
14860 Expr *ExecConfig,
14861 bool AllowTypoCorrection,
14862 bool CalleesAddressIsTaken) {
14863
14864 OverloadCandidateSet::CandidateSetKind CSK =
14865 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14866 : OverloadCandidateSet::CSK_Normal;
14867
14868 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14869 ExprResult result;
14870
14871 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14872 &result))
14873 return result;
14874
14875 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14876 // functions that aren't addressible are considered unviable.
14877 if (CalleesAddressIsTaken)
14878 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14879
14880 OverloadCandidateSet::iterator Best;
14881 OverloadingResult OverloadResult =
14882 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14883
14884 // [C++23][over.call.func]
14885 // if overload resolution selects a non-static member function,
14886 // the call is ill-formed;
14887 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
14888 Best != CandidateSet.end()) {
14889 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14890 M && M->isImplicitObjectMemberFunction()) {
14891 OverloadResult = OR_No_Viable_Function;
14892 }
14893 }
14894
14895 // Model the case with a call to a templated function whose definition
14896 // encloses the call and whose return type contains a placeholder type as if
14897 // the UnresolvedLookupExpr was type-dependent.
14898 if (OverloadResult == OR_Success) {
14899 const FunctionDecl *FDecl = Best->Function;
14900 if (LangOpts.CUDA)
14901 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14902 if (FDecl && FDecl->isTemplateInstantiation() &&
14903 FDecl->getReturnType()->isUndeducedType()) {
14904
14905 // Creating dependent CallExpr is not okay if the enclosing context itself
14906 // is not dependent. This situation notably arises if a non-dependent
14907 // member function calls the later-defined overloaded static function.
14908 //
14909 // For example, in
14910 // class A {
14911 // void c() { callee(1); }
14912 // static auto callee(auto x) { }
14913 // };
14914 //
14915 // Here callee(1) is unresolved at the call site, but is not inside a
14916 // dependent context. There will be no further attempt to resolve this
14917 // call if it is made dependent.
14918
14919 if (const auto *TP =
14920 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14921 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14922 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14923 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14924 }
14925 }
14926 }
14927
14928 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14929 ExecConfig, &CandidateSet, &Best,
14930 OverloadResult, AllowTypoCorrection);
14931 }
14932
14933 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14934 NestedNameSpecifierLoc NNSLoc,
14935 DeclarationNameInfo DNI,
14936 const UnresolvedSetImpl &Fns,
14937 bool PerformADL) {
14938 return UnresolvedLookupExpr::Create(
14939 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14940 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14941 }
14942
14943 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14944 CXXConversionDecl *Method,
14945 bool HadMultipleCandidates) {
14946 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14947 // the FoundDecl as it impedes TransformMemberExpr.
14948 // We go a bit further here: if there's no difference in UnderlyingDecl,
14949 // then using FoundDecl vs Method shouldn't make a difference either.
14950 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14951 FoundDecl = Method;
14952 // Convert the expression to match the conversion function's implicit object
14953 // parameter.
14954 ExprResult Exp;
14955 if (Method->isExplicitObjectMemberFunction())
14956 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14957 else
14958 Exp = PerformImplicitObjectArgumentInitialization(
14959 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14960 if (Exp.isInvalid())
14961 return true;
14962
14963 if (Method->getParent()->isLambda() &&
14964 Method->getConversionType()->isBlockPointerType()) {
14965 // This is a lambda conversion to block pointer; check if the argument
14966 // was a LambdaExpr.
14967 Expr *SubE = E;
14968 auto *CE = dyn_cast<CastExpr>(SubE);
14969 if (CE && CE->getCastKind() == CK_NoOp)
14970 SubE = CE->getSubExpr();
14971 SubE = SubE->IgnoreParens();
14972 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14973 SubE = BE->getSubExpr();
14974 if (isa<LambdaExpr>(SubE)) {
14975 // For the conversion to block pointer on a lambda expression, we
14976 // construct a special BlockLiteral instead; this doesn't really make
14977 // a difference in ARC, but outside of ARC the resulting block literal
14978 // follows the normal lifetime rules for block literals instead of being
14979 // autoreleased.
14980 PushExpressionEvaluationContext(
14981 ExpressionEvaluationContext::PotentiallyEvaluated);
14982 ExprResult BlockExp = BuildBlockForLambdaConversion(
14983 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14984 PopExpressionEvaluationContext();
14985
14986 // FIXME: This note should be produced by a CodeSynthesisContext.
14987 if (BlockExp.isInvalid())
14988 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14989 return BlockExp;
14990 }
14991 }
14992 CallExpr *CE;
14993 QualType ResultType = Method->getReturnType();
14994 ExprValueKind VK = Expr::getValueKindForType(ResultType);
14995 ResultType = ResultType.getNonLValueExprType(Context);
14996 if (Method->isExplicitObjectMemberFunction()) {
14997 ExprResult FnExpr =
14998 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14999 HadMultipleCandidates, E->getBeginLoc());
15000 if (FnExpr.isInvalid())
15001 return ExprError();
15002 Expr *ObjectParam = Exp.get();
15003 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15004 ResultType, VK, Exp.get()->getEndLoc(),
15005 CurFPFeatureOverrides());
15006 CE->setUsesMemberSyntax(true);
15007 } else {
15008 MemberExpr *ME =
15009 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15010 NestedNameSpecifierLoc(), SourceLocation(), Method,
15011 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15012 HadMultipleCandidates, DeclarationNameInfo(),
15013 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15014
15015 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15016 Exp.get()->getEndLoc(),
15017 CurFPFeatureOverrides());
15018 }
15019
15020 if (CheckFunctionCall(Method, CE,
15021 Method->getType()->castAs<FunctionProtoType>()))
15022 return ExprError();
15023
15024 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
15025 }
15026
15027 ExprResult
15028 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15029 const UnresolvedSetImpl &Fns,
15030 Expr *Input, bool PerformADL) {
15031 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15032 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15033 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15034 // TODO: provide better source location info.
15035 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15036
15037 if (checkPlaceholderForOverload(*this, Input))
15038 return ExprError();
15039
15040 Expr *Args[2] = { Input, nullptr };
15041 unsigned NumArgs = 1;
15042
15043 // For post-increment and post-decrement, add the implicit '0' as
15044 // the second argument, so that we know this is a post-increment or
15045 // post-decrement.
15046 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15047 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15048 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15049 SourceLocation());
15050 NumArgs = 2;
15051 }
15052
15053 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15054
15055 if (Input->isTypeDependent()) {
15056 ExprValueKind VK = ExprValueKind::VK_PRValue;
15057 // [C++26][expr.unary.op][expr.pre.incr]
15058 // The * operator yields an lvalue of type
15059 // The pre/post increment operators yied an lvalue.
15060 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15061 VK = VK_LValue;
15062
15063 if (Fns.empty())
15064 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15065 OK_Ordinary, OpLoc, false,
15066 CurFPFeatureOverrides());
15067
15068 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15069 ExprResult Fn = CreateUnresolvedLookupExpr(
15070 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15071 if (Fn.isInvalid())
15072 return ExprError();
15073 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15074 Context.DependentTy, VK_PRValue, OpLoc,
15075 CurFPFeatureOverrides());
15076 }
15077
15078 // Build an empty overload set.
15079 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15080
15081 // Add the candidates from the given function set.
15082 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15083
15084 // Add operator candidates that are member functions.
15085 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15086
15087 // Add candidates from ADL.
15088 if (PerformADL) {
15089 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15090 /*ExplicitTemplateArgs*/nullptr,
15091 CandidateSet);
15092 }
15093
15094 // Add builtin operator candidates.
15095 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15096
15097 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15098
15099 // Perform overload resolution.
15100 OverloadCandidateSet::iterator Best;
15101 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15102 case OR_Success: {
15103 // We found a built-in operator or an overloaded operator.
15104 FunctionDecl *FnDecl = Best->Function;
15105
15106 if (FnDecl) {
15107 Expr *Base = nullptr;
15108 // We matched an overloaded operator. Build a call to that
15109 // operator.
15110
15111 // Convert the arguments.
15112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15113 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15114
15115 ExprResult InputInit;
15116 if (Method->isExplicitObjectMemberFunction())
15117 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15118 else
15119 InputInit = PerformImplicitObjectArgumentInitialization(
15120 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15121 if (InputInit.isInvalid())
15122 return ExprError();
15123 Base = Input = InputInit.get();
15124 } else {
15125 // Convert the arguments.
15126 ExprResult InputInit
15127 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
15128 Context,
15129 FnDecl->getParamDecl(0)),
15130 SourceLocation(),
15131 Input);
15132 if (InputInit.isInvalid())
15133 return ExprError();
15134 Input = InputInit.get();
15135 }
15136
15137 // Build the actual expression node.
15138 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15139 Base, HadMultipleCandidates,
15140 OpLoc);
15141 if (FnExpr.isInvalid())
15142 return ExprError();
15143
15144 // Determine the result type.
15145 QualType ResultTy = FnDecl->getReturnType();
15146 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15147 ResultTy = ResultTy.getNonLValueExprType(Context);
15148
15149 Args[0] = Input;
15150 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15151 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15152 CurFPFeatureOverrides(),
15153 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15154
15155 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15156 return ExprError();
15157
15158 if (CheckFunctionCall(FnDecl, TheCall,
15159 FnDecl->getType()->castAs<FunctionProtoType>()))
15160 return ExprError();
15161 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15162 } else {
15163 // We matched a built-in operator. Convert the arguments, then
15164 // break out so that we will build the appropriate built-in
15165 // operator node.
15166 ExprResult InputRes = PerformImplicitConversion(
15167 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15168 AssignmentAction::Passing,
15169 CheckedConversionKind::ForBuiltinOverloadedOp);
15170 if (InputRes.isInvalid())
15171 return ExprError();
15172 Input = InputRes.get();
15173 break;
15174 }
15175 }
15176
15177 case OR_No_Viable_Function:
15178 // This is an erroneous use of an operator which can be overloaded by
15179 // a non-member function. Check for non-member operators which were
15180 // defined too late to be candidates.
15181 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15182 // FIXME: Recover by calling the found function.
15183 return ExprError();
15184
15185 // No viable function; fall through to handling this as a
15186 // built-in operator, which will produce an error message for us.
15187 break;
15188
15189 case OR_Ambiguous:
15190 CandidateSet.NoteCandidates(
15191 PartialDiagnosticAt(OpLoc,
15192 PDiag(diag::err_ovl_ambiguous_oper_unary)
15193 << UnaryOperator::getOpcodeStr(Opc)
15194 << Input->getType() << Input->getSourceRange()),
15195 *this, OCD_AmbiguousCandidates, ArgsArray,
15196 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15197 return ExprError();
15198
15199 case OR_Deleted: {
15200 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15201 // object whose method was called. Later in NoteCandidates size of ArgsArray
15202 // is passed further and it eventually ends up compared to number of
15203 // function candidate parameters which never includes the object parameter,
15204 // so slice ArgsArray to make sure apples are compared to apples.
15205 StringLiteral *Msg = Best->Function->getDeletedMessage();
15206 CandidateSet.NoteCandidates(
15207 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15208 << UnaryOperator::getOpcodeStr(Opc)
15209 << (Msg != nullptr)
15210 << (Msg ? Msg->getString() : StringRef())
15211 << Input->getSourceRange()),
15212 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15213 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15214 return ExprError();
15215 }
15216 }
15217
15218 // Either we found no viable overloaded operator or we matched a
15219 // built-in operator. In either case, fall through to trying to
15220 // build a built-in operation.
15221 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15222 }
15223
15224 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15225 OverloadedOperatorKind Op,
15226 const UnresolvedSetImpl &Fns,
15227 ArrayRef<Expr *> Args, bool PerformADL) {
15228 SourceLocation OpLoc = CandidateSet.getLocation();
15229
15230 OverloadedOperatorKind ExtraOp =
15231 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15232 ? getRewrittenOverloadedOperator(Op)
15233 : OO_None;
15234
15235 // Add the candidates from the given function set. This also adds the
15236 // rewritten candidates using these functions if necessary.
15237 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15238
15239 // As template candidates are not deduced immediately,
15240 // persist the array in the overload set.
15241 ArrayRef<Expr *> ReversedArgs;
15242 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15243 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15244 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15245
15246 // Add operator candidates that are member functions.
15247 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15248 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15249 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15250 OverloadCandidateParamOrder::Reversed);
15251
15252 // In C++20, also add any rewritten member candidates.
15253 if (ExtraOp) {
15254 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15255 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15256 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15257 OverloadCandidateParamOrder::Reversed);
15258 }
15259
15260 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15261 // performed for an assignment operator (nor for operator[] nor operator->,
15262 // which don't get here).
15263 if (Op != OO_Equal && PerformADL) {
15264 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15265 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15266 /*ExplicitTemplateArgs*/ nullptr,
15267 CandidateSet);
15268 if (ExtraOp) {
15269 DeclarationName ExtraOpName =
15270 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15271 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15272 /*ExplicitTemplateArgs*/ nullptr,
15273 CandidateSet);
15274 }
15275 }
15276
15277 // Add builtin operator candidates.
15278 //
15279 // FIXME: We don't add any rewritten candidates here. This is strictly
15280 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15281 // resulting in our selecting a rewritten builtin candidate. For example:
15282 //
15283 // enum class E { e };
15284 // bool operator!=(E, E) requires false;
15285 // bool k = E::e != E::e;
15286 //
15287 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15288 // it seems unreasonable to consider rewritten builtin candidates. A core
15289 // issue has been filed proposing to removed this requirement.
15290 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15291 }
15292
15293 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15294 BinaryOperatorKind Opc,
15295 const UnresolvedSetImpl &Fns, Expr *LHS,
15296 Expr *RHS, bool PerformADL,
15297 bool AllowRewrittenCandidates,
15298 FunctionDecl *DefaultedFn) {
15299 Expr *Args[2] = { LHS, RHS };
15300 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15301
15302 if (!getLangOpts().CPlusPlus20)
15303 AllowRewrittenCandidates = false;
15304
15305 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15306
15307 // If either side is type-dependent, create an appropriate dependent
15308 // expression.
15309 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15310 if (Fns.empty()) {
15311 // If there are no functions to store, just build a dependent
15312 // BinaryOperator or CompoundAssignment.
15313 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15314 return CompoundAssignOperator::Create(
15315 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15316 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15317 Context.DependentTy);
15318 return BinaryOperator::Create(
15319 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15320 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
15321 }
15322
15323 // FIXME: save results of ADL from here?
15324 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15325 // TODO: provide better source location info in DNLoc component.
15326 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15327 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15328 ExprResult Fn = CreateUnresolvedLookupExpr(
15329 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15330 if (Fn.isInvalid())
15331 return ExprError();
15332 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15333 Context.DependentTy, VK_PRValue, OpLoc,
15334 CurFPFeatureOverrides());
15335 }
15336
15337 // If this is the .* operator, which is not overloadable, just
15338 // create a built-in binary operator.
15339 if (Opc == BO_PtrMemD) {
15340 auto CheckPlaceholder = [&](Expr *&Arg) {
15341 ExprResult Res = CheckPlaceholderExpr(Arg);
15342 if (Res.isUsable())
15343 Arg = Res.get();
15344 return !Res.isUsable();
15345 };
15346
15347 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15348 // expression that contains placeholders (in either the LHS or RHS).
15349 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15350 return ExprError();
15351 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15352 }
15353
15354 // Always do placeholder-like conversions on the RHS.
15355 if (checkPlaceholderForOverload(*this, Args[1]))
15356 return ExprError();
15357
15358 // Do placeholder-like conversion on the LHS; note that we should
15359 // not get here with a PseudoObject LHS.
15360 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15361 if (checkPlaceholderForOverload(*this, Args[0]))
15362 return ExprError();
15363
15364 // If this is the assignment operator, we only perform overload resolution
15365 // if the left-hand side is a class or enumeration type. This is actually
15366 // a hack. The standard requires that we do overload resolution between the
15367 // various built-in candidates, but as DR507 points out, this can lead to
15368 // problems. So we do it this way, which pretty much follows what GCC does.
15369 // Note that we go the traditional code path for compound assignment forms.
15370 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15371 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15372
15373 // Build the overload set.
15374 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15375 OverloadCandidateSet::OperatorRewriteInfo(
15376 Op, OpLoc, AllowRewrittenCandidates));
15377 if (DefaultedFn)
15378 CandidateSet.exclude(DefaultedFn);
15379 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15380
15381 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15382
15383 // Perform overload resolution.
15384 OverloadCandidateSet::iterator Best;
15385 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15386 case OR_Success: {
15387 // We found a built-in operator or an overloaded operator.
15388 FunctionDecl *FnDecl = Best->Function;
15389
15390 bool IsReversed = Best->isReversed();
15391 if (IsReversed)
15392 std::swap(Args[0], Args[1]);
15393
15394 if (FnDecl) {
15395
15396 if (FnDecl->isInvalidDecl())
15397 return ExprError();
15398
15399 Expr *Base = nullptr;
15400 // We matched an overloaded operator. Build a call to that
15401 // operator.
15402
15403 OverloadedOperatorKind ChosenOp =
15404 FnDecl->getDeclName().getCXXOverloadedOperator();
15405
15406 // C++2a [over.match.oper]p9:
15407 // If a rewritten operator== candidate is selected by overload
15408 // resolution for an operator@, its return type shall be cv bool
15409 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15410 !FnDecl->getReturnType()->isBooleanType()) {
15411 bool IsExtension =
15412 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15413 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15414 : diag::err_ovl_rewrite_equalequal_not_bool)
15415 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15416 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15417 Diag(FnDecl->getLocation(), diag::note_declared_at);
15418 if (!IsExtension)
15419 return ExprError();
15420 }
15421
15422 if (AllowRewrittenCandidates && !IsReversed &&
15423 CandidateSet.getRewriteInfo().isReversible()) {
15424 // We could have reversed this operator, but didn't. Check if some
15425 // reversed form was a viable candidate, and if so, if it had a
15426 // better conversion for either parameter. If so, this call is
15427 // formally ambiguous, and allowing it is an extension.
15428 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15429 for (OverloadCandidate &Cand : CandidateSet) {
15430 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15431 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15432 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15433 if (CompareImplicitConversionSequences(
15434 *this, OpLoc, Cand.Conversions[ArgIdx],
15435 Best->Conversions[ArgIdx]) ==
15436 ImplicitConversionSequence::Better) {
15437 AmbiguousWith.push_back(Cand.Function);
15438 break;
15439 }
15440 }
15441 }
15442 }
15443
15444 if (!AmbiguousWith.empty()) {
15445 bool AmbiguousWithSelf =
15446 AmbiguousWith.size() == 1 &&
15447 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15448 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15449 << BinaryOperator::getOpcodeStr(Opc)
15450 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15451 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15452 if (AmbiguousWithSelf) {
15453 Diag(FnDecl->getLocation(),
15454 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15455 // Mark member== const or provide matching != to disallow reversed
15456 // args. Eg.
15457 // struct S { bool operator==(const S&); };
15458 // S()==S();
15459 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15460 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15461 !MD->isConst() &&
15462 !MD->hasCXXExplicitFunctionObjectParameter() &&
15463 Context.hasSameUnqualifiedType(
15464 MD->getFunctionObjectParameterType(),
15465 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15466 Context.hasSameUnqualifiedType(
15467 MD->getFunctionObjectParameterType(),
15468 Args[0]->getType()) &&
15469 Context.hasSameUnqualifiedType(
15470 MD->getFunctionObjectParameterType(),
15471 Args[1]->getType()))
15472 Diag(FnDecl->getLocation(),
15473 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15474 } else {
15475 Diag(FnDecl->getLocation(),
15476 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15477 for (auto *F : AmbiguousWith)
15478 Diag(F->getLocation(),
15479 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15480 }
15481 }
15482 }
15483
15484 // Check for nonnull = nullable.
15485 // This won't be caught in the arg's initialization: the parameter to
15486 // the assignment operator is not marked nonnull.
15487 if (Op == OO_Equal)
15488 diagnoseNullableToNonnullConversion(Args[0]->getType(),
15489 Args[1]->getType(), OpLoc);
15490
15491 // Convert the arguments.
15492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15493 // Best->Access is only meaningful for class members.
15494 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15495
15496 ExprResult Arg0, Arg1;
15497 unsigned ParamIdx = 0;
15498 if (Method->isExplicitObjectMemberFunction()) {
15499 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15500 ParamIdx = 1;
15501 } else {
15502 Arg0 = PerformImplicitObjectArgumentInitialization(
15503 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15504 }
15505 Arg1 = PerformCopyInitialization(
15506 InitializedEntity::InitializeParameter(
15507 Context, FnDecl->getParamDecl(ParamIdx)),
15508 SourceLocation(), Args[1]);
15509 if (Arg0.isInvalid() || Arg1.isInvalid())
15510 return ExprError();
15511
15512 Base = Args[0] = Arg0.getAs<Expr>();
15513 Args[1] = RHS = Arg1.getAs<Expr>();
15514 } else {
15515 // Convert the arguments.
15516 ExprResult Arg0 = PerformCopyInitialization(
15517 InitializedEntity::InitializeParameter(Context,
15518 FnDecl->getParamDecl(0)),
15519 SourceLocation(), Args[0]);
15520 if (Arg0.isInvalid())
15521 return ExprError();
15522
15523 ExprResult Arg1 =
15524 PerformCopyInitialization(
15525 InitializedEntity::InitializeParameter(Context,
15526 FnDecl->getParamDecl(1)),
15527 SourceLocation(), Args[1]);
15528 if (Arg1.isInvalid())
15529 return ExprError();
15530 Args[0] = LHS = Arg0.getAs<Expr>();
15531 Args[1] = RHS = Arg1.getAs<Expr>();
15532 }
15533
15534 // Build the actual expression node.
15535 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15536 Best->FoundDecl, Base,
15537 HadMultipleCandidates, OpLoc);
15538 if (FnExpr.isInvalid())
15539 return ExprError();
15540
15541 // Determine the result type.
15542 QualType ResultTy = FnDecl->getReturnType();
15543 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15544 ResultTy = ResultTy.getNonLValueExprType(Context);
15545
15546 CallExpr *TheCall;
15547 ArrayRef<const Expr *> ArgsArray(Args, 2);
15548 const Expr *ImplicitThis = nullptr;
15549
15550 // We always create a CXXOperatorCallExpr, even for explicit object
15551 // members; CodeGen should take care not to emit the this pointer.
15552 TheCall = CXXOperatorCallExpr::Create(
15553 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15554 CurFPFeatureOverrides(),
15555 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15556
15557 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15558 Method && Method->isImplicitObjectMemberFunction()) {
15559 // Cut off the implicit 'this'.
15560 ImplicitThis = ArgsArray[0];
15561 ArgsArray = ArgsArray.slice(1);
15562 }
15563
15564 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15565 FnDecl))
15566 return ExprError();
15567
15568 if (Op == OO_Equal) {
15569 // Check for a self move.
15570 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15571 // lifetime check.
15572 checkAssignmentLifetime(
15573 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15574 Args[1]);
15575 }
15576 if (ImplicitThis) {
15577 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15578 QualType ThisTypeFromDecl = Context.getPointerType(
15579 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15580
15581 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15582 ThisTypeFromDecl);
15583 }
15584
15585 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15586 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15587 VariadicCallType::DoesNotApply);
15588
15589 ExprResult R = MaybeBindToTemporary(TheCall);
15590 if (R.isInvalid())
15591 return ExprError();
15592
15593 R = CheckForImmediateInvocation(R, FnDecl);
15594 if (R.isInvalid())
15595 return ExprError();
15596
15597 // For a rewritten candidate, we've already reversed the arguments
15598 // if needed. Perform the rest of the rewrite now.
15599 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15600 (Op == OO_Spaceship && IsReversed)) {
15601 if (Op == OO_ExclaimEqual) {
15602 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15603 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15604 } else {
15605 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15606 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15607 Expr *ZeroLiteral =
15608 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
15609
15610 Sema::CodeSynthesisContext Ctx;
15611 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15612 Ctx.Entity = FnDecl;
15613 pushCodeSynthesisContext(Ctx);
15614
15615 R = CreateOverloadedBinOp(
15616 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15617 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15618 /*AllowRewrittenCandidates=*/false);
15619
15620 popCodeSynthesisContext();
15621 }
15622 if (R.isInvalid())
15623 return ExprError();
15624 } else {
15625 assert(ChosenOp == Op && "unexpected operator name");
15626 }
15627
15628 // Make a note in the AST if we did any rewriting.
15629 if (Best->RewriteKind != CRK_None)
15630 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15631
15632 return R;
15633 } else {
15634 // We matched a built-in operator. Convert the arguments, then
15635 // break out so that we will build the appropriate built-in
15636 // operator node.
15637 ExprResult ArgsRes0 = PerformImplicitConversion(
15638 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15639 AssignmentAction::Passing,
15640 CheckedConversionKind::ForBuiltinOverloadedOp);
15641 if (ArgsRes0.isInvalid())
15642 return ExprError();
15643 Args[0] = ArgsRes0.get();
15644
15645 ExprResult ArgsRes1 = PerformImplicitConversion(
15646 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15647 AssignmentAction::Passing,
15648 CheckedConversionKind::ForBuiltinOverloadedOp);
15649 if (ArgsRes1.isInvalid())
15650 return ExprError();
15651 Args[1] = ArgsRes1.get();
15652 break;
15653 }
15654 }
15655
15656 case OR_No_Viable_Function: {
15657 // C++ [over.match.oper]p9:
15658 // If the operator is the operator , [...] and there are no
15659 // viable functions, then the operator is assumed to be the
15660 // built-in operator and interpreted according to clause 5.
15661 if (Opc == BO_Comma)
15662 break;
15663
15664 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15665 // compare result using '==' and '<'.
15666 if (DefaultedFn && Opc == BO_Cmp) {
15667 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15668 Args[1], DefaultedFn);
15669 if (E.isInvalid() || E.isUsable())
15670 return E;
15671 }
15672
15673 // For class as left operand for assignment or compound assignment
15674 // operator do not fall through to handling in built-in, but report that
15675 // no overloaded assignment operator found
15676 ExprResult Result = ExprError();
15677 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15678 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15679 Args, OpLoc);
15680 DeferDiagsRAII DDR(*this,
15681 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15682 if (Args[0]->getType()->isRecordType() &&
15683 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15684 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15685 << BinaryOperator::getOpcodeStr(Opc)
15686 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15687 if (Args[0]->getType()->isIncompleteType()) {
15688 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15689 << Args[0]->getType()
15690 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15691 }
15692 } else {
15693 // This is an erroneous use of an operator which can be overloaded by
15694 // a non-member function. Check for non-member operators which were
15695 // defined too late to be candidates.
15696 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15697 // FIXME: Recover by calling the found function.
15698 return ExprError();
15699
15700 // No viable function; try to create a built-in operation, which will
15701 // produce an error. Then, show the non-viable candidates.
15702 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15703 }
15704 assert(Result.isInvalid() &&
15705 "C++ binary operator overloading is missing candidates!");
15706 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15707 return Result;
15708 }
15709
15710 case OR_Ambiguous:
15711 CandidateSet.NoteCandidates(
15712 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15713 << BinaryOperator::getOpcodeStr(Opc)
15714 << Args[0]->getType()
15715 << Args[1]->getType()
15716 << Args[0]->getSourceRange()
15717 << Args[1]->getSourceRange()),
15718 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15719 OpLoc);
15720 return ExprError();
15721
15722 case OR_Deleted: {
15723 if (isImplicitlyDeleted(Best->Function)) {
15724 FunctionDecl *DeletedFD = Best->Function;
15725 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15726 if (DFK.isSpecialMember()) {
15727 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15728 << Args[0]->getType() << DFK.asSpecialMember();
15729 } else {
15730 assert(DFK.isComparison());
15731 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15732 << Args[0]->getType() << DeletedFD;
15733 }
15734
15735 // The user probably meant to call this special member. Just
15736 // explain why it's deleted.
15737 NoteDeletedFunction(DeletedFD);
15738 return ExprError();
15739 }
15740
15741 StringLiteral *Msg = Best->Function->getDeletedMessage();
15742 CandidateSet.NoteCandidates(
15743 PartialDiagnosticAt(
15744 OpLoc,
15745 PDiag(diag::err_ovl_deleted_oper)
15746 << getOperatorSpelling(Best->Function->getDeclName()
15747 .getCXXOverloadedOperator())
15748 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15749 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15750 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15751 OpLoc);
15752 return ExprError();
15753 }
15754 }
15755
15756 // We matched a built-in operator; build it.
15757 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15758 }
15759
15760 ExprResult Sema::BuildSynthesizedThreeWayComparison(
15761 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15762 FunctionDecl *DefaultedFn) {
15763 const ComparisonCategoryInfo *Info =
15764 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15765 // If we're not producing a known comparison category type, we can't
15766 // synthesize a three-way comparison. Let the caller diagnose this.
15767 if (!Info)
15768 return ExprResult((Expr*)nullptr);
15769
15770 // If we ever want to perform this synthesis more generally, we will need to
15771 // apply the temporary materialization conversion to the operands.
15772 assert(LHS->isGLValue() && RHS->isGLValue() &&
15773 "cannot use prvalue expressions more than once");
15774 Expr *OrigLHS = LHS;
15775 Expr *OrigRHS = RHS;
15776
15777 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15778 // each of them multiple times below.
15779 LHS = new (Context)
15780 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15781 LHS->getObjectKind(), LHS);
15782 RHS = new (Context)
15783 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15784 RHS->getObjectKind(), RHS);
15785
15786 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15787 DefaultedFn);
15788 if (Eq.isInvalid())
15789 return ExprError();
15790
15791 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15792 true, DefaultedFn);
15793 if (Less.isInvalid())
15794 return ExprError();
15795
15796 ExprResult Greater;
15797 if (Info->isPartial()) {
15798 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15799 DefaultedFn);
15800 if (Greater.isInvalid())
15801 return ExprError();
15802 }
15803
15804 // Form the list of comparisons we're going to perform.
15805 struct Comparison {
15806 ExprResult Cmp;
15807 ComparisonCategoryResult Result;
15808 } Comparisons[4] =
15809 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
15810 : ComparisonCategoryResult::Equivalent},
15811 {Less, ComparisonCategoryResult::Less},
15812 {Greater, ComparisonCategoryResult::Greater},
15813 {ExprResult(), ComparisonCategoryResult::Unordered},
15814 };
15815
15816 int I = Info->isPartial() ? 3 : 2;
15817
15818 // Combine the comparisons with suitable conditional expressions.
15819 ExprResult Result;
15820 for (; I >= 0; --I) {
15821 // Build a reference to the comparison category constant.
15822 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15823 // FIXME: Missing a constant for a comparison category. Diagnose this?
15824 if (!VI)
15825 return ExprResult((Expr*)nullptr);
15826 ExprResult ThisResult =
15827 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15828 if (ThisResult.isInvalid())
15829 return ExprError();
15830
15831 // Build a conditional unless this is the final case.
15832 if (Result.get()) {
15833 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15834 ThisResult.get(), Result.get());
15835 if (Result.isInvalid())
15836 return ExprError();
15837 } else {
15838 Result = ThisResult;
15839 }
15840 }
15841
15842 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15843 // bind the OpaqueValueExprs before they're (repeatedly) used.
15844 Expr *SyntacticForm = BinaryOperator::Create(
15845 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15846 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15847 CurFPFeatureOverrides());
15848 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15849 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15850 }
15851
15852 static bool PrepareArgumentsForCallToObjectOfClassType(
15853 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15854 MultiExprArg Args, SourceLocation LParenLoc) {
15855
15856 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15857 unsigned NumParams = Proto->getNumParams();
15858 unsigned NumArgsSlots =
15859 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15860 // Build the full argument list for the method call (the implicit object
15861 // parameter is placed at the beginning of the list).
15862 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15863 bool IsError = false;
15864 // Initialize the implicit object parameter.
15865 // Check the argument types.
15866 for (unsigned i = 0; i != NumParams; i++) {
15867 Expr *Arg;
15868 if (i < Args.size()) {
15869 Arg = Args[i];
15870 ExprResult InputInit =
15871 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
15872 S.Context, Method->getParamDecl(i)),
15873 SourceLocation(), Arg);
15874 IsError |= InputInit.isInvalid();
15875 Arg = InputInit.getAs<Expr>();
15876 } else {
15877 ExprResult DefArg =
15878 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15879 if (DefArg.isInvalid()) {
15880 IsError = true;
15881 break;
15882 }
15883 Arg = DefArg.getAs<Expr>();
15884 }
15885
15886 MethodArgs.push_back(Arg);
15887 }
15888 return IsError;
15889 }
15890
15891 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15892 SourceLocation RLoc,
15893 Expr *Base,
15894 MultiExprArg ArgExpr) {
15895 SmallVector<Expr *, 2> Args;
15896 Args.push_back(Base);
15897 for (auto *e : ArgExpr) {
15898 Args.push_back(e);
15899 }
15900 DeclarationName OpName =
15901 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15902
15903 SourceRange Range = ArgExpr.empty()
15904 ? SourceRange{}
15905 : SourceRange(ArgExpr.front()->getBeginLoc(),
15906 ArgExpr.back()->getEndLoc());
15907
15908 // If either side is type-dependent, create an appropriate dependent
15909 // expression.
15910 if (Expr::hasAnyTypeDependentArguments(Args)) {
15911
15912 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15913 // CHECKME: no 'operator' keyword?
15914 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15915 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15916 ExprResult Fn = CreateUnresolvedLookupExpr(
15917 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15918 if (Fn.isInvalid())
15919 return ExprError();
15920 // Can't add any actual overloads yet
15921
15922 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15923 Context.DependentTy, VK_PRValue, RLoc,
15924 CurFPFeatureOverrides());
15925 }
15926
15927 // Handle placeholders
15928 UnbridgedCastsSet UnbridgedCasts;
15929 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15930 return ExprError();
15931 }
15932 // Build an empty overload set.
15933 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15934
15935 // Subscript can only be overloaded as a member function.
15936
15937 // Add operator candidates that are member functions.
15938 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15939
15940 // Add builtin operator candidates.
15941 if (Args.size() == 2)
15942 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15943
15944 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15945
15946 // Perform overload resolution.
15947 OverloadCandidateSet::iterator Best;
15948 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15949 case OR_Success: {
15950 // We found a built-in operator or an overloaded operator.
15951 FunctionDecl *FnDecl = Best->Function;
15952
15953 if (FnDecl) {
15954 // We matched an overloaded operator. Build a call to that
15955 // operator.
15956
15957 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15958
15959 // Convert the arguments.
15960 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15961 SmallVector<Expr *, 2> MethodArgs;
15962
15963 // Initialize the object parameter.
15964 if (Method->isExplicitObjectMemberFunction()) {
15965 ExprResult Res =
15966 InitializeExplicitObjectArgument(*this, Args[0], Method);
15967 if (Res.isInvalid())
15968 return ExprError();
15969 Args[0] = Res.get();
15970 ArgExpr = Args;
15971 } else {
15972 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15973 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15974 if (Arg0.isInvalid())
15975 return ExprError();
15976
15977 MethodArgs.push_back(Arg0.get());
15978 }
15979
15980 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15981 *this, MethodArgs, Method, ArgExpr, LLoc);
15982 if (IsError)
15983 return ExprError();
15984
15985 // Build the actual expression node.
15986 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15987 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15988 ExprResult FnExpr = CreateFunctionRefExpr(
15989 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15990 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15991 if (FnExpr.isInvalid())
15992 return ExprError();
15993
15994 // Determine the result type
15995 QualType ResultTy = FnDecl->getReturnType();
15996 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15997 ResultTy = ResultTy.getNonLValueExprType(Context);
15998
15999 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16000 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16001 CurFPFeatureOverrides());
16002
16003 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16004 return ExprError();
16005
16006 if (CheckFunctionCall(Method, TheCall,
16007 Method->getType()->castAs<FunctionProtoType>()))
16008 return ExprError();
16009
16010 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
16011 FnDecl);
16012 } else {
16013 // We matched a built-in operator. Convert the arguments, then
16014 // break out so that we will build the appropriate built-in
16015 // operator node.
16016 ExprResult ArgsRes0 = PerformImplicitConversion(
16017 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16018 AssignmentAction::Passing,
16019 CheckedConversionKind::ForBuiltinOverloadedOp);
16020 if (ArgsRes0.isInvalid())
16021 return ExprError();
16022 Args[0] = ArgsRes0.get();
16023
16024 ExprResult ArgsRes1 = PerformImplicitConversion(
16025 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16026 AssignmentAction::Passing,
16027 CheckedConversionKind::ForBuiltinOverloadedOp);
16028 if (ArgsRes1.isInvalid())
16029 return ExprError();
16030 Args[1] = ArgsRes1.get();
16031
16032 break;
16033 }
16034 }
16035
16036 case OR_No_Viable_Function: {
16037 PartialDiagnostic PD =
16038 CandidateSet.empty()
16039 ? (PDiag(diag::err_ovl_no_oper)
16040 << Args[0]->getType() << /*subscript*/ 0
16041 << Args[0]->getSourceRange() << Range)
16042 : (PDiag(diag::err_ovl_no_viable_subscript)
16043 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16044 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16045 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16046 return ExprError();
16047 }
16048
16049 case OR_Ambiguous:
16050 if (Args.size() == 2) {
16051 CandidateSet.NoteCandidates(
16052 PartialDiagnosticAt(
16053 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16054 << "[]" << Args[0]->getType() << Args[1]->getType()
16055 << Args[0]->getSourceRange() << Range),
16056 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16057 } else {
16058 CandidateSet.NoteCandidates(
16059 PartialDiagnosticAt(LLoc,
16060 PDiag(diag::err_ovl_ambiguous_subscript_call)
16061 << Args[0]->getType()
16062 << Args[0]->getSourceRange() << Range),
16063 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16064 }
16065 return ExprError();
16066
16067 case OR_Deleted: {
16068 StringLiteral *Msg = Best->Function->getDeletedMessage();
16069 CandidateSet.NoteCandidates(
16070 PartialDiagnosticAt(LLoc,
16071 PDiag(diag::err_ovl_deleted_oper)
16072 << "[]" << (Msg != nullptr)
16073 << (Msg ? Msg->getString() : StringRef())
16074 << Args[0]->getSourceRange() << Range),
16075 *this, OCD_AllCandidates, Args, "[]", LLoc);
16076 return ExprError();
16077 }
16078 }
16079
16080 // We matched a built-in operator; build it.
16081 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16082 }
16083
16084 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16085 SourceLocation LParenLoc,
16086 MultiExprArg Args,
16087 SourceLocation RParenLoc,
16088 Expr *ExecConfig, bool IsExecConfig,
16089 bool AllowRecovery) {
16090 assert(MemExprE->getType() == Context.BoundMemberTy ||
16091 MemExprE->getType() == Context.OverloadTy);
16092
16093 // Dig out the member expression. This holds both the object
16094 // argument and the member function we're referring to.
16095 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16096
16097 // Determine whether this is a call to a pointer-to-member function.
16098 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16099 assert(op->getType() == Context.BoundMemberTy);
16100 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16101
16102 QualType fnType =
16103 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16104
16105 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16106 QualType resultType = proto->getCallResultType(Context);
16107 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
16108
16109 // Check that the object type isn't more qualified than the
16110 // member function we're calling.
16111 Qualifiers funcQuals = proto->getMethodQuals();
16112
16113 QualType objectType = op->getLHS()->getType();
16114 if (op->getOpcode() == BO_PtrMemI)
16115 objectType = objectType->castAs<PointerType>()->getPointeeType();
16116 Qualifiers objectQuals = objectType.getQualifiers();
16117
16118 Qualifiers difference = objectQuals - funcQuals;
16119 difference.removeObjCGCAttr();
16120 difference.removeAddressSpace();
16121 if (difference) {
16122 std::string qualsString = difference.getAsString();
16123 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16124 << fnType.getUnqualifiedType()
16125 << qualsString
16126 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16127 }
16128
16129 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16130 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16131 CurFPFeatureOverrides(), proto->getNumParams());
16132
16133 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16134 call, nullptr))
16135 return ExprError();
16136
16137 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16138 return ExprError();
16139
16140 if (CheckOtherCall(call, proto))
16141 return ExprError();
16142
16143 return MaybeBindToTemporary(call);
16144 }
16145
16146 // We only try to build a recovery expr at this level if we can preserve
16147 // the return type, otherwise we return ExprError() and let the caller
16148 // recover.
16149 auto BuildRecoveryExpr = [&](QualType Type) {
16150 if (!AllowRecovery)
16151 return ExprError();
16152 std::vector<Expr *> SubExprs = {MemExprE};
16153 llvm::append_range(SubExprs, Args);
16154 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16155 Type);
16156 };
16157 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16158 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16159 RParenLoc, CurFPFeatureOverrides());
16160
16161 UnbridgedCastsSet UnbridgedCasts;
16162 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16163 return ExprError();
16164
16165 MemberExpr *MemExpr;
16166 CXXMethodDecl *Method = nullptr;
16167 bool HadMultipleCandidates = false;
16168 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16169 NestedNameSpecifier Qualifier = std::nullopt;
16170 if (isa<MemberExpr>(NakedMemExpr)) {
16171 MemExpr = cast<MemberExpr>(NakedMemExpr);
16172 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
16173 FoundDecl = MemExpr->getFoundDecl();
16174 Qualifier = MemExpr->getQualifier();
16175 UnbridgedCasts.restore();
16176 } else {
16177 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16178 Qualifier = UnresExpr->getQualifier();
16179
16180 QualType ObjectType = UnresExpr->getBaseType();
16181 Expr::Classification ObjectClassification
16182 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16183 : UnresExpr->getBase()->Classify(Context);
16184
16185 // Add overload candidates
16186 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16187 OverloadCandidateSet::CSK_Normal);
16188
16189 // FIXME: avoid copy.
16190 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16191 if (UnresExpr->hasExplicitTemplateArgs()) {
16192 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16193 TemplateArgs = &TemplateArgsBuffer;
16194 }
16195
16196 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16197 E = UnresExpr->decls_end(); I != E; ++I) {
16198
16199 QualType ExplicitObjectType = ObjectType;
16200
16201 NamedDecl *Func = *I;
16202 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16203 if (isa<UsingShadowDecl>(Func))
16204 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16205
16206 bool HasExplicitParameter = false;
16207 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16208 M && M->hasCXXExplicitFunctionObjectParameter())
16209 HasExplicitParameter = true;
16210 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16211 M &&
16212 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16213 HasExplicitParameter = true;
16214
16215 if (HasExplicitParameter)
16216 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16217
16218 // Microsoft supports direct constructor calls.
16219 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16220 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
16221 CandidateSet,
16222 /*SuppressUserConversions*/ false);
16223 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16224 // If explicit template arguments were provided, we can't call a
16225 // non-template member function.
16226 if (TemplateArgs)
16227 continue;
16228
16229 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16230 ObjectClassification, Args, CandidateSet,
16231 /*SuppressUserConversions=*/false);
16232 } else {
16233 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
16234 I.getPair(), ActingDC, TemplateArgs,
16235 ExplicitObjectType, ObjectClassification,
16236 Args, CandidateSet,
16237 /*SuppressUserConversions=*/false);
16238 }
16239 }
16240
16241 HadMultipleCandidates = (CandidateSet.size() > 1);
16242
16243 DeclarationName DeclName = UnresExpr->getMemberName();
16244
16245 UnbridgedCasts.restore();
16246
16247 OverloadCandidateSet::iterator Best;
16248 bool Succeeded = false;
16249 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16250 Best)) {
16251 case OR_Success:
16252 Method = cast<CXXMethodDecl>(Best->Function);
16253 FoundDecl = Best->FoundDecl;
16254 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16255 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16256 break;
16257 // If FoundDecl is different from Method (such as if one is a template
16258 // and the other a specialization), make sure DiagnoseUseOfDecl is
16259 // called on both.
16260 // FIXME: This would be more comprehensively addressed by modifying
16261 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16262 // being used.
16263 if (Method != FoundDecl.getDecl() &&
16264 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
16265 break;
16266 Succeeded = true;
16267 break;
16268
16269 case OR_No_Viable_Function:
16270 CandidateSet.NoteCandidates(
16271 PartialDiagnosticAt(
16272 UnresExpr->getMemberLoc(),
16273 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16274 << DeclName << MemExprE->getSourceRange()),
16275 *this, OCD_AllCandidates, Args);
16276 break;
16277 case OR_Ambiguous:
16278 CandidateSet.NoteCandidates(
16279 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16280 PDiag(diag::err_ovl_ambiguous_member_call)
16281 << DeclName << MemExprE->getSourceRange()),
16282 *this, OCD_AmbiguousCandidates, Args);
16283 break;
16284 case OR_Deleted:
16285 DiagnoseUseOfDeletedFunction(
16286 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16287 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16288 break;
16289 }
16290 // Overload resolution fails, try to recover.
16291 if (!Succeeded)
16292 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16293
16294 ExprResult Res =
16295 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16296 if (Res.isInvalid())
16297 return ExprError();
16298 MemExprE = Res.get();
16299
16300 // If overload resolution picked a static member
16301 // build a non-member call based on that function.
16302 if (Method->isStatic()) {
16303 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16304 ExecConfig, IsExecConfig);
16305 }
16306
16307 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16308 }
16309
16310 QualType ResultType = Method->getReturnType();
16311 ExprValueKind VK = Expr::getValueKindForType(ResultType);
16312 ResultType = ResultType.getNonLValueExprType(Context);
16313
16314 assert(Method && "Member call to something that isn't a method?");
16315 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16316
16317 CallExpr *TheCall = nullptr;
16318 llvm::SmallVector<Expr *, 8> NewArgs;
16319 if (Method->isExplicitObjectMemberFunction()) {
16320 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16321 NewArgs))
16322 return ExprError();
16323
16324 // Build the actual expression node.
16325 ExprResult FnExpr =
16326 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16327 HadMultipleCandidates, MemExpr->getExprLoc());
16328 if (FnExpr.isInvalid())
16329 return ExprError();
16330
16331 TheCall =
16332 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16333 CurFPFeatureOverrides(), Proto->getNumParams());
16334 TheCall->setUsesMemberSyntax(true);
16335 } else {
16336 // Convert the object argument (for a non-static member function call).
16337 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16338 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16339 if (ObjectArg.isInvalid())
16340 return ExprError();
16341 MemExpr->setBase(ObjectArg.get());
16342 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16343 RParenLoc, CurFPFeatureOverrides(),
16344 Proto->getNumParams());
16345 }
16346
16347 // Check for a valid return type.
16348 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16349 TheCall, Method))
16350 return BuildRecoveryExpr(ResultType);
16351
16352 // Convert the rest of the arguments
16353 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16354 RParenLoc))
16355 return BuildRecoveryExpr(ResultType);
16356
16357 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16358
16359 if (CheckFunctionCall(Method, TheCall, Proto))
16360 return ExprError();
16361
16362 // In the case the method to call was not selected by the overloading
16363 // resolution process, we still need to handle the enable_if attribute. Do
16364 // that here, so it will not hide previous -- and more relevant -- errors.
16365 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16366 if (const EnableIfAttr *Attr =
16367 CheckEnableIf(Method, LParenLoc, Args, true)) {
16368 Diag(MemE->getMemberLoc(),
16369 diag::err_ovl_no_viable_member_function_in_call)
16370 << Method << Method->getSourceRange();
16371 Diag(Method->getLocation(),
16372 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16373 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16374 return ExprError();
16375 }
16376 }
16377
16378 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
16379 TheCall->getDirectCallee()->isPureVirtual()) {
16380 const FunctionDecl *MD = TheCall->getDirectCallee();
16381
16382 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16383 MemExpr->performsVirtualDispatch(getLangOpts())) {
16384 Diag(MemExpr->getBeginLoc(),
16385 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16386 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
16387 << MD->getParent();
16388
16389 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16390 if (getLangOpts().AppleKext)
16391 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16392 << MD->getParent() << MD->getDeclName();
16393 }
16394 }
16395
16396 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16397 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16398 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16399 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16400 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16401 MemExpr->getMemberLoc());
16402 }
16403
16404 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
16405 TheCall->getDirectCallee());
16406 }
16407
16408 ExprResult
16409 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16410 SourceLocation LParenLoc,
16411 MultiExprArg Args,
16412 SourceLocation RParenLoc) {
16413 if (checkPlaceholderForOverload(*this, Obj))
16414 return ExprError();
16415 ExprResult Object = Obj;
16416
16417 UnbridgedCastsSet UnbridgedCasts;
16418 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16419 return ExprError();
16420
16421 assert(Object.get()->getType()->isRecordType() &&
16422 "Requires object type argument");
16423
16424 // C++ [over.call.object]p1:
16425 // If the primary-expression E in the function call syntax
16426 // evaluates to a class object of type "cv T", then the set of
16427 // candidate functions includes at least the function call
16428 // operators of T. The function call operators of T are obtained by
16429 // ordinary lookup of the name operator() in the context of
16430 // (E).operator().
16431 OverloadCandidateSet CandidateSet(LParenLoc,
16432 OverloadCandidateSet::CSK_Operator);
16433 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16434
16435 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16436 diag::err_incomplete_object_call, Object.get()))
16437 return true;
16438
16439 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16440 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16441 LookupQualifiedName(R, Record);
16442 R.suppressAccessDiagnostics();
16443
16444 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16445 Oper != OperEnd; ++Oper) {
16446 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16447 Object.get()->Classify(Context), Args, CandidateSet,
16448 /*SuppressUserConversion=*/false);
16449 }
16450
16451 // When calling a lambda, both the call operator, and
16452 // the conversion operator to function pointer
16453 // are considered. But when constraint checking
16454 // on the call operator fails, it will also fail on the
16455 // conversion operator as the constraints are always the same.
16456 // As the user probably does not intend to perform a surrogate call,
16457 // we filter them out to produce better error diagnostics, ie to avoid
16458 // showing 2 failed overloads instead of one.
16459 bool IgnoreSurrogateFunctions = false;
16460 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16461 const OverloadCandidate &Candidate = *CandidateSet.begin();
16462 if (!Candidate.Viable &&
16463 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16464 IgnoreSurrogateFunctions = true;
16465 }
16466
16467 // C++ [over.call.object]p2:
16468 // In addition, for each (non-explicit in C++0x) conversion function
16469 // declared in T of the form
16470 //
16471 // operator conversion-type-id () cv-qualifier;
16472 //
16473 // where cv-qualifier is the same cv-qualification as, or a
16474 // greater cv-qualification than, cv, and where conversion-type-id
16475 // denotes the type "pointer to function of (P1,...,Pn) returning
16476 // R", or the type "reference to pointer to function of
16477 // (P1,...,Pn) returning R", or the type "reference to function
16478 // of (P1,...,Pn) returning R", a surrogate call function [...]
16479 // is also considered as a candidate function. Similarly,
16480 // surrogate call functions are added to the set of candidate
16481 // functions for each conversion function declared in an
16482 // accessible base class provided the function is not hidden
16483 // within T by another intervening declaration.
16484 const auto &Conversions = Record->getVisibleConversionFunctions();
16485 for (auto I = Conversions.begin(), E = Conversions.end();
16486 !IgnoreSurrogateFunctions && I != E; ++I) {
16487 NamedDecl *D = *I;
16488 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16489 if (isa<UsingShadowDecl>(D))
16490 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16491
16492 // Skip over templated conversion functions; they aren't
16493 // surrogates.
16494 if (isa<FunctionTemplateDecl>(D))
16495 continue;
16496
16497 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
16498 if (!Conv->isExplicit()) {
16499 // Strip the reference type (if any) and then the pointer type (if
16500 // any) to get down to what might be a function type.
16501 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16502 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16503 ConvType = ConvPtrType->getPointeeType();
16504
16505 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16506 {
16507 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16508 Object.get(), Args, CandidateSet);
16509 }
16510 }
16511 }
16512
16513 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16514
16515 // Perform overload resolution.
16516 OverloadCandidateSet::iterator Best;
16517 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16518 Best)) {
16519 case OR_Success:
16520 // Overload resolution succeeded; we'll build the appropriate call
16521 // below.
16522 break;
16523
16524 case OR_No_Viable_Function: {
16525 PartialDiagnostic PD =
16526 CandidateSet.empty()
16527 ? (PDiag(diag::err_ovl_no_oper)
16528 << Object.get()->getType() << /*call*/ 1
16529 << Object.get()->getSourceRange())
16530 : (PDiag(diag::err_ovl_no_viable_object_call)
16531 << Object.get()->getType() << Object.get()->getSourceRange());
16532 CandidateSet.NoteCandidates(
16533 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16534 OCD_AllCandidates, Args);
16535 break;
16536 }
16537 case OR_Ambiguous:
16538 if (!R.isAmbiguous())
16539 CandidateSet.NoteCandidates(
16540 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16541 PDiag(diag::err_ovl_ambiguous_object_call)
16542 << Object.get()->getType()
16543 << Object.get()->getSourceRange()),
16544 *this, OCD_AmbiguousCandidates, Args);
16545 break;
16546
16547 case OR_Deleted: {
16548 // FIXME: Is this diagnostic here really necessary? It seems that
16549 // 1. we don't have any tests for this diagnostic, and
16550 // 2. we already issue err_deleted_function_use for this later on anyway.
16551 StringLiteral *Msg = Best->Function->getDeletedMessage();
16552 CandidateSet.NoteCandidates(
16553 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16554 PDiag(diag::err_ovl_deleted_object_call)
16555 << Object.get()->getType() << (Msg != nullptr)
16556 << (Msg ? Msg->getString() : StringRef())
16557 << Object.get()->getSourceRange()),
16558 *this, OCD_AllCandidates, Args);
16559 break;
16560 }
16561 }
16562
16563 if (Best == CandidateSet.end())
16564 return true;
16565
16566 UnbridgedCasts.restore();
16567
16568 if (Best->Function == nullptr) {
16569 // Since there is no function declaration, this is one of the
16570 // surrogate candidates. Dig out the conversion function.
16571 CXXConversionDecl *Conv
16572 = cast<CXXConversionDecl>(
16573 Best->Conversions[0].UserDefined.ConversionFunction);
16574
16575 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16576 Best->FoundDecl);
16577 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16578 return ExprError();
16579 assert(Conv == Best->FoundDecl.getDecl() &&
16580 "Found Decl & conversion-to-functionptr should be same, right?!");
16581 // We selected one of the surrogate functions that converts the
16582 // object parameter to a function pointer. Perform the conversion
16583 // on the object argument, then let BuildCallExpr finish the job.
16584
16585 // Create an implicit member expr to refer to the conversion operator.
16586 // and then call it.
16587 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16588 Conv, HadMultipleCandidates);
16589 if (Call.isInvalid())
16590 return ExprError();
16591 // Record usage of conversion in an implicit cast.
16592 Call = ImplicitCastExpr::Create(
16593 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16594 nullptr, VK_PRValue, CurFPFeatureOverrides());
16595
16596 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16597 }
16598
16599 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16600
16601 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16602 // that calls this method, using Object for the implicit object
16603 // parameter and passing along the remaining arguments.
16604 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16605
16606 // An error diagnostic has already been printed when parsing the declaration.
16607 if (Method->isInvalidDecl())
16608 return ExprError();
16609
16610 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16611 unsigned NumParams = Proto->getNumParams();
16612
16613 DeclarationNameInfo OpLocInfo(
16614 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16615 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16616 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16617 Obj, HadMultipleCandidates,
16618 OpLocInfo.getLoc(),
16619 OpLocInfo.getInfo());
16620 if (NewFn.isInvalid())
16621 return true;
16622
16623 SmallVector<Expr *, 8> MethodArgs;
16624 MethodArgs.reserve(NumParams + 1);
16625
16626 bool IsError = false;
16627
16628 // Initialize the object parameter.
16629 llvm::SmallVector<Expr *, 8> NewArgs;
16630 if (Method->isExplicitObjectMemberFunction()) {
16631 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16632 } else {
16633 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16634 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16635 if (ObjRes.isInvalid())
16636 IsError = true;
16637 else
16638 Object = ObjRes;
16639 MethodArgs.push_back(Object.get());
16640 }
16641
16642 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16643 *this, MethodArgs, Method, Args, LParenLoc);
16644
16645 // If this is a variadic call, handle args passed through "...".
16646 if (Proto->isVariadic()) {
16647 // Promote the arguments (C99 6.5.2.2p7).
16648 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16649 ExprResult Arg = DefaultVariadicArgumentPromotion(
16650 Args[i], VariadicCallType::Method, nullptr);
16651 IsError |= Arg.isInvalid();
16652 MethodArgs.push_back(Arg.get());
16653 }
16654 }
16655
16656 if (IsError)
16657 return true;
16658
16659 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16660
16661 // Once we've built TheCall, all of the expressions are properly owned.
16662 QualType ResultTy = Method->getReturnType();
16663 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16664 ResultTy = ResultTy.getNonLValueExprType(Context);
16665
16666 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16667 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16668 CurFPFeatureOverrides());
16669
16670 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16671 return true;
16672
16673 if (CheckFunctionCall(Method, TheCall, Proto))
16674 return true;
16675
16676 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16677 }
16678
16679 ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16680 SourceLocation OpLoc,
16681 bool *NoArrowOperatorFound) {
16682 assert(Base->getType()->isRecordType() &&
16683 "left-hand side must have class type");
16684
16685 if (checkPlaceholderForOverload(*this, Base))
16686 return ExprError();
16687
16688 SourceLocation Loc = Base->getExprLoc();
16689
16690 // C++ [over.ref]p1:
16691 //
16692 // [...] An expression x->m is interpreted as (x.operator->())->m
16693 // for a class object x of type T if T::operator->() exists and if
16694 // the operator is selected as the best match function by the
16695 // overload resolution mechanism (13.3).
16696 DeclarationName OpName =
16697 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16698 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16699
16700 if (RequireCompleteType(Loc, Base->getType(),
16701 diag::err_typecheck_incomplete_tag, Base))
16702 return ExprError();
16703
16704 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16705 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16706 R.suppressAccessDiagnostics();
16707
16708 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16709 Oper != OperEnd; ++Oper) {
16710 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16711 {}, CandidateSet,
16712 /*SuppressUserConversion=*/false);
16713 }
16714
16715 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16716
16717 // Perform overload resolution.
16718 OverloadCandidateSet::iterator Best;
16719 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16720 case OR_Success:
16721 // Overload resolution succeeded; we'll build the call below.
16722 break;
16723
16724 case OR_No_Viable_Function: {
16725 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16726 if (CandidateSet.empty()) {
16727 QualType BaseType = Base->getType();
16728 if (NoArrowOperatorFound) {
16729 // Report this specific error to the caller instead of emitting a
16730 // diagnostic, as requested.
16731 *NoArrowOperatorFound = true;
16732 return ExprError();
16733 }
16734 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16735 << BaseType << Base->getSourceRange();
16736 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16737 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16738 << FixItHint::CreateReplacement(OpLoc, ".");
16739 }
16740 } else
16741 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16742 << "operator->" << Base->getSourceRange();
16743 CandidateSet.NoteCandidates(*this, Base, Cands);
16744 return ExprError();
16745 }
16746 case OR_Ambiguous:
16747 if (!R.isAmbiguous())
16748 CandidateSet.NoteCandidates(
16749 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16750 << "->" << Base->getType()
16751 << Base->getSourceRange()),
16752 *this, OCD_AmbiguousCandidates, Base);
16753 return ExprError();
16754
16755 case OR_Deleted: {
16756 StringLiteral *Msg = Best->Function->getDeletedMessage();
16757 CandidateSet.NoteCandidates(
16758 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16759 << "->" << (Msg != nullptr)
16760 << (Msg ? Msg->getString() : StringRef())
16761 << Base->getSourceRange()),
16762 *this, OCD_AllCandidates, Base);
16763 return ExprError();
16764 }
16765 }
16766
16767 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16768
16769 // Convert the object parameter.
16770 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16771
16772 if (Method->isExplicitObjectMemberFunction()) {
16773 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16774 if (R.isInvalid())
16775 return ExprError();
16776 Base = R.get();
16777 } else {
16778 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16779 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16780 if (BaseResult.isInvalid())
16781 return ExprError();
16782 Base = BaseResult.get();
16783 }
16784
16785 // Build the operator call.
16786 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16787 Base, HadMultipleCandidates, OpLoc);
16788 if (FnExpr.isInvalid())
16789 return ExprError();
16790
16791 QualType ResultTy = Method->getReturnType();
16792 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16793 ResultTy = ResultTy.getNonLValueExprType(Context);
16794
16795 CallExpr *TheCall =
16796 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16797 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16798
16799 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16800 return ExprError();
16801
16802 if (CheckFunctionCall(Method, TheCall,
16803 Method->getType()->castAs<FunctionProtoType>()))
16804 return ExprError();
16805
16806 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16807 }
16808
16809 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16810 DeclarationNameInfo &SuffixInfo,
16811 ArrayRef<Expr*> Args,
16812 SourceLocation LitEndLoc,
16813 TemplateArgumentListInfo *TemplateArgs) {
16814 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16815
16816 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16817 OverloadCandidateSet::CSK_Normal);
16818 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16819 TemplateArgs);
16820
16821 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16822
16823 // Perform overload resolution. This will usually be trivial, but might need
16824 // to perform substitutions for a literal operator template.
16825 OverloadCandidateSet::iterator Best;
16826 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16827 case OR_Success:
16828 case OR_Deleted:
16829 break;
16830
16831 case OR_No_Viable_Function:
16832 CandidateSet.NoteCandidates(
16833 PartialDiagnosticAt(UDSuffixLoc,
16834 PDiag(diag::err_ovl_no_viable_function_in_call)
16835 << R.getLookupName()),
16836 *this, OCD_AllCandidates, Args);
16837 return ExprError();
16838
16839 case OR_Ambiguous:
16840 CandidateSet.NoteCandidates(
16841 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16842 << R.getLookupName()),
16843 *this, OCD_AmbiguousCandidates, Args);
16844 return ExprError();
16845 }
16846
16847 FunctionDecl *FD = Best->Function;
16848 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16849 nullptr, HadMultipleCandidates,
16850 SuffixInfo.getLoc(),
16851 SuffixInfo.getInfo());
16852 if (Fn.isInvalid())
16853 return true;
16854
16855 // Check the argument types. This should almost always be a no-op, except
16856 // that array-to-pointer decay is applied to string literals.
16857 Expr *ConvArgs[2];
16858 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16859 ExprResult InputInit = PerformCopyInitialization(
16860 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
16861 SourceLocation(), Args[ArgIdx]);
16862 if (InputInit.isInvalid())
16863 return true;
16864 ConvArgs[ArgIdx] = InputInit.get();
16865 }
16866
16867 QualType ResultTy = FD->getReturnType();
16868 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16869 ResultTy = ResultTy.getNonLValueExprType(Context);
16870
16871 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16872 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16873 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16874
16875 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16876 return ExprError();
16877
16878 if (CheckFunctionCall(FD, UDL, nullptr))
16879 return ExprError();
16880
16881 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16882 }
16883
16884 Sema::ForRangeStatus
16885 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16886 SourceLocation RangeLoc,
16887 const DeclarationNameInfo &NameInfo,
16888 LookupResult &MemberLookup,
16889 OverloadCandidateSet *CandidateSet,
16890 Expr *Range, ExprResult *CallExpr) {
16891 Scope *S = nullptr;
16892
16893 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
16894 if (!MemberLookup.empty()) {
16895 ExprResult MemberRef =
16896 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16897 /*IsPtr=*/false, CXXScopeSpec(),
16898 /*TemplateKWLoc=*/SourceLocation(),
16899 /*FirstQualifierInScope=*/nullptr,
16900 MemberLookup,
16901 /*TemplateArgs=*/nullptr, S);
16902 if (MemberRef.isInvalid()) {
16903 *CallExpr = ExprError();
16904 return FRS_DiagnosticIssued;
16905 }
16906 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16907 if (CallExpr->isInvalid()) {
16908 *CallExpr = ExprError();
16909 return FRS_DiagnosticIssued;
16910 }
16911 } else {
16912 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16913 NestedNameSpecifierLoc(),
16914 NameInfo, UnresolvedSet<0>());
16915 if (FnR.isInvalid())
16916 return FRS_DiagnosticIssued;
16917 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16918
16919 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16920 CandidateSet, CallExpr);
16921 if (CandidateSet->empty() || CandidateSetError) {
16922 *CallExpr = ExprError();
16923 return FRS_NoViableFunction;
16924 }
16925 OverloadCandidateSet::iterator Best;
16926 OverloadingResult OverloadResult =
16927 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16928
16929 if (OverloadResult == OR_No_Viable_Function) {
16930 *CallExpr = ExprError();
16931 return FRS_NoViableFunction;
16932 }
16933 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16934 Loc, nullptr, CandidateSet, &Best,
16935 OverloadResult,
16936 /*AllowTypoCorrection=*/false);
16937 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16938 *CallExpr = ExprError();
16939 return FRS_DiagnosticIssued;
16940 }
16941 }
16942 return FRS_Success;
16943 }
16944
16945 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16946 FunctionDecl *Fn) {
16947 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16948 ExprResult SubExpr =
16949 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16950 if (SubExpr.isInvalid())
16951 return ExprError();
16952 if (SubExpr.get() == PE->getSubExpr())
16953 return PE;
16954
16955 return new (Context)
16956 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16957 }
16958
16959 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16960 ExprResult SubExpr =
16961 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16962 if (SubExpr.isInvalid())
16963 return ExprError();
16964 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16965 SubExpr.get()->getType()) &&
16966 "Implicit cast type cannot be determined from overload");
16967 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16968 if (SubExpr.get() == ICE->getSubExpr())
16969 return ICE;
16970
16971 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16972 SubExpr.get(), nullptr, ICE->getValueKind(),
16973 CurFPFeatureOverrides());
16974 }
16975
16976 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16977 if (!GSE->isResultDependent()) {
16978 ExprResult SubExpr =
16979 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16980 if (SubExpr.isInvalid())
16981 return ExprError();
16982 if (SubExpr.get() == GSE->getResultExpr())
16983 return GSE;
16984
16985 // Replace the resulting type information before rebuilding the generic
16986 // selection expression.
16987 ArrayRef<Expr *> A = GSE->getAssocExprs();
16988 SmallVector<Expr *, 4> AssocExprs(A);
16989 unsigned ResultIdx = GSE->getResultIndex();
16990 AssocExprs[ResultIdx] = SubExpr.get();
16991
16992 if (GSE->isExprPredicate())
16993 return GenericSelectionExpr::Create(
16994 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16995 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16996 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16997 ResultIdx);
16998 return GenericSelectionExpr::Create(
16999 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17000 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17001 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17002 ResultIdx);
17003 }
17004 // Rather than fall through to the unreachable, return the original generic
17005 // selection expression.
17006 return GSE;
17007 }
17008
17009 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17010 assert(UnOp->getOpcode() == UO_AddrOf &&
17011 "Can only take the address of an overloaded function");
17012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17013 if (!Method->isImplicitObjectMemberFunction()) {
17014 // Do nothing: the address of static and
17015 // explicit object member functions is a (non-member) function pointer.
17016 } else {
17017 // Fix the subexpression, which really has to be an
17018 // UnresolvedLookupExpr holding an overloaded member function
17019 // or template.
17020 ExprResult SubExpr =
17021 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17022 if (SubExpr.isInvalid())
17023 return ExprError();
17024 if (SubExpr.get() == UnOp->getSubExpr())
17025 return UnOp;
17026
17027 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17028 SubExpr.get(), Method))
17029 return ExprError();
17030
17031 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17032 "fixed to something other than a decl ref");
17033 NestedNameSpecifier Qualifier =
17034 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17035 assert(Qualifier &&
17036 "fixed to a member ref with no nested name qualifier");
17037
17038 // We have taken the address of a pointer to member
17039 // function. Perform the computation here so that we get the
17040 // appropriate pointer to member type.
17041 QualType MemPtrType = Context.getMemberPointerType(
17042 Fn->getType(), Qualifier,
17043 cast<CXXRecordDecl>(Method->getDeclContext()));
17044 // Under the MS ABI, lock down the inheritance model now.
17045 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17046 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17047
17048 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17049 MemPtrType, VK_PRValue, OK_Ordinary,
17050 UnOp->getOperatorLoc(), false,
17051 CurFPFeatureOverrides());
17052 }
17053 }
17054 ExprResult SubExpr =
17055 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17056 if (SubExpr.isInvalid())
17057 return ExprError();
17058 if (SubExpr.get() == UnOp->getSubExpr())
17059 return UnOp;
17060
17061 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17062 SubExpr.get());
17063 }
17064
17065 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17066 if (Found.getAccess() == AS_none) {
17067 CheckUnresolvedLookupAccess(ULE, Found);
17068 }
17069 // FIXME: avoid copy.
17070 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17071 if (ULE->hasExplicitTemplateArgs()) {
17072 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17073 TemplateArgs = &TemplateArgsBuffer;
17074 }
17075
17076 QualType Type = Fn->getType();
17077 ExprValueKind ValueKind =
17078 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17079 ? VK_LValue
17080 : VK_PRValue;
17081
17082 // FIXME: Duplicated from BuildDeclarationNameExpr.
17083 if (unsigned BID = Fn->getBuiltinID()) {
17084 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17085 Type = Context.BuiltinFnTy;
17086 ValueKind = VK_PRValue;
17087 }
17088 }
17089
17090 DeclRefExpr *DRE = BuildDeclRefExpr(
17091 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17092 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17093 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17094 return DRE;
17095 }
17096
17097 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17098 // FIXME: avoid copy.
17099 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17100 if (MemExpr->hasExplicitTemplateArgs()) {
17101 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17102 TemplateArgs = &TemplateArgsBuffer;
17103 }
17104
17105 Expr *Base;
17106
17107 // If we're filling in a static method where we used to have an
17108 // implicit member access, rewrite to a simple decl ref.
17109 if (MemExpr->isImplicitAccess()) {
17110 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17111 DeclRefExpr *DRE = BuildDeclRefExpr(
17112 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17113 MemExpr->getQualifierLoc(), Found.getDecl(),
17114 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17115 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17116 return DRE;
17117 } else {
17118 SourceLocation Loc = MemExpr->getMemberLoc();
17119 if (MemExpr->getQualifier())
17120 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17121 Base =
17122 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17123 }
17124 } else
17125 Base = MemExpr->getBase();
17126
17127 ExprValueKind valueKind;
17128 QualType type;
17129 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17130 valueKind = VK_LValue;
17131 type = Fn->getType();
17132 } else {
17133 valueKind = VK_PRValue;
17134 type = Context.BoundMemberTy;
17135 }
17136
17137 return BuildMemberExpr(
17138 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17139 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17140 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17141 type, valueKind, OK_Ordinary, TemplateArgs);
17142 }
17143
17144 llvm_unreachable("Invalid reference to overloaded function");
17145 }
17146
17147 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17148 DeclAccessPair Found,
17149 FunctionDecl *Fn) {
17150 return FixOverloadedFunctionReference(E.get(), Found, Fn);
17151 }
17152
17153 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17154 FunctionDecl *Function) {
17155 if (!PartialOverloading || !Function)
17156 return true;
17157 if (Function->isVariadic())
17158 return false;
17159 if (const auto *Proto =
17160 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17161 if (Proto->isTemplateVariadic())
17162 return false;
17163 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17164 if (const auto *Proto =
17165 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17166 if (Proto->isTemplateVariadic())
17167 return false;
17168 return true;
17169 }
17170
17171 void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17172 DeclarationName Name,
17173 OverloadCandidateSet &CandidateSet,
17174 FunctionDecl *Fn, MultiExprArg Args,
17175 bool IsMember) {
17176 StringLiteral *Msg = Fn->getDeletedMessage();
17177 CandidateSet.NoteCandidates(
17178 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17179 << IsMember << Name << (Msg != nullptr)
17180 << (Msg ? Msg->getString() : StringRef())
17181 << Range),
17182 *this, OCD_AllCandidates, Args);
17183 }