clang 20.0.0git
SemaOverload.cpp
Go to the documentation of this file.
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"
15#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/Type.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/Support/Casting.h"
49#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdlib>
53#include <optional>
54
55using namespace clang;
56using namespace sema;
57
59
61 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
62 return P->hasAttr<PassObjectSizeAttr>();
63 });
64}
65
66/// A convenience routine for creating a decayed reference to a function.
68 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
69 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
70 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
71 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
72 return ExprError();
73 // If FoundDecl is different from Fn (such as if one is a template
74 // and the other a specialization), make sure DiagnoseUseOfDecl is
75 // called on both.
76 // FIXME: This would be more comprehensively addressed by modifying
77 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
78 // being used.
79 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
80 return ExprError();
81 DeclRefExpr *DRE = new (S.Context)
82 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
83 if (HadMultipleCandidates)
84 DRE->setHadMultipleCandidates(true);
85
87 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
88 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
90 DRE->setType(Fn->getType());
91 }
92 }
93 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
94 CK_FunctionToPointerDecay);
95}
96
97static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
98 bool InOverloadResolution,
100 bool CStyle,
101 bool AllowObjCWritebackConversion);
102
104 QualType &ToType,
105 bool InOverloadResolution,
107 bool CStyle);
109IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
111 OverloadCandidateSet& Conversions,
112 AllowedExplicit AllowExplicit,
113 bool AllowObjCConversionOnExplicit);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
127 const StandardConversionSequence& SCS1,
128 const StandardConversionSequence& SCS2);
129
130/// GetConversionRank - Retrieve the implicit conversion rank
131/// corresponding to the given implicit conversion kind.
133 static const ImplicitConversionRank Rank[] = {
160 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
161 // it was omitted by the patch that added
162 // ICK_Zero_Event_Conversion
163 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Queue_Conversion
172 };
173 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
174 return Rank[(int)Kind];
175}
176
179 ImplicitConversionKind Dimension) {
181 if (Rank == ICR_HLSL_Scalar_Widening) {
182 if (Base == ICR_Promotion)
184 if (Base == ICR_Conversion)
186 }
187 if (Rank == ICR_HLSL_Dimension_Reduction) {
188 if (Base == ICR_Promotion)
190 if (Base == ICR_Conversion)
192 }
193 return Rank;
194}
195
196/// GetImplicitConversionName - Return the name of this kind of
197/// implicit conversion.
199 static const char *const Name[] = {
200 "No conversion",
201 "Lvalue-to-rvalue",
202 "Array-to-pointer",
203 "Function-to-pointer",
204 "Function pointer conversion",
205 "Qualification",
206 "Integral promotion",
207 "Floating point promotion",
208 "Complex promotion",
209 "Integral conversion",
210 "Floating conversion",
211 "Complex conversion",
212 "Floating-integral conversion",
213 "Pointer conversion",
214 "Pointer-to-member conversion",
215 "Boolean conversion",
216 "Compatible-types conversion",
217 "Derived-to-base conversion",
218 "Vector conversion",
219 "SVE Vector conversion",
220 "RVV Vector conversion",
221 "Vector splat",
222 "Complex-real conversion",
223 "Block Pointer conversion",
224 "Transparent Union Conversion",
225 "Writeback conversion",
226 "OpenCL Zero Event Conversion",
227 "OpenCL Zero Queue Conversion",
228 "C specific type conversion",
229 "Incompatible pointer conversion",
230 "Fixed point conversion",
231 "HLSL vector truncation",
232 "Non-decaying array conversion",
233 "HLSL vector splat",
234 };
235 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
236 return Name[Kind];
237}
238
239/// StandardConversionSequence - Set the standard conversion
240/// sequence to the identity conversion.
248 ReferenceBinding = false;
249 DirectBinding = false;
250 IsLvalueReference = true;
251 BindsToFunctionLvalue = false;
252 BindsToRvalue = 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.
263 if (GetConversionRank(First) > Rank)
264 Rank = GetConversionRank(First);
265 if (GetConversionRank(Second) > Rank)
267 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
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).
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() ||
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).
298bool
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.
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.
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.
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 (auto *ET = ToType->getAs<EnumType>())
377 ToType = ET->getDecl()->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
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
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())
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 Result.convertToInteger(ConvertedValue,
420 llvm::APFloat::rmTowardZero, &ignored);
421 // If the resulting value is different, this was a narrowing conversion.
422 if (*IntConstantValue != ConvertedValue) {
423 ConstantValue = APValue(*IntConstantValue);
424 ConstantType = Initializer->getType();
426 }
427 } else {
428 // Variables are always narrowings.
430 }
431 }
432 return NK_Not_Narrowing;
433
434 // -- from long double to double or float, or from double to float, except
435 // where the source is a constant expression and the actual value after
436 // conversion is within the range of values that can be represented (even
437 // if it cannot be represented exactly), or
439 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
440 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
441 // FromType is larger than ToType.
442 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
443
444 // If it's value-dependent, we can't tell whether it's narrowing.
445 if (Initializer->isValueDependent())
447
449 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
450 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
451 // Constant!
452 if (Ctx.getLangOpts().C23)
453 ConstantValue = R.Val;
454 assert(ConstantValue.isFloat());
455 llvm::APFloat FloatVal = ConstantValue.getFloat();
456 // Convert the source value into the target type.
457 bool ignored;
458 llvm::APFloat Converted = FloatVal;
459 llvm::APFloat::opStatus ConvertStatus =
460 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
461 llvm::APFloat::rmNearestTiesToEven, &ignored);
462 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
463 llvm::APFloat::rmNearestTiesToEven, &ignored);
464 if (Ctx.getLangOpts().C23) {
465 if (FloatVal.isNaN() && Converted.isNaN() &&
466 !FloatVal.isSignaling() && !Converted.isSignaling()) {
467 // Quiet NaNs are considered the same value, regardless of
468 // payloads.
469 return NK_Not_Narrowing;
470 }
471 // For normal values, check exact equality.
472 if (!Converted.bitwiseIsEqual(FloatVal)) {
473 ConstantType = Initializer->getType();
475 }
476 } else {
477 // If there was no overflow, the source value is within the range of
478 // values that can be represented.
479 if (ConvertStatus & llvm::APFloat::opOverflow) {
480 ConstantType = Initializer->getType();
482 }
483 }
484 } else {
486 }
487 }
488 return NK_Not_Narrowing;
489
490 // -- from an integer type or unscoped enumeration type to an integer type
491 // that cannot represent all the values of the original type, except where
492 // (CWG2627) -- the source is a bit-field whose width w is less than that
493 // of its type (or, for an enumeration type, its underlying type) and the
494 // target type can represent all the values of a hypothetical extended
495 // integer type with width w and with the same signedness as the original
496 // type or
497 // -- the source is a constant expression and the actual value after
498 // conversion will fit into the target type and will produce the original
499 // value when converted back to the original type.
501 IntegralConversion: {
502 assert(FromType->isIntegralOrUnscopedEnumerationType());
503 assert(ToType->isIntegralOrUnscopedEnumerationType());
504 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
505 unsigned FromWidth = Ctx.getIntWidth(FromType);
506 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
507 const unsigned ToWidth = Ctx.getIntWidth(ToType);
508
509 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
510 bool ToSigned, unsigned ToWidth) {
511 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
512 (FromSigned <= ToSigned);
513 };
514
515 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
516 return NK_Not_Narrowing;
517
518 // Not all values of FromType can be represented in ToType.
519 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
520
521 bool DependentBitField = false;
522 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
523 if (BitField->getBitWidth()->isValueDependent())
524 DependentBitField = true;
525 else if (unsigned BitFieldWidth = BitField->getBitWidthValue(Ctx);
526 BitFieldWidth < FromWidth) {
527 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
528 return NK_Not_Narrowing;
529
530 // The initializer will be truncated to the bit-field width
531 FromWidth = BitFieldWidth;
532 }
533 }
534
535 // If it's value-dependent, we can't tell whether it's narrowing.
536 if (Initializer->isValueDependent())
538
539 std::optional<llvm::APSInt> OptInitializerValue =
540 Initializer->getIntegerConstantExpr(Ctx);
541 if (!OptInitializerValue) {
542 // If the bit-field width was dependent, it might end up being small
543 // enough to fit in the target type (unless the target type is unsigned
544 // and the source type is signed, in which case it will never fit)
545 if (DependentBitField && (FromSigned <= ToSigned))
547
548 // Otherwise, such a conversion is always narrowing
550 }
551 llvm::APSInt &InitializerValue = *OptInitializerValue;
552 bool Narrowing = false;
553 if (FromWidth < ToWidth) {
554 // Negative -> unsigned is narrowing. Otherwise, more bits is never
555 // narrowing.
556 if (InitializerValue.isSigned() && InitializerValue.isNegative())
557 Narrowing = true;
558 } else {
559 // Add a bit to the InitializerValue so we don't have to worry about
560 // signed vs. unsigned comparisons.
561 InitializerValue =
562 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
563 // Convert the initializer to and from the target width and signed-ness.
564 llvm::APSInt ConvertedValue = InitializerValue;
565 ConvertedValue = ConvertedValue.trunc(ToWidth);
566 ConvertedValue.setIsSigned(ToSigned);
567 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
568 ConvertedValue.setIsSigned(InitializerValue.isSigned());
569 // If the result is different, this was a narrowing conversion.
570 if (ConvertedValue != InitializerValue)
571 Narrowing = true;
572 }
573 if (Narrowing) {
574 ConstantType = Initializer->getType();
575 ConstantValue = APValue(InitializerValue);
577 }
578
579 return NK_Not_Narrowing;
580 }
581 case ICK_Complex_Real:
582 if (FromType->isComplexType() && !ToType->isComplexType())
583 return NK_Type_Narrowing;
584 return NK_Not_Narrowing;
585
587 if (Ctx.getLangOpts().C23) {
588 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
590 if (Initializer->EvaluateAsRValue(R, Ctx)) {
591 ConstantValue = R.Val;
592 assert(ConstantValue.isFloat());
593 llvm::APFloat FloatVal = ConstantValue.getFloat();
594 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
595 // value, the unqualified versions of the type of the initializer and
596 // the corresponding real type of the object declared shall be
597 // compatible.
598 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
599 ConstantType = Initializer->getType();
601 }
602 }
603 }
604 return NK_Not_Narrowing;
605 default:
606 // Other kinds of conversions are not narrowings.
607 return NK_Not_Narrowing;
608 }
609}
610
611/// dump - Print this standard conversion sequence to standard
612/// error. Useful for debugging overloading issues.
613LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
614 raw_ostream &OS = llvm::errs();
615 bool PrintedSomething = false;
616 if (First != ICK_Identity) {
618 PrintedSomething = true;
619 }
620
621 if (Second != ICK_Identity) {
622 if (PrintedSomething) {
623 OS << " -> ";
624 }
626
627 if (CopyConstructor) {
628 OS << " (by copy constructor)";
629 } else if (DirectBinding) {
630 OS << " (direct reference binding)";
631 } else if (ReferenceBinding) {
632 OS << " (reference binding)";
633 }
634 PrintedSomething = true;
635 }
636
637 if (Third != ICK_Identity) {
638 if (PrintedSomething) {
639 OS << " -> ";
640 }
642 PrintedSomething = true;
643 }
644
645 if (!PrintedSomething) {
646 OS << "No conversions required";
647 }
648}
649
650/// dump - Print this user-defined conversion sequence to standard
651/// error. Useful for debugging overloading issues.
653 raw_ostream &OS = llvm::errs();
654 if (Before.First || Before.Second || Before.Third) {
655 Before.dump();
656 OS << " -> ";
657 }
659 OS << '\'' << *ConversionFunction << '\'';
660 else
661 OS << "aggregate initialization";
662 if (After.First || After.Second || After.Third) {
663 OS << " -> ";
664 After.dump();
665 }
666}
667
668/// dump - Print this implicit conversion sequence to standard
669/// error. Useful for debugging overloading issues.
671 raw_ostream &OS = llvm::errs();
673 OS << "Worst list element conversion: ";
674 switch (ConversionKind) {
676 OS << "Standard conversion: ";
677 Standard.dump();
678 break;
680 OS << "User-defined conversion: ";
682 break;
684 OS << "Ellipsis conversion";
685 break;
687 OS << "Ambiguous conversion";
688 break;
689 case BadConversion:
690 OS << "Bad conversion";
691 break;
692 }
693
694 OS << "\n";
695}
696
698 new (&conversions()) ConversionSet();
699}
700
702 conversions().~ConversionSet();
703}
704
705void
710}
711
712namespace {
713 // Structure used by DeductionFailureInfo to store
714 // template argument information.
715 struct DFIArguments {
716 TemplateArgument FirstArg;
717 TemplateArgument SecondArg;
718 };
719 // Structure used by DeductionFailureInfo to store
720 // template parameter and template argument information.
721 struct DFIParamWithArguments : DFIArguments {
722 TemplateParameter Param;
723 };
724 // Structure used by DeductionFailureInfo to store template argument
725 // information and the index of the problematic call argument.
726 struct DFIDeducedMismatchArgs : DFIArguments {
727 TemplateArgumentList *TemplateArgs;
728 unsigned CallArgIndex;
729 };
730 // Structure used by DeductionFailureInfo to store information about
731 // unsatisfied constraints.
732 struct CNSInfo {
733 TemplateArgumentList *TemplateArgs;
734 ConstraintSatisfaction Satisfaction;
735 };
736}
737
738/// Convert from Sema's representation of template deduction information
739/// to the form used in overload-candidate information.
743 TemplateDeductionInfo &Info) {
745 Result.Result = static_cast<unsigned>(TDK);
746 Result.HasDiagnostic = false;
747 switch (TDK) {
754 Result.Data = nullptr;
755 break;
756
759 Result.Data = Info.Param.getOpaqueValue();
760 break;
761
764 // FIXME: Should allocate from normal heap so that we can free this later.
765 auto *Saved = new (Context) DFIDeducedMismatchArgs;
766 Saved->FirstArg = Info.FirstArg;
767 Saved->SecondArg = Info.SecondArg;
768 Saved->TemplateArgs = Info.takeSugared();
769 Saved->CallArgIndex = Info.CallArgIndex;
770 Result.Data = Saved;
771 break;
772 }
773
775 // FIXME: Should allocate from normal heap so that we can free this later.
776 DFIArguments *Saved = new (Context) DFIArguments;
777 Saved->FirstArg = Info.FirstArg;
778 Saved->SecondArg = Info.SecondArg;
779 Result.Data = Saved;
780 break;
781 }
782
784 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
787 // FIXME: Should allocate from normal heap so that we can free this later.
788 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
789 Saved->Param = Info.Param;
790 Saved->FirstArg = Info.FirstArg;
791 Saved->SecondArg = Info.SecondArg;
792 Result.Data = Saved;
793 break;
794 }
795
797 Result.Data = Info.takeSugared();
798 if (Info.hasSFINAEDiagnostic()) {
802 Result.HasDiagnostic = true;
803 }
804 break;
805
807 CNSInfo *Saved = new (Context) CNSInfo;
808 Saved->TemplateArgs = Info.takeSugared();
809 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
810 Result.Data = Saved;
811 break;
812 }
813
817 llvm_unreachable("not a deduction failure");
818 }
819
820 return Result;
821}
822
824 switch (static_cast<TemplateDeductionResult>(Result)) {
834 break;
835
842 // FIXME: Destroy the data?
843 Data = nullptr;
844 break;
845
847 // FIXME: Destroy the template argument list?
848 Data = nullptr;
850 Diag->~PartialDiagnosticAt();
851 HasDiagnostic = false;
852 }
853 break;
854
856 // FIXME: Destroy the template argument list?
857 Data = nullptr;
859 Diag->~PartialDiagnosticAt();
860 HasDiagnostic = false;
861 }
862 break;
863
864 // Unhandled
867 break;
868 }
869}
870
872 if (HasDiagnostic)
873 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
874 return nullptr;
875}
876
878 switch (static_cast<TemplateDeductionResult>(Result)) {
891 return TemplateParameter();
892
895 return TemplateParameter::getFromOpaqueValue(Data);
896
900 return static_cast<DFIParamWithArguments*>(Data)->Param;
901
902 // Unhandled
905 break;
906 }
907
908 return TemplateParameter();
909}
910
912 switch (static_cast<TemplateDeductionResult>(Result)) {
926 return nullptr;
927
930 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
931
933 return static_cast<TemplateArgumentList*>(Data);
934
936 return static_cast<CNSInfo*>(Data)->TemplateArgs;
937
938 // Unhandled
941 break;
942 }
943
944 return nullptr;
945}
946
948 switch (static_cast<TemplateDeductionResult>(Result)) {
960 return nullptr;
961
968 return &static_cast<DFIArguments*>(Data)->FirstArg;
969
970 // Unhandled
973 break;
974 }
975
976 return nullptr;
977}
978
980 switch (static_cast<TemplateDeductionResult>(Result)) {
993 return nullptr;
994
1000 return &static_cast<DFIArguments*>(Data)->SecondArg;
1001
1002 // Unhandled
1005 break;
1006 }
1007
1008 return nullptr;
1009}
1010
1011std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
1012 switch (static_cast<TemplateDeductionResult>(Result)) {
1015 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1016
1017 default:
1018 return std::nullopt;
1019 }
1020}
1021
1023 const FunctionDecl *Y) {
1024 if (!X || !Y)
1025 return false;
1026 if (X->getNumParams() != Y->getNumParams())
1027 return false;
1028 // FIXME: when do rewritten comparison operators
1029 // with explicit object parameters correspond?
1030 // https://cplusplus.github.io/CWG/issues/2797.html
1031 for (unsigned I = 0; I < X->getNumParams(); ++I)
1032 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1033 Y->getParamDecl(I)->getType()))
1034 return false;
1035 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1036 auto *FTY = Y->getDescribedFunctionTemplate();
1037 if (!FTY)
1038 return false;
1039 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1040 FTY->getTemplateParameters()))
1041 return false;
1042 }
1043 return true;
1044}
1045
1047 Expr *FirstOperand, FunctionDecl *EqFD) {
1048 assert(EqFD->getOverloadedOperator() ==
1049 OverloadedOperatorKind::OO_EqualEqual);
1050 // C++2a [over.match.oper]p4:
1051 // A non-template function or function template F named operator== is a
1052 // rewrite target with first operand o unless a search for the name operator!=
1053 // in the scope S from the instantiation context of the operator expression
1054 // finds a function or function template that would correspond
1055 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1056 // scope of the class type of o if F is a class member, and the namespace
1057 // scope of which F is a member otherwise. A function template specialization
1058 // named operator== is a rewrite target if its function template is a rewrite
1059 // target.
1061 OverloadedOperatorKind::OO_ExclaimEqual);
1062 if (isa<CXXMethodDecl>(EqFD)) {
1063 // If F is a class member, search scope is class type of first operand.
1064 QualType RHS = FirstOperand->getType();
1065 auto *RHSRec = RHS->getAs<RecordType>();
1066 if (!RHSRec)
1067 return true;
1068 LookupResult Members(S, NotEqOp, OpLoc,
1070 S.LookupQualifiedName(Members, RHSRec->getDecl());
1071 Members.suppressAccessDiagnostics();
1072 for (NamedDecl *Op : Members)
1073 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1074 return false;
1075 return true;
1076 }
1077 // Otherwise the search scope is the namespace scope of which F is a member.
1078 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1079 auto *NotEqFD = Op->getAsFunction();
1080 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1081 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1082 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1084 cast<Decl>(Op->getLexicalDeclContext())))
1085 return false;
1086 }
1087 return true;
1088}
1089
1093 return false;
1094 return Op == OO_EqualEqual || Op == OO_Spaceship;
1095}
1096
1098 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1099 auto Op = FD->getOverloadedOperator();
1100 if (!allowsReversed(Op))
1101 return false;
1102 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1103 assert(OriginalArgs.size() == 2);
1105 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1106 return false;
1107 }
1108 // Don't bother adding a reversed candidate that can never be a better
1109 // match than the non-reversed version.
1110 return FD->getNumNonObjectParams() != 2 ||
1112 FD->getParamDecl(1)->getType()) ||
1113 FD->hasAttr<EnableIfAttr>();
1114}
1115
1116void OverloadCandidateSet::destroyCandidates() {
1117 for (iterator i = begin(), e = end(); i != e; ++i) {
1118 for (auto &C : i->Conversions)
1119 C.~ImplicitConversionSequence();
1120 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1121 i->DeductionFailure.Destroy();
1122 }
1123}
1124
1126 destroyCandidates();
1127 SlabAllocator.Reset();
1128 NumInlineBytesUsed = 0;
1129 Candidates.clear();
1130 Functions.clear();
1131 Kind = CSK;
1132}
1133
1134namespace {
1135 class UnbridgedCastsSet {
1136 struct Entry {
1137 Expr **Addr;
1138 Expr *Saved;
1139 };
1140 SmallVector<Entry, 2> Entries;
1141
1142 public:
1143 void save(Sema &S, Expr *&E) {
1144 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1145 Entry entry = { &E, E };
1146 Entries.push_back(entry);
1148 }
1149
1150 void restore() {
1152 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1153 *i->Addr = i->Saved;
1154 }
1155 };
1156}
1157
1158/// checkPlaceholderForOverload - Do any interesting placeholder-like
1159/// preprocessing on the given expression.
1160///
1161/// \param unbridgedCasts a collection to which to add unbridged casts;
1162/// without this, they will be immediately diagnosed as errors
1163///
1164/// Return true on unrecoverable error.
1165static bool
1167 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1168 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1169 // We can't handle overloaded expressions here because overload
1170 // resolution might reasonably tweak them.
1171 if (placeholder->getKind() == BuiltinType::Overload) return false;
1172
1173 // If the context potentially accepts unbridged ARC casts, strip
1174 // the unbridged cast and add it to the collection for later restoration.
1175 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1176 unbridgedCasts) {
1177 unbridgedCasts->save(S, E);
1178 return false;
1179 }
1180
1181 // Go ahead and check everything else.
1182 ExprResult result = S.CheckPlaceholderExpr(E);
1183 if (result.isInvalid())
1184 return true;
1185
1186 E = result.get();
1187 return false;
1188 }
1189
1190 // Nothing to do.
1191 return false;
1192}
1193
1194/// checkArgPlaceholdersForOverload - Check a set of call operands for
1195/// placeholders.
1197 UnbridgedCastsSet &unbridged) {
1198 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1199 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1200 return true;
1201
1202 return false;
1203}
1204
1207 NamedDecl *&Match, bool NewIsUsingDecl) {
1208 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1209 I != E; ++I) {
1210 NamedDecl *OldD = *I;
1211
1212 bool OldIsUsingDecl = false;
1213 if (isa<UsingShadowDecl>(OldD)) {
1214 OldIsUsingDecl = true;
1215
1216 // We can always introduce two using declarations into the same
1217 // context, even if they have identical signatures.
1218 if (NewIsUsingDecl) continue;
1219
1220 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1221 }
1222
1223 // A using-declaration does not conflict with another declaration
1224 // if one of them is hidden.
1225 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1226 continue;
1227
1228 // If either declaration was introduced by a using declaration,
1229 // we'll need to use slightly different rules for matching.
1230 // Essentially, these rules are the normal rules, except that
1231 // function templates hide function templates with different
1232 // return types or template parameter lists.
1233 bool UseMemberUsingDeclRules =
1234 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1235 !New->getFriendObjectKind();
1236
1237 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1238 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1239 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1240 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1241 continue;
1242 }
1243
1244 if (!isa<FunctionTemplateDecl>(OldD) &&
1245 !shouldLinkPossiblyHiddenDecl(*I, New))
1246 continue;
1247
1248 Match = *I;
1249 return Ovl_Match;
1250 }
1251
1252 // Builtins that have custom typechecking or have a reference should
1253 // not be overloadable or redeclarable.
1254 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1255 Match = *I;
1256 return Ovl_NonFunction;
1257 }
1258 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1259 // We can overload with these, which can show up when doing
1260 // redeclaration checks for UsingDecls.
1261 assert(Old.getLookupKind() == LookupUsingDeclName);
1262 } else if (isa<TagDecl>(OldD)) {
1263 // We can always overload with tags by hiding them.
1264 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1265 // Optimistically assume that an unresolved using decl will
1266 // overload; if it doesn't, we'll have to diagnose during
1267 // template instantiation.
1268 //
1269 // Exception: if the scope is dependent and this is not a class
1270 // member, the using declaration can only introduce an enumerator.
1271 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1272 Match = *I;
1273 return Ovl_NonFunction;
1274 }
1275 } else {
1276 // (C++ 13p1):
1277 // Only function declarations can be overloaded; object and type
1278 // declarations cannot be overloaded.
1279 Match = *I;
1280 return Ovl_NonFunction;
1281 }
1282 }
1283
1284 // C++ [temp.friend]p1:
1285 // For a friend function declaration that is not a template declaration:
1286 // -- if the name of the friend is a qualified or unqualified template-id,
1287 // [...], otherwise
1288 // -- if the name of the friend is a qualified-id and a matching
1289 // non-template function is found in the specified class or namespace,
1290 // the friend declaration refers to that function, otherwise,
1291 // -- if the name of the friend is a qualified-id and a matching function
1292 // template is found in the specified class or namespace, the friend
1293 // declaration refers to the deduced specialization of that function
1294 // template, otherwise
1295 // -- the name shall be an unqualified-id [...]
1296 // If we get here for a qualified friend declaration, we've just reached the
1297 // third bullet. If the type of the friend is dependent, skip this lookup
1298 // until instantiation.
1299 if (New->getFriendObjectKind() && New->getQualifier() &&
1302 !New->getType()->isDependentType()) {
1303 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1304 TemplateSpecResult.addAllDecls(Old);
1305 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1306 /*QualifiedFriend*/true)) {
1307 New->setInvalidDecl();
1308 return Ovl_Overload;
1309 }
1310
1311 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1312 return Ovl_Match;
1313 }
1314
1315 return Ovl_Overload;
1316}
1317
1318static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1319 FunctionDecl *Old,
1320 bool UseMemberUsingDeclRules,
1321 bool ConsiderCudaAttrs,
1322 bool UseOverrideRules = false) {
1323 // C++ [basic.start.main]p2: This function shall not be overloaded.
1324 if (New->isMain())
1325 return false;
1326
1327 // MSVCRT user defined entry points cannot be overloaded.
1328 if (New->isMSVCRTEntryPoint())
1329 return false;
1330
1331 NamedDecl *OldDecl = Old;
1332 NamedDecl *NewDecl = New;
1335
1336 // C++ [temp.fct]p2:
1337 // A function template can be overloaded with other function templates
1338 // and with normal (non-template) functions.
1339 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1340 return true;
1341
1342 // Is the function New an overload of the function Old?
1343 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1344 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1345
1346 // Compare the signatures (C++ 1.3.10) of the two functions to
1347 // determine whether they are overloads. If we find any mismatch
1348 // in the signature, they are overloads.
1349
1350 // If either of these functions is a K&R-style function (no
1351 // prototype), then we consider them to have matching signatures.
1352 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1353 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1354 return false;
1355
1356 const auto *OldType = cast<FunctionProtoType>(OldQType);
1357 const auto *NewType = cast<FunctionProtoType>(NewQType);
1358
1359 // The signature of a function includes the types of its
1360 // parameters (C++ 1.3.10), which includes the presence or absence
1361 // of the ellipsis; see C++ DR 357).
1362 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1363 return true;
1364
1365 // For member-like friends, the enclosing class is part of the signature.
1366 if ((New->isMemberLikeConstrainedFriend() ||
1369 return true;
1370
1371 // Compare the parameter lists.
1372 // This can only be done once we have establish that friend functions
1373 // inhabit the same context, otherwise we might tried to instantiate
1374 // references to non-instantiated entities during constraint substitution.
1375 // GH78101.
1376 if (NewTemplate) {
1377 OldDecl = OldTemplate;
1378 NewDecl = NewTemplate;
1379 // C++ [temp.over.link]p4:
1380 // The signature of a function template consists of its function
1381 // signature, its return type and its template parameter list. The names
1382 // of the template parameters are significant only for establishing the
1383 // relationship between the template parameters and the rest of the
1384 // signature.
1385 //
1386 // We check the return type and template parameter lists for function
1387 // templates first; the remaining checks follow.
1388 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1389 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1390 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1391 bool SameReturnType = SemaRef.Context.hasSameType(
1393 // FIXME(GH58571): Match template parameter list even for non-constrained
1394 // template heads. This currently ensures that the code prior to C++20 is
1395 // not newly broken.
1396 bool ConstraintsInTemplateHead =
1399 // C++ [namespace.udecl]p11:
1400 // The set of declarations named by a using-declarator that inhabits a
1401 // class C does not include member functions and member function
1402 // templates of a base class that "correspond" to (and thus would
1403 // conflict with) a declaration of a function or function template in
1404 // C.
1405 // Comparing return types is not required for the "correspond" check to
1406 // decide whether a member introduced by a shadow declaration is hidden.
1407 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1408 !SameTemplateParameterList)
1409 return true;
1410 if (!UseMemberUsingDeclRules &&
1411 (!SameTemplateParameterList || !SameReturnType))
1412 return true;
1413 }
1414
1415 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1416 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1417
1418 int OldParamsOffset = 0;
1419 int NewParamsOffset = 0;
1420
1421 // When determining if a method is an overload from a base class, act as if
1422 // the implicit object parameter are of the same type.
1423
1424 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1426 return Q;
1427
1428 // We do not allow overloading based off of '__restrict'.
1429 Q.removeRestrict();
1430
1431 // We may not have applied the implicit const for a constexpr member
1432 // function yet (because we haven't yet resolved whether this is a static
1433 // or non-static member function). Add it now, on the assumption that this
1434 // is a redeclaration of OldMethod.
1435 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1436 (M->isConstexpr() || M->isConsteval()) &&
1437 !isa<CXXConstructorDecl>(NewMethod))
1438 Q.addConst();
1439 return Q;
1440 };
1441
1442 auto CompareType = [&](QualType Base, QualType D) {
1443 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1444 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1445
1446 auto DS = D.getNonReferenceType().getCanonicalType().split();
1447 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1448
1449 if (BS.Quals != DS.Quals)
1450 return false;
1451
1452 if (OldMethod->isImplicitObjectMemberFunction() &&
1453 OldMethod->getParent() != NewMethod->getParent()) {
1454 QualType ParentType =
1455 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1457 if (ParentType.getTypePtr() != BS.Ty)
1458 return false;
1459 BS.Ty = DS.Ty;
1460 }
1461
1462 // FIXME: should we ignore some type attributes here?
1463 if (BS.Ty != DS.Ty)
1464 return false;
1465
1466 if (Base->isLValueReferenceType())
1467 return D->isLValueReferenceType();
1468 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1469 };
1470
1471 // If the function is a class member, its signature includes the
1472 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1473 auto DiagnoseInconsistentRefQualifiers = [&]() {
1474 if (SemaRef.LangOpts.CPlusPlus23)
1475 return false;
1476 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1477 return false;
1478 if (OldMethod->isExplicitObjectMemberFunction() ||
1479 NewMethod->isExplicitObjectMemberFunction())
1480 return false;
1481 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1482 NewMethod->getRefQualifier() == RQ_None)) {
1483 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1484 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1485 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1486 return true;
1487 }
1488 return false;
1489 };
1490
1491 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1492 OldParamsOffset++;
1493 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1494 NewParamsOffset++;
1495
1496 if (OldType->getNumParams() - OldParamsOffset !=
1497 NewType->getNumParams() - NewParamsOffset ||
1499 {OldType->param_type_begin() + OldParamsOffset,
1500 OldType->param_type_end()},
1501 {NewType->param_type_begin() + NewParamsOffset,
1502 NewType->param_type_end()},
1503 nullptr)) {
1504 return true;
1505 }
1506
1507 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1508 !NewMethod->isStatic()) {
1509 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1510 const CXXMethodDecl *New) {
1511 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1512 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1513
1514 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1515 return F->getRefQualifier() == RQ_None &&
1516 !F->isExplicitObjectMemberFunction();
1517 };
1518
1519 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1520 CompareType(OldObjectType.getNonReferenceType(),
1521 NewObjectType.getNonReferenceType()))
1522 return true;
1523 return CompareType(OldObjectType, NewObjectType);
1524 }(OldMethod, NewMethod);
1525
1526 if (!HaveCorrespondingObjectParameters) {
1527 if (DiagnoseInconsistentRefQualifiers())
1528 return true;
1529 // CWG2554
1530 // and, if at least one is an explicit object member function, ignoring
1531 // object parameters
1532 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1533 !OldMethod->isExplicitObjectMemberFunction()))
1534 return true;
1535 }
1536 }
1537
1538 if (!UseOverrideRules &&
1540 Expr *NewRC = New->getTrailingRequiresClause(),
1541 *OldRC = Old->getTrailingRequiresClause();
1542 if ((NewRC != nullptr) != (OldRC != nullptr))
1543 return true;
1544 if (NewRC &&
1545 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1546 return true;
1547 }
1548
1549 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1550 NewMethod->isImplicitObjectMemberFunction()) {
1551 if (DiagnoseInconsistentRefQualifiers())
1552 return true;
1553 }
1554
1555 // Though pass_object_size is placed on parameters and takes an argument, we
1556 // consider it to be a function-level modifier for the sake of function
1557 // identity. Either the function has one or more parameters with
1558 // pass_object_size or it doesn't.
1561 return true;
1562
1563 // enable_if attributes are an order-sensitive part of the signature.
1565 NewI = New->specific_attr_begin<EnableIfAttr>(),
1566 NewE = New->specific_attr_end<EnableIfAttr>(),
1567 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1568 OldE = Old->specific_attr_end<EnableIfAttr>();
1569 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1570 if (NewI == NewE || OldI == OldE)
1571 return true;
1572 llvm::FoldingSetNodeID NewID, OldID;
1573 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1574 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1575 if (NewID != OldID)
1576 return true;
1577 }
1578
1579 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1580 // Don't allow overloading of destructors. (In theory we could, but it
1581 // would be a giant change to clang.)
1582 if (!isa<CXXDestructorDecl>(New)) {
1583 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1584 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1585 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1586 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1587 "Unexpected invalid target.");
1588
1589 // Allow overloading of functions with same signature and different CUDA
1590 // target attributes.
1591 if (NewTarget != OldTarget)
1592 return true;
1593 }
1594 }
1595 }
1596
1597 // The signatures match; this is not an overload.
1598 return false;
1599}
1600
1602 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1603 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1604 ConsiderCudaAttrs);
1605}
1606
1608 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1609 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1610 /*UseMemberUsingDeclRules=*/false,
1611 /*ConsiderCudaAttrs=*/true,
1612 /*UseOverrideRules=*/true);
1613}
1614
1615/// Tries a user-defined conversion from From to ToType.
1616///
1617/// Produces an implicit conversion sequence for when a standard conversion
1618/// is not an option. See TryImplicitConversion for more information.
1621 bool SuppressUserConversions,
1622 AllowedExplicit AllowExplicit,
1623 bool InOverloadResolution,
1624 bool CStyle,
1625 bool AllowObjCWritebackConversion,
1626 bool AllowObjCConversionOnExplicit) {
1628
1629 if (SuppressUserConversions) {
1630 // We're not in the case above, so there is no conversion that
1631 // we can perform.
1633 return ICS;
1634 }
1635
1636 // Attempt user-defined conversion.
1637 OverloadCandidateSet Conversions(From->getExprLoc(),
1639 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1640 Conversions, AllowExplicit,
1641 AllowObjCConversionOnExplicit)) {
1642 case OR_Success:
1643 case OR_Deleted:
1644 ICS.setUserDefined();
1645 // C++ [over.ics.user]p4:
1646 // A conversion of an expression of class type to the same class
1647 // type is given Exact Match rank, and a conversion of an
1648 // expression of class type to a base class of that type is
1649 // given Conversion rank, in spite of the fact that a copy
1650 // constructor (i.e., a user-defined conversion function) is
1651 // called for those cases.
1652 if (CXXConstructorDecl *Constructor
1653 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1654 QualType FromType;
1655 SourceLocation FromLoc;
1656 // C++11 [over.ics.list]p6, per DR2137:
1657 // C++17 [over.ics.list]p6:
1658 // If C is not an initializer-list constructor and the initializer list
1659 // has a single element of type cv U, where U is X or a class derived
1660 // from X, the implicit conversion sequence has Exact Match rank if U is
1661 // X, or Conversion rank if U is derived from X.
1662 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1663 InitList && InitList->getNumInits() == 1 &&
1664 !S.isInitListConstructor(Constructor)) {
1665 const Expr *SingleInit = InitList->getInit(0);
1666 FromType = SingleInit->getType();
1667 FromLoc = SingleInit->getBeginLoc();
1668 } else {
1669 FromType = From->getType();
1670 FromLoc = From->getBeginLoc();
1671 }
1672 QualType FromCanon =
1674 QualType ToCanon
1676 if ((FromCanon == ToCanon ||
1677 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1678 // Turn this into a "standard" conversion sequence, so that it
1679 // gets ranked with standard conversion sequences.
1681 ICS.setStandard();
1683 ICS.Standard.setFromType(FromType);
1684 ICS.Standard.setAllToTypes(ToType);
1685 ICS.Standard.CopyConstructor = Constructor;
1687 if (ToCanon != FromCanon)
1689 }
1690 }
1691 break;
1692
1693 case OR_Ambiguous:
1694 ICS.setAmbiguous();
1695 ICS.Ambiguous.setFromType(From->getType());
1696 ICS.Ambiguous.setToType(ToType);
1697 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1698 Cand != Conversions.end(); ++Cand)
1699 if (Cand->Best)
1700 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1701 break;
1702
1703 // Fall through.
1706 break;
1707 }
1708
1709 return ICS;
1710}
1711
1712/// TryImplicitConversion - Attempt to perform an implicit conversion
1713/// from the given expression (Expr) to the given type (ToType). This
1714/// function returns an implicit conversion sequence that can be used
1715/// to perform the initialization. Given
1716///
1717/// void f(float f);
1718/// void g(int i) { f(i); }
1719///
1720/// this routine would produce an implicit conversion sequence to
1721/// describe the initialization of f from i, which will be a standard
1722/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1723/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1724//
1725/// Note that this routine only determines how the conversion can be
1726/// performed; it does not actually perform the conversion. As such,
1727/// it will not produce any diagnostics if no conversion is available,
1728/// but will instead return an implicit conversion sequence of kind
1729/// "BadConversion".
1730///
1731/// If @p SuppressUserConversions, then user-defined conversions are
1732/// not permitted.
1733/// If @p AllowExplicit, then explicit user-defined conversions are
1734/// permitted.
1735///
1736/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1737/// writeback conversion, which allows __autoreleasing id* parameters to
1738/// be initialized with __strong id* or __weak id* arguments.
1741 bool SuppressUserConversions,
1742 AllowedExplicit AllowExplicit,
1743 bool InOverloadResolution,
1744 bool CStyle,
1745 bool AllowObjCWritebackConversion,
1746 bool AllowObjCConversionOnExplicit) {
1748 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1749 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1750 ICS.setStandard();
1751 return ICS;
1752 }
1753
1754 if (!S.getLangOpts().CPlusPlus) {
1756 return ICS;
1757 }
1758
1759 // C++ [over.ics.user]p4:
1760 // A conversion of an expression of class type to the same class
1761 // type is given Exact Match rank, and a conversion of an
1762 // expression of class type to a base class of that type is
1763 // given Conversion rank, in spite of the fact that a copy/move
1764 // constructor (i.e., a user-defined conversion function) is
1765 // called for those cases.
1766 QualType FromType = From->getType();
1767 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1768 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1769 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1770 ICS.setStandard();
1772 ICS.Standard.setFromType(FromType);
1773 ICS.Standard.setAllToTypes(ToType);
1774
1775 // We don't actually check at this point whether there is a valid
1776 // copy/move constructor, since overloading just assumes that it
1777 // exists. When we actually perform initialization, we'll find the
1778 // appropriate constructor to copy the returned object, if needed.
1779 ICS.Standard.CopyConstructor = nullptr;
1780
1781 // Determine whether this is considered a derived-to-base conversion.
1782 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1784
1785 return ICS;
1786 }
1787
1788 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1789 AllowExplicit, InOverloadResolution, CStyle,
1790 AllowObjCWritebackConversion,
1791 AllowObjCConversionOnExplicit);
1792}
1793
1796 bool SuppressUserConversions,
1797 AllowedExplicit AllowExplicit,
1798 bool InOverloadResolution,
1799 bool CStyle,
1800 bool AllowObjCWritebackConversion) {
1801 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1802 AllowExplicit, InOverloadResolution, CStyle,
1803 AllowObjCWritebackConversion,
1804 /*AllowObjCConversionOnExplicit=*/false);
1805}
1806
1808 AssignmentAction Action,
1809 bool AllowExplicit) {
1810 if (checkPlaceholderForOverload(*this, From))
1811 return ExprError();
1812
1813 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1814 bool AllowObjCWritebackConversion
1815 = getLangOpts().ObjCAutoRefCount &&
1816 (Action == AA_Passing || Action == AA_Sending);
1817 if (getLangOpts().ObjC)
1818 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1819 From->getType(), From);
1821 *this, From, ToType,
1822 /*SuppressUserConversions=*/false,
1823 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1824 /*InOverloadResolution=*/false,
1825 /*CStyle=*/false, AllowObjCWritebackConversion,
1826 /*AllowObjCConversionOnExplicit=*/false);
1827 return PerformImplicitConversion(From, ToType, ICS, Action);
1828}
1829
1831 QualType &ResultTy) {
1832 if (Context.hasSameUnqualifiedType(FromType, ToType))
1833 return false;
1834
1835 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1836 // or F(t noexcept) -> F(t)
1837 // where F adds one of the following at most once:
1838 // - a pointer
1839 // - a member pointer
1840 // - a block pointer
1841 // Changes here need matching changes in FindCompositePointerType.
1842 CanQualType CanTo = Context.getCanonicalType(ToType);
1843 CanQualType CanFrom = Context.getCanonicalType(FromType);
1844 Type::TypeClass TyClass = CanTo->getTypeClass();
1845 if (TyClass != CanFrom->getTypeClass()) return false;
1846 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1847 if (TyClass == Type::Pointer) {
1848 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1849 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1850 } else if (TyClass == Type::BlockPointer) {
1851 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1852 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1853 } else if (TyClass == Type::MemberPointer) {
1854 auto ToMPT = CanTo.castAs<MemberPointerType>();
1855 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1856 // A function pointer conversion cannot change the class of the function.
1857 if (ToMPT->getClass() != FromMPT->getClass())
1858 return false;
1859 CanTo = ToMPT->getPointeeType();
1860 CanFrom = FromMPT->getPointeeType();
1861 } else {
1862 return false;
1863 }
1864
1865 TyClass = CanTo->getTypeClass();
1866 if (TyClass != CanFrom->getTypeClass()) return false;
1867 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1868 return false;
1869 }
1870
1871 const auto *FromFn = cast<FunctionType>(CanFrom);
1872 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1873
1874 const auto *ToFn = cast<FunctionType>(CanTo);
1875 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1876
1877 bool Changed = false;
1878
1879 // Drop 'noreturn' if not present in target type.
1880 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1881 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1882 Changed = true;
1883 }
1884
1885 // Drop 'noexcept' if not present in target type.
1886 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1887 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1888 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1889 FromFn = cast<FunctionType>(
1890 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1891 EST_None)
1892 .getTypePtr());
1893 Changed = true;
1894 }
1895
1896 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1897 // only if the ExtParameterInfo lists of the two function prototypes can be
1898 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1900 bool CanUseToFPT, CanUseFromFPT;
1901 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1902 CanUseFromFPT, NewParamInfos) &&
1903 CanUseToFPT && !CanUseFromFPT) {
1904 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1905 ExtInfo.ExtParameterInfos =
1906 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1907 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1908 FromFPT->getParamTypes(), ExtInfo);
1909 FromFn = QT->getAs<FunctionType>();
1910 Changed = true;
1911 }
1912
1913 // For C, when called from checkPointerTypesForAssignment,
1914 // we need to not alter FromFn, or else even an innocuous cast
1915 // like dropping effects will fail. In C++ however we do want to
1916 // alter FromFn (because of the way PerformImplicitConversion works).
1917 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1918 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1919
1920 // Transparently add/drop effects; here we are concerned with
1921 // language rules/canonicalization. Adding/dropping effects is a warning.
1922 const auto FromFX = FromFPT->getFunctionEffects();
1923 const auto ToFX = ToFPT->getFunctionEffects();
1924 if (FromFX != ToFX) {
1925 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1926 ExtInfo.FunctionEffects = ToFX;
1927 QualType QT = Context.getFunctionType(
1928 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1929 FromFn = QT->getAs<FunctionType>();
1930 Changed = true;
1931 }
1932 }
1933 }
1934
1935 if (!Changed)
1936 return false;
1937
1938 assert(QualType(FromFn, 0).isCanonical());
1939 if (QualType(FromFn, 0) != CanTo) return false;
1940
1941 ResultTy = ToType;
1942 return true;
1943}
1944
1945/// Determine whether the conversion from FromType to ToType is a valid
1946/// floating point conversion.
1947///
1948static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1949 QualType ToType) {
1950 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1951 return false;
1952 // FIXME: disable conversions between long double, __ibm128 and __float128
1953 // if their representation is different until there is back end support
1954 // We of course allow this conversion if long double is really double.
1955
1956 // Conversions between bfloat16 and float16 are currently not supported.
1957 if ((FromType->isBFloat16Type() &&
1958 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1959 (ToType->isBFloat16Type() &&
1960 (FromType->isFloat16Type() || FromType->isHalfType())))
1961 return false;
1962
1963 // Conversions between IEEE-quad and IBM-extended semantics are not
1964 // permitted.
1965 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1966 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1967 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1968 &ToSem == &llvm::APFloat::IEEEquad()) ||
1969 (&FromSem == &llvm::APFloat::IEEEquad() &&
1970 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1971 return false;
1972 return true;
1973}
1974
1975static bool IsVectorElementConversion(Sema &S, QualType FromType,
1976 QualType ToType,
1977 ImplicitConversionKind &ICK, Expr *From) {
1978 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1979 return true;
1980
1981 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1983 return true;
1984 }
1985
1986 if (IsFloatingPointConversion(S, FromType, ToType)) {
1988 return true;
1989 }
1990
1991 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1993 return true;
1994 }
1995
1996 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1998 ToType->isRealFloatingType())) {
2000 return true;
2001 }
2002
2003 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2005 return true;
2006 }
2007
2008 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2009 ToType->isIntegralType(S.Context)) {
2011 return true;
2012 }
2013
2014 return false;
2015}
2016
2017/// Determine whether the conversion from FromType to ToType is a valid
2018/// vector conversion.
2019///
2020/// \param ICK Will be set to the vector conversion kind, if this is a vector
2021/// conversion.
2022static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2024 ImplicitConversionKind &ElConv, Expr *From,
2025 bool InOverloadResolution, bool CStyle) {
2026 // We need at least one of these types to be a vector type to have a vector
2027 // conversion.
2028 if (!ToType->isVectorType() && !FromType->isVectorType())
2029 return false;
2030
2031 // Identical types require no conversions.
2032 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2033 return false;
2034
2035 // There are no conversions between extended vector types, only identity.
2036 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2037 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2038 // HLSL allows implicit truncation of vector types.
2039 if (S.getLangOpts().HLSL) {
2040 unsigned FromElts = FromExtType->getNumElements();
2041 unsigned ToElts = ToExtType->getNumElements();
2042 if (FromElts < ToElts)
2043 return false;
2044 if (FromElts == ToElts)
2045 ElConv = ICK_Identity;
2046 else
2048
2049 QualType FromElTy = FromExtType->getElementType();
2050 QualType ToElTy = ToExtType->getElementType();
2051 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2052 return true;
2053 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2054 }
2055 // There are no conversions between extended vector types other than the
2056 // identity conversion.
2057 return false;
2058 }
2059
2060 // Vector splat from any arithmetic type to a vector.
2061 if (FromType->isArithmeticType()) {
2062 if (S.getLangOpts().HLSL) {
2063 ElConv = ICK_HLSL_Vector_Splat;
2064 QualType ToElTy = ToExtType->getElementType();
2065 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2066 }
2067 ICK = ICK_Vector_Splat;
2068 return true;
2069 }
2070 }
2071
2072 if (ToType->isSVESizelessBuiltinType() ||
2073 FromType->isSVESizelessBuiltinType())
2074 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2075 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2077 return true;
2078 }
2079
2080 if (ToType->isRVVSizelessBuiltinType() ||
2081 FromType->isRVVSizelessBuiltinType())
2082 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2083 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2085 return true;
2086 }
2087
2088 // We can perform the conversion between vector types in the following cases:
2089 // 1)vector types are equivalent AltiVec and GCC vector types
2090 // 2)lax vector conversions are permitted and the vector types are of the
2091 // same size
2092 // 3)the destination type does not have the ARM MVE strict-polymorphism
2093 // attribute, which inhibits lax vector conversion for overload resolution
2094 // only
2095 if (ToType->isVectorType() && FromType->isVectorType()) {
2096 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2097 (S.isLaxVectorConversion(FromType, ToType) &&
2098 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2099 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2100 S.isLaxVectorConversion(FromType, ToType) &&
2101 S.anyAltivecTypes(FromType, ToType) &&
2102 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2103 !InOverloadResolution && !CStyle) {
2104 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2105 << FromType << ToType;
2106 }
2108 return true;
2109 }
2110 }
2111
2112 return false;
2113}
2114
2115static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2116 bool InOverloadResolution,
2118 bool CStyle);
2119
2120/// IsStandardConversion - Determines whether there is a standard
2121/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2122/// expression From to the type ToType. Standard conversion sequences
2123/// only consider non-class types; for conversions that involve class
2124/// types, use TryImplicitConversion. If a conversion exists, SCS will
2125/// contain the standard conversion sequence required to perform this
2126/// conversion and this routine will return true. Otherwise, this
2127/// routine will return false and the value of SCS is unspecified.
2128static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2129 bool InOverloadResolution,
2131 bool CStyle,
2132 bool AllowObjCWritebackConversion) {
2133 QualType FromType = From->getType();
2134
2135 // Standard conversions (C++ [conv])
2137 SCS.IncompatibleObjC = false;
2138 SCS.setFromType(FromType);
2139 SCS.CopyConstructor = nullptr;
2140
2141 // There are no standard conversions for class types in C++, so
2142 // abort early. When overloading in C, however, we do permit them.
2143 if (S.getLangOpts().CPlusPlus &&
2144 (FromType->isRecordType() || ToType->isRecordType()))
2145 return false;
2146
2147 // The first conversion can be an lvalue-to-rvalue conversion,
2148 // array-to-pointer conversion, or function-to-pointer conversion
2149 // (C++ 4p1).
2150
2151 if (FromType == S.Context.OverloadTy) {
2152 DeclAccessPair AccessPair;
2153 if (FunctionDecl *Fn
2154 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2155 AccessPair)) {
2156 // We were able to resolve the address of the overloaded function,
2157 // so we can convert to the type of that function.
2158 FromType = Fn->getType();
2159 SCS.setFromType(FromType);
2160
2161 // we can sometimes resolve &foo<int> regardless of ToType, so check
2162 // if the type matches (identity) or we are converting to bool
2164 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2165 QualType resultTy;
2166 // if the function type matches except for [[noreturn]], it's ok
2167 if (!S.IsFunctionConversion(FromType,
2168 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2169 // otherwise, only a boolean conversion is standard
2170 if (!ToType->isBooleanType())
2171 return false;
2172 }
2173
2174 // Check if the "from" expression is taking the address of an overloaded
2175 // function and recompute the FromType accordingly. Take advantage of the
2176 // fact that non-static member functions *must* have such an address-of
2177 // expression.
2178 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2179 if (Method && !Method->isStatic() &&
2180 !Method->isExplicitObjectMemberFunction()) {
2181 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2182 "Non-unary operator on non-static member address");
2183 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2184 == UO_AddrOf &&
2185 "Non-address-of operator on non-static member address");
2186 const Type *ClassType
2188 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2189 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2190 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2191 UO_AddrOf &&
2192 "Non-address-of operator for overloaded function expression");
2193 FromType = S.Context.getPointerType(FromType);
2194 }
2195 } else {
2196 return false;
2197 }
2198 }
2199 // Lvalue-to-rvalue conversion (C++11 4.1):
2200 // A glvalue (3.10) of a non-function, non-array type T can
2201 // be converted to a prvalue.
2202 bool argIsLValue = From->isGLValue();
2203 if (argIsLValue && !FromType->canDecayToPointerType() &&
2204 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2206
2207 // C11 6.3.2.1p2:
2208 // ... if the lvalue has atomic type, the value has the non-atomic version
2209 // of the type of the lvalue ...
2210 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2211 FromType = Atomic->getValueType();
2212
2213 // If T is a non-class type, the type of the rvalue is the
2214 // cv-unqualified version of T. Otherwise, the type of the rvalue
2215 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2216 // just strip the qualifiers because they don't matter.
2217 FromType = FromType.getUnqualifiedType();
2218 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2219 ToType->isArrayParameterType()) {
2220 // HLSL constant array parameters do not decay, so if the argument is a
2221 // constant array and the parameter is an ArrayParameterType we have special
2222 // handling here.
2223 FromType = S.Context.getArrayParameterType(FromType);
2224 if (S.Context.getCanonicalType(FromType) !=
2225 S.Context.getCanonicalType(ToType))
2226 return false;
2227
2229 SCS.setAllToTypes(ToType);
2230 return true;
2231 } else if (FromType->isArrayType()) {
2232 // Array-to-pointer conversion (C++ 4.2)
2234
2235 // An lvalue or rvalue of type "array of N T" or "array of unknown
2236 // bound of T" can be converted to an rvalue of type "pointer to
2237 // T" (C++ 4.2p1).
2238 FromType = S.Context.getArrayDecayedType(FromType);
2239
2240 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2241 // This conversion is deprecated in C++03 (D.4)
2243
2244 // For the purpose of ranking in overload resolution
2245 // (13.3.3.1.1), this conversion is considered an
2246 // array-to-pointer conversion followed by a qualification
2247 // conversion (4.4). (C++ 4.2p2)
2248 SCS.Second = ICK_Identity;
2251 SCS.setAllToTypes(FromType);
2252 return true;
2253 }
2254 } else if (FromType->isFunctionType() && argIsLValue) {
2255 // Function-to-pointer conversion (C++ 4.3).
2257
2258 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2259 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2261 return false;
2262
2263 // An lvalue of function type T can be converted to an rvalue of
2264 // type "pointer to T." The result is a pointer to the
2265 // function. (C++ 4.3p1).
2266 FromType = S.Context.getPointerType(FromType);
2267 } else {
2268 // We don't require any conversions for the first step.
2269 SCS.First = ICK_Identity;
2270 }
2271 SCS.setToType(0, FromType);
2272
2273 // The second conversion can be an integral promotion, floating
2274 // point promotion, integral conversion, floating point conversion,
2275 // floating-integral conversion, pointer conversion,
2276 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2277 // For overloading in C, this can also be a "compatible-type"
2278 // conversion.
2279 bool IncompatibleObjC = false;
2281 ImplicitConversionKind DimensionICK = ICK_Identity;
2282 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2283 // The unqualified versions of the types are the same: there's no
2284 // conversion to do.
2285 SCS.Second = ICK_Identity;
2286 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2287 // Integral promotion (C++ 4.5).
2289 FromType = ToType.getUnqualifiedType();
2290 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2291 // Floating point promotion (C++ 4.6).
2293 FromType = ToType.getUnqualifiedType();
2294 } else if (S.IsComplexPromotion(FromType, ToType)) {
2295 // Complex promotion (Clang extension)
2297 FromType = ToType.getUnqualifiedType();
2298 } else if (ToType->isBooleanType() &&
2299 (FromType->isArithmeticType() ||
2300 FromType->isAnyPointerType() ||
2301 FromType->isBlockPointerType() ||
2302 FromType->isMemberPointerType())) {
2303 // Boolean conversions (C++ 4.12).
2305 FromType = S.Context.BoolTy;
2306 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2307 ToType->isIntegralType(S.Context)) {
2308 // Integral conversions (C++ 4.7).
2310 FromType = ToType.getUnqualifiedType();
2311 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2312 // Complex conversions (C99 6.3.1.6)
2314 FromType = ToType.getUnqualifiedType();
2315 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2316 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2317 // Complex-real conversions (C99 6.3.1.7)
2319 FromType = ToType.getUnqualifiedType();
2320 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2321 // Floating point conversions (C++ 4.8).
2323 FromType = ToType.getUnqualifiedType();
2324 } else if ((FromType->isRealFloatingType() &&
2325 ToType->isIntegralType(S.Context)) ||
2327 ToType->isRealFloatingType())) {
2328
2329 // Floating-integral conversions (C++ 4.9).
2331 FromType = ToType.getUnqualifiedType();
2332 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2334 } else if (AllowObjCWritebackConversion &&
2335 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2337 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2338 FromType, IncompatibleObjC)) {
2339 // Pointer conversions (C++ 4.10).
2341 SCS.IncompatibleObjC = IncompatibleObjC;
2342 FromType = FromType.getUnqualifiedType();
2343 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2344 InOverloadResolution, FromType)) {
2345 // Pointer to member conversions (4.11).
2347 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2348 From, InOverloadResolution, CStyle)) {
2349 SCS.Second = SecondICK;
2350 SCS.Dimension = DimensionICK;
2351 FromType = ToType.getUnqualifiedType();
2352 } else if (!S.getLangOpts().CPlusPlus &&
2353 S.Context.typesAreCompatible(ToType, FromType)) {
2354 // Compatible conversions (Clang extension for C function overloading)
2356 FromType = ToType.getUnqualifiedType();
2358 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2360 FromType = ToType;
2361 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2362 CStyle)) {
2363 // tryAtomicConversion has updated the standard conversion sequence
2364 // appropriately.
2365 return true;
2366 } else if (ToType->isEventT() &&
2368 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2370 FromType = ToType;
2371 } else if (ToType->isQueueT() &&
2373 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2375 FromType = ToType;
2376 } else if (ToType->isSamplerT() &&
2379 FromType = ToType;
2380 } else if ((ToType->isFixedPointType() &&
2381 FromType->isConvertibleToFixedPointType()) ||
2382 (FromType->isFixedPointType() &&
2383 ToType->isConvertibleToFixedPointType())) {
2385 FromType = ToType;
2386 } else {
2387 // No second conversion required.
2388 SCS.Second = ICK_Identity;
2389 }
2390 SCS.setToType(1, FromType);
2391
2392 // The third conversion can be a function pointer conversion or a
2393 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2394 bool ObjCLifetimeConversion;
2395 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2396 // Function pointer conversions (removing 'noexcept') including removal of
2397 // 'noreturn' (Clang extension).
2399 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2400 ObjCLifetimeConversion)) {
2402 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2403 FromType = ToType;
2404 } else {
2405 // No conversion required
2406 SCS.Third = ICK_Identity;
2407 }
2408
2409 // C++ [over.best.ics]p6:
2410 // [...] Any difference in top-level cv-qualification is
2411 // subsumed by the initialization itself and does not constitute
2412 // a conversion. [...]
2413 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2414 QualType CanonTo = S.Context.getCanonicalType(ToType);
2415 if (CanonFrom.getLocalUnqualifiedType()
2416 == CanonTo.getLocalUnqualifiedType() &&
2417 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2418 FromType = ToType;
2419 CanonFrom = CanonTo;
2420 }
2421
2422 SCS.setToType(2, FromType);
2423
2424 if (CanonFrom == CanonTo)
2425 return true;
2426
2427 // If we have not converted the argument type to the parameter type,
2428 // this is a bad conversion sequence, unless we're resolving an overload in C.
2429 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2430 return false;
2431
2432 ExprResult ER = ExprResult{From};
2435 /*Diagnose=*/false,
2436 /*DiagnoseCFAudited=*/false,
2437 /*ConvertRHS=*/false);
2438 ImplicitConversionKind SecondConv;
2439 switch (Conv) {
2440 case Sema::Compatible:
2441 SecondConv = ICK_C_Only_Conversion;
2442 break;
2443 // For our purposes, discarding qualifiers is just as bad as using an
2444 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2445 // qualifiers, as well.
2450 break;
2451 default:
2452 return false;
2453 }
2454
2455 // First can only be an lvalue conversion, so we pretend that this was the
2456 // second conversion. First should already be valid from earlier in the
2457 // function.
2458 SCS.Second = SecondConv;
2459 SCS.setToType(1, ToType);
2460
2461 // Third is Identity, because Second should rank us worse than any other
2462 // conversion. This could also be ICK_Qualification, but it's simpler to just
2463 // lump everything in with the second conversion, and we don't gain anything
2464 // from making this ICK_Qualification.
2465 SCS.Third = ICK_Identity;
2466 SCS.setToType(2, ToType);
2467 return true;
2468}
2469
2470static bool
2472 QualType &ToType,
2473 bool InOverloadResolution,
2475 bool CStyle) {
2476
2477 const RecordType *UT = ToType->getAsUnionType();
2478 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2479 return false;
2480 // The field to initialize within the transparent union.
2481 RecordDecl *UD = UT->getDecl();
2482 // It's compatible if the expression matches any of the fields.
2483 for (const auto *it : UD->fields()) {
2484 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2485 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2486 ToType = it->getType();
2487 return true;
2488 }
2489 }
2490 return false;
2491}
2492
2493bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2494 const BuiltinType *To = ToType->getAs<BuiltinType>();
2495 // All integers are built-in.
2496 if (!To) {
2497 return false;
2498 }
2499
2500 // An rvalue of type char, signed char, unsigned char, short int, or
2501 // unsigned short int can be converted to an rvalue of type int if
2502 // int can represent all the values of the source type; otherwise,
2503 // the source rvalue can be converted to an rvalue of type unsigned
2504 // int (C++ 4.5p1).
2505 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2506 !FromType->isEnumeralType()) {
2507 if ( // We can promote any signed, promotable integer type to an int
2508 (FromType->isSignedIntegerType() ||
2509 // We can promote any unsigned integer type whose size is
2510 // less than int to an int.
2511 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2512 return To->getKind() == BuiltinType::Int;
2513 }
2514
2515 return To->getKind() == BuiltinType::UInt;
2516 }
2517
2518 // C++11 [conv.prom]p3:
2519 // A prvalue of an unscoped enumeration type whose underlying type is not
2520 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2521 // following types that can represent all the values of the enumeration
2522 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2523 // unsigned int, long int, unsigned long int, long long int, or unsigned
2524 // long long int. If none of the types in that list can represent all the
2525 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2526 // type can be converted to an rvalue a prvalue of the extended integer type
2527 // with lowest integer conversion rank (4.13) greater than the rank of long
2528 // long in which all the values of the enumeration can be represented. If
2529 // there are two such extended types, the signed one is chosen.
2530 // C++11 [conv.prom]p4:
2531 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2532 // can be converted to a prvalue of its underlying type. Moreover, if
2533 // integral promotion can be applied to its underlying type, a prvalue of an
2534 // unscoped enumeration type whose underlying type is fixed can also be
2535 // converted to a prvalue of the promoted underlying type.
2536 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2537 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2538 // provided for a scoped enumeration.
2539 if (FromEnumType->getDecl()->isScoped())
2540 return false;
2541
2542 // We can perform an integral promotion to the underlying type of the enum,
2543 // even if that's not the promoted type. Note that the check for promoting
2544 // the underlying type is based on the type alone, and does not consider
2545 // the bitfield-ness of the actual source expression.
2546 if (FromEnumType->getDecl()->isFixed()) {
2547 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2548 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2549 IsIntegralPromotion(nullptr, Underlying, ToType);
2550 }
2551
2552 // We have already pre-calculated the promotion type, so this is trivial.
2553 if (ToType->isIntegerType() &&
2554 isCompleteType(From->getBeginLoc(), FromType))
2555 return Context.hasSameUnqualifiedType(
2556 ToType, FromEnumType->getDecl()->getPromotionType());
2557
2558 // C++ [conv.prom]p5:
2559 // If the bit-field has an enumerated type, it is treated as any other
2560 // value of that type for promotion purposes.
2561 //
2562 // ... so do not fall through into the bit-field checks below in C++.
2563 if (getLangOpts().CPlusPlus)
2564 return false;
2565 }
2566
2567 // C++0x [conv.prom]p2:
2568 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2569 // to an rvalue a prvalue of the first of the following types that can
2570 // represent all the values of its underlying type: int, unsigned int,
2571 // long int, unsigned long int, long long int, or unsigned long long int.
2572 // If none of the types in that list can represent all the values of its
2573 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2574 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2575 // type.
2576 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2577 ToType->isIntegerType()) {
2578 // Determine whether the type we're converting from is signed or
2579 // unsigned.
2580 bool FromIsSigned = FromType->isSignedIntegerType();
2581 uint64_t FromSize = Context.getTypeSize(FromType);
2582
2583 // The types we'll try to promote to, in the appropriate
2584 // order. Try each of these types.
2585 QualType PromoteTypes[6] = {
2586 Context.IntTy, Context.UnsignedIntTy,
2587 Context.LongTy, Context.UnsignedLongTy ,
2588 Context.LongLongTy, Context.UnsignedLongLongTy
2589 };
2590 for (int Idx = 0; Idx < 6; ++Idx) {
2591 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2592 if (FromSize < ToSize ||
2593 (FromSize == ToSize &&
2594 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2595 // We found the type that we can promote to. If this is the
2596 // type we wanted, we have a promotion. Otherwise, no
2597 // promotion.
2598 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2599 }
2600 }
2601 }
2602
2603 // An rvalue for an integral bit-field (9.6) can be converted to an
2604 // rvalue of type int if int can represent all the values of the
2605 // bit-field; otherwise, it can be converted to unsigned int if
2606 // unsigned int can represent all the values of the bit-field. If
2607 // the bit-field is larger yet, no integral promotion applies to
2608 // it. If the bit-field has an enumerated type, it is treated as any
2609 // other value of that type for promotion purposes (C++ 4.5p3).
2610 // FIXME: We should delay checking of bit-fields until we actually perform the
2611 // conversion.
2612 //
2613 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2614 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2615 // bit-fields and those whose underlying type is larger than int) for GCC
2616 // compatibility.
2617 if (From) {
2618 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2619 std::optional<llvm::APSInt> BitWidth;
2620 if (FromType->isIntegralType(Context) &&
2621 (BitWidth =
2622 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2623 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2624 ToSize = Context.getTypeSize(ToType);
2625
2626 // Are we promoting to an int from a bitfield that fits in an int?
2627 if (*BitWidth < ToSize ||
2628 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2629 return To->getKind() == BuiltinType::Int;
2630 }
2631
2632 // Are we promoting to an unsigned int from an unsigned bitfield
2633 // that fits into an unsigned int?
2634 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2635 return To->getKind() == BuiltinType::UInt;
2636 }
2637
2638 return false;
2639 }
2640 }
2641 }
2642
2643 // An rvalue of type bool can be converted to an rvalue of type int,
2644 // with false becoming zero and true becoming one (C++ 4.5p4).
2645 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2646 return true;
2647 }
2648
2649 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2650 // integral type.
2651 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2652 ToType->isIntegerType())
2653 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2654
2655 return false;
2656}
2657
2659 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2660 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2661 /// An rvalue of type float can be converted to an rvalue of type
2662 /// double. (C++ 4.6p1).
2663 if (FromBuiltin->getKind() == BuiltinType::Float &&
2664 ToBuiltin->getKind() == BuiltinType::Double)
2665 return true;
2666
2667 // C99 6.3.1.5p1:
2668 // When a float is promoted to double or long double, or a
2669 // double is promoted to long double [...].
2670 if (!getLangOpts().CPlusPlus &&
2671 (FromBuiltin->getKind() == BuiltinType::Float ||
2672 FromBuiltin->getKind() == BuiltinType::Double) &&
2673 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2674 ToBuiltin->getKind() == BuiltinType::Float128 ||
2675 ToBuiltin->getKind() == BuiltinType::Ibm128))
2676 return true;
2677
2678 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2679 // or not native half types are enabled.
2680 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2681 (ToBuiltin->getKind() == BuiltinType::Float ||
2682 ToBuiltin->getKind() == BuiltinType::Double))
2683 return true;
2684
2685 // Half can be promoted to float.
2686 if (!getLangOpts().NativeHalfType &&
2687 FromBuiltin->getKind() == BuiltinType::Half &&
2688 ToBuiltin->getKind() == BuiltinType::Float)
2689 return true;
2690 }
2691
2692 return false;
2693}
2694
2696 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2697 if (!FromComplex)
2698 return false;
2699
2700 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2701 if (!ToComplex)
2702 return false;
2703
2704 return IsFloatingPointPromotion(FromComplex->getElementType(),
2705 ToComplex->getElementType()) ||
2706 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2707 ToComplex->getElementType());
2708}
2709
2710/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2711/// the pointer type FromPtr to a pointer to type ToPointee, with the
2712/// same type qualifiers as FromPtr has on its pointee type. ToType,
2713/// if non-empty, will be a pointer to ToType that may or may not have
2714/// the right set of qualifiers on its pointee.
2715///
2716static QualType
2718 QualType ToPointee, QualType ToType,
2719 ASTContext &Context,
2720 bool StripObjCLifetime = false) {
2721 assert((FromPtr->getTypeClass() == Type::Pointer ||
2722 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2723 "Invalid similarly-qualified pointer type");
2724
2725 /// Conversions to 'id' subsume cv-qualifier conversions.
2726 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2727 return ToType.getUnqualifiedType();
2728
2729 QualType CanonFromPointee
2730 = Context.getCanonicalType(FromPtr->getPointeeType());
2731 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2732 Qualifiers Quals = CanonFromPointee.getQualifiers();
2733
2734 if (StripObjCLifetime)
2735 Quals.removeObjCLifetime();
2736
2737 // Exact qualifier match -> return the pointer type we're converting to.
2738 if (CanonToPointee.getLocalQualifiers() == Quals) {
2739 // ToType is exactly what we need. Return it.
2740 if (!ToType.isNull())
2741 return ToType.getUnqualifiedType();
2742
2743 // Build a pointer to ToPointee. It has the right qualifiers
2744 // already.
2745 if (isa<ObjCObjectPointerType>(ToType))
2746 return Context.getObjCObjectPointerType(ToPointee);
2747 return Context.getPointerType(ToPointee);
2748 }
2749
2750 // Just build a canonical type that has the right qualifiers.
2751 QualType QualifiedCanonToPointee
2752 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2753
2754 if (isa<ObjCObjectPointerType>(ToType))
2755 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2756 return Context.getPointerType(QualifiedCanonToPointee);
2757}
2758
2760 bool InOverloadResolution,
2761 ASTContext &Context) {
2762 // Handle value-dependent integral null pointer constants correctly.
2763 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2764 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2766 return !InOverloadResolution;
2767
2768 return Expr->isNullPointerConstant(Context,
2769 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2771}
2772
2774 bool InOverloadResolution,
2775 QualType& ConvertedType,
2776 bool &IncompatibleObjC) {
2777 IncompatibleObjC = false;
2778 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2779 IncompatibleObjC))
2780 return true;
2781
2782 // Conversion from a null pointer constant to any Objective-C pointer type.
2783 if (ToType->isObjCObjectPointerType() &&
2784 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2785 ConvertedType = ToType;
2786 return true;
2787 }
2788
2789 // Blocks: Block pointers can be converted to void*.
2790 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2791 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2792 ConvertedType = ToType;
2793 return true;
2794 }
2795 // Blocks: A null pointer constant can be converted to a block
2796 // pointer type.
2797 if (ToType->isBlockPointerType() &&
2798 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2799 ConvertedType = ToType;
2800 return true;
2801 }
2802
2803 // If the left-hand-side is nullptr_t, the right side can be a null
2804 // pointer constant.
2805 if (ToType->isNullPtrType() &&
2806 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2807 ConvertedType = ToType;
2808 return true;
2809 }
2810
2811 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2812 if (!ToTypePtr)
2813 return false;
2814
2815 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2816 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2817 ConvertedType = ToType;
2818 return true;
2819 }
2820
2821 // Beyond this point, both types need to be pointers
2822 // , including objective-c pointers.
2823 QualType ToPointeeType = ToTypePtr->getPointeeType();
2824 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2825 !getLangOpts().ObjCAutoRefCount) {
2826 ConvertedType = BuildSimilarlyQualifiedPointerType(
2827 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2828 Context);
2829 return true;
2830 }
2831 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2832 if (!FromTypePtr)
2833 return false;
2834
2835 QualType FromPointeeType = FromTypePtr->getPointeeType();
2836
2837 // If the unqualified pointee types are the same, this can't be a
2838 // pointer conversion, so don't do all of the work below.
2839 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2840 return false;
2841
2842 // An rvalue of type "pointer to cv T," where T is an object type,
2843 // can be converted to an rvalue of type "pointer to cv void" (C++
2844 // 4.10p2).
2845 if (FromPointeeType->isIncompleteOrObjectType() &&
2846 ToPointeeType->isVoidType()) {
2847 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2848 ToPointeeType,
2849 ToType, Context,
2850 /*StripObjCLifetime=*/true);
2851 return true;
2852 }
2853
2854 // MSVC allows implicit function to void* type conversion.
2855 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2856 ToPointeeType->isVoidType()) {
2857 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2858 ToPointeeType,
2859 ToType, Context);
2860 return true;
2861 }
2862
2863 // When we're overloading in C, we allow a special kind of pointer
2864 // conversion for compatible-but-not-identical pointee types.
2865 if (!getLangOpts().CPlusPlus &&
2866 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2867 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2868 ToPointeeType,
2869 ToType, Context);
2870 return true;
2871 }
2872
2873 // C++ [conv.ptr]p3:
2874 //
2875 // An rvalue of type "pointer to cv D," where D is a class type,
2876 // can be converted to an rvalue of type "pointer to cv B," where
2877 // B is a base class (clause 10) of D. If B is an inaccessible
2878 // (clause 11) or ambiguous (10.2) base class of D, a program that
2879 // necessitates this conversion is ill-formed. The result of the
2880 // conversion is a pointer to the base class sub-object of the
2881 // derived class object. The null pointer value is converted to
2882 // the null pointer value of the destination type.
2883 //
2884 // Note that we do not check for ambiguity or inaccessibility
2885 // here. That is handled by CheckPointerConversion.
2886 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2887 ToPointeeType->isRecordType() &&
2888 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2889 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2890 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2891 ToPointeeType,
2892 ToType, Context);
2893 return true;
2894 }
2895
2896 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2897 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2898 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2899 ToPointeeType,
2900 ToType, Context);
2901 return true;
2902 }
2903
2904 return false;
2905}
2906
2907/// Adopt the given qualifiers for the given type.
2909 Qualifiers TQs = T.getQualifiers();
2910
2911 // Check whether qualifiers already match.
2912 if (TQs == Qs)
2913 return T;
2914
2915 if (Qs.compatiblyIncludes(TQs))
2916 return Context.getQualifiedType(T, Qs);
2917
2918 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2919}
2920
2922 QualType& ConvertedType,
2923 bool &IncompatibleObjC) {
2924 if (!getLangOpts().ObjC)
2925 return false;
2926
2927 // The set of qualifiers on the type we're converting from.
2928 Qualifiers FromQualifiers = FromType.getQualifiers();
2929
2930 // First, we handle all conversions on ObjC object pointer types.
2931 const ObjCObjectPointerType* ToObjCPtr =
2932 ToType->getAs<ObjCObjectPointerType>();
2933 const ObjCObjectPointerType *FromObjCPtr =
2934 FromType->getAs<ObjCObjectPointerType>();
2935
2936 if (ToObjCPtr && FromObjCPtr) {
2937 // If the pointee types are the same (ignoring qualifications),
2938 // then this is not a pointer conversion.
2939 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2940 FromObjCPtr->getPointeeType()))
2941 return false;
2942
2943 // Conversion between Objective-C pointers.
2944 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2945 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2946 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2947 if (getLangOpts().CPlusPlus && LHS && RHS &&
2949 FromObjCPtr->getPointeeType()))
2950 return false;
2951 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2952 ToObjCPtr->getPointeeType(),
2953 ToType, Context);
2954 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2955 return true;
2956 }
2957
2958 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2959 // Okay: this is some kind of implicit downcast of Objective-C
2960 // interfaces, which is permitted. However, we're going to
2961 // complain about it.
2962 IncompatibleObjC = true;
2963 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2964 ToObjCPtr->getPointeeType(),
2965 ToType, Context);
2966 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2967 return true;
2968 }
2969 }
2970 // Beyond this point, both types need to be C pointers or block pointers.
2971 QualType ToPointeeType;
2972 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2973 ToPointeeType = ToCPtr->getPointeeType();
2974 else if (const BlockPointerType *ToBlockPtr =
2975 ToType->getAs<BlockPointerType>()) {
2976 // Objective C++: We're able to convert from a pointer to any object
2977 // to a block pointer type.
2978 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2979 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2980 return true;
2981 }
2982 ToPointeeType = ToBlockPtr->getPointeeType();
2983 }
2984 else if (FromType->getAs<BlockPointerType>() &&
2985 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2986 // Objective C++: We're able to convert from a block pointer type to a
2987 // pointer to any object.
2988 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2989 return true;
2990 }
2991 else
2992 return false;
2993
2994 QualType FromPointeeType;
2995 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2996 FromPointeeType = FromCPtr->getPointeeType();
2997 else if (const BlockPointerType *FromBlockPtr =
2998 FromType->getAs<BlockPointerType>())
2999 FromPointeeType = FromBlockPtr->getPointeeType();
3000 else
3001 return false;
3002
3003 // If we have pointers to pointers, recursively check whether this
3004 // is an Objective-C conversion.
3005 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3006 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3007 IncompatibleObjC)) {
3008 // We always complain about this conversion.
3009 IncompatibleObjC = true;
3010 ConvertedType = Context.getPointerType(ConvertedType);
3011 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3012 return true;
3013 }
3014 // Allow conversion of pointee being objective-c pointer to another one;
3015 // as in I* to id.
3016 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3017 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3018 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3019 IncompatibleObjC)) {
3020
3021 ConvertedType = Context.getPointerType(ConvertedType);
3022 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3023 return true;
3024 }
3025
3026 // If we have pointers to functions or blocks, check whether the only
3027 // differences in the argument and result types are in Objective-C
3028 // pointer conversions. If so, we permit the conversion (but
3029 // complain about it).
3030 const FunctionProtoType *FromFunctionType
3031 = FromPointeeType->getAs<FunctionProtoType>();
3032 const FunctionProtoType *ToFunctionType
3033 = ToPointeeType->getAs<FunctionProtoType>();
3034 if (FromFunctionType && ToFunctionType) {
3035 // If the function types are exactly the same, this isn't an
3036 // Objective-C pointer conversion.
3037 if (Context.getCanonicalType(FromPointeeType)
3038 == Context.getCanonicalType(ToPointeeType))
3039 return false;
3040
3041 // Perform the quick checks that will tell us whether these
3042 // function types are obviously different.
3043 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3044 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3045 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3046 return false;
3047
3048 bool HasObjCConversion = false;
3049 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3050 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3051 // Okay, the types match exactly. Nothing to do.
3052 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3053 ToFunctionType->getReturnType(),
3054 ConvertedType, IncompatibleObjC)) {
3055 // Okay, we have an Objective-C pointer conversion.
3056 HasObjCConversion = true;
3057 } else {
3058 // Function types are too different. Abort.
3059 return false;
3060 }
3061
3062 // Check argument types.
3063 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3064 ArgIdx != NumArgs; ++ArgIdx) {
3065 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3066 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3067 if (Context.getCanonicalType(FromArgType)
3068 == Context.getCanonicalType(ToArgType)) {
3069 // Okay, the types match exactly. Nothing to do.
3070 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3071 ConvertedType, IncompatibleObjC)) {
3072 // Okay, we have an Objective-C pointer conversion.
3073 HasObjCConversion = true;
3074 } else {
3075 // Argument types are too different. Abort.
3076 return false;
3077 }
3078 }
3079
3080 if (HasObjCConversion) {
3081 // We had an Objective-C conversion. Allow this pointer
3082 // conversion, but complain about it.
3083 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3084 IncompatibleObjC = true;
3085 return true;
3086 }
3087 }
3088
3089 return false;
3090}
3091
3093 QualType& ConvertedType) {
3094 QualType ToPointeeType;
3095 if (const BlockPointerType *ToBlockPtr =
3096 ToType->getAs<BlockPointerType>())
3097 ToPointeeType = ToBlockPtr->getPointeeType();
3098 else
3099 return false;
3100
3101 QualType FromPointeeType;
3102 if (const BlockPointerType *FromBlockPtr =
3103 FromType->getAs<BlockPointerType>())
3104 FromPointeeType = FromBlockPtr->getPointeeType();
3105 else
3106 return false;
3107 // We have pointer to blocks, check whether the only
3108 // differences in the argument and result types are in Objective-C
3109 // pointer conversions. If so, we permit the conversion.
3110
3111 const FunctionProtoType *FromFunctionType
3112 = FromPointeeType->getAs<FunctionProtoType>();
3113 const FunctionProtoType *ToFunctionType
3114 = ToPointeeType->getAs<FunctionProtoType>();
3115
3116 if (!FromFunctionType || !ToFunctionType)
3117 return false;
3118
3119 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3120 return true;
3121
3122 // Perform the quick checks that will tell us whether these
3123 // function types are obviously different.
3124 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3125 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3126 return false;
3127
3128 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3129 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3130 if (FromEInfo != ToEInfo)
3131 return false;
3132
3133 bool IncompatibleObjC = false;
3134 if (Context.hasSameType(FromFunctionType->getReturnType(),
3135 ToFunctionType->getReturnType())) {
3136 // Okay, the types match exactly. Nothing to do.
3137 } else {
3138 QualType RHS = FromFunctionType->getReturnType();
3139 QualType LHS = ToFunctionType->getReturnType();
3140 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3141 !RHS.hasQualifiers() && LHS.hasQualifiers())
3142 LHS = LHS.getUnqualifiedType();
3143
3144 if (Context.hasSameType(RHS,LHS)) {
3145 // OK exact match.
3146 } else if (isObjCPointerConversion(RHS, LHS,
3147 ConvertedType, IncompatibleObjC)) {
3148 if (IncompatibleObjC)
3149 return false;
3150 // Okay, we have an Objective-C pointer conversion.
3151 }
3152 else
3153 return false;
3154 }
3155
3156 // Check argument types.
3157 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3158 ArgIdx != NumArgs; ++ArgIdx) {
3159 IncompatibleObjC = false;
3160 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3161 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3162 if (Context.hasSameType(FromArgType, ToArgType)) {
3163 // Okay, the types match exactly. Nothing to do.
3164 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3165 ConvertedType, IncompatibleObjC)) {
3166 if (IncompatibleObjC)
3167 return false;
3168 // Okay, we have an Objective-C pointer conversion.
3169 } else
3170 // Argument types are too different. Abort.
3171 return false;
3172 }
3173
3175 bool CanUseToFPT, CanUseFromFPT;
3176 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3177 CanUseToFPT, CanUseFromFPT,
3178 NewParamInfos))
3179 return false;
3180
3181 ConvertedType = ToType;
3182 return true;
3183}
3184
3185enum {
3194
3195/// Attempts to get the FunctionProtoType from a Type. Handles
3196/// MemberFunctionPointers properly.
3198 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3199 return FPT;
3200
3201 if (auto *MPT = FromType->getAs<MemberPointerType>())
3202 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3203
3204 return nullptr;
3205}
3206
3208 QualType FromType, QualType ToType) {
3209 // If either type is not valid, include no extra info.
3210 if (FromType.isNull() || ToType.isNull()) {
3211 PDiag << ft_default;
3212 return;
3213 }
3214
3215 // Get the function type from the pointers.
3216 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3217 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3218 *ToMember = ToType->castAs<MemberPointerType>();
3219 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3220 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3221 << QualType(FromMember->getClass(), 0);
3222 return;
3223 }
3224 FromType = FromMember->getPointeeType();
3225 ToType = ToMember->getPointeeType();
3226 }
3227
3228 if (FromType->isPointerType())
3229 FromType = FromType->getPointeeType();
3230 if (ToType->isPointerType())
3231 ToType = ToType->getPointeeType();
3232
3233 // Remove references.
3234 FromType = FromType.getNonReferenceType();
3235 ToType = ToType.getNonReferenceType();
3236
3237 // Don't print extra info for non-specialized template functions.
3238 if (FromType->isInstantiationDependentType() &&
3239 !FromType->getAs<TemplateSpecializationType>()) {
3240 PDiag << ft_default;
3241 return;
3242 }
3243
3244 // No extra info for same types.
3245 if (Context.hasSameType(FromType, ToType)) {
3246 PDiag << ft_default;
3247 return;
3248 }
3249
3250 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3251 *ToFunction = tryGetFunctionProtoType(ToType);
3252
3253 // Both types need to be function types.
3254 if (!FromFunction || !ToFunction) {
3255 PDiag << ft_default;
3256 return;
3257 }
3258
3259 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3260 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3261 << FromFunction->getNumParams();
3262 return;
3263 }
3264
3265 // Handle different parameter types.
3266 unsigned ArgPos;
3267 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3268 PDiag << ft_parameter_mismatch << ArgPos + 1
3269 << ToFunction->getParamType(ArgPos)
3270 << FromFunction->getParamType(ArgPos);
3271 return;
3272 }
3273
3274 // Handle different return type.
3275 if (!Context.hasSameType(FromFunction->getReturnType(),
3276 ToFunction->getReturnType())) {
3277 PDiag << ft_return_type << ToFunction->getReturnType()
3278 << FromFunction->getReturnType();
3279 return;
3280 }
3281
3282 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3283 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3284 << FromFunction->getMethodQuals();
3285 return;
3286 }
3287
3288 // Handle exception specification differences on canonical type (in C++17
3289 // onwards).
3290 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3291 ->isNothrow() !=
3292 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3293 ->isNothrow()) {
3294 PDiag << ft_noexcept;
3295 return;
3296 }
3297
3298 // Unable to find a difference, so add no extra info.
3299 PDiag << ft_default;
3300}
3301
3303 ArrayRef<QualType> New, unsigned *ArgPos,
3304 bool Reversed) {
3305 assert(llvm::size(Old) == llvm::size(New) &&
3306 "Can't compare parameters of functions with different number of "
3307 "parameters!");
3308
3309 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3310 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3311 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3312
3313 // Ignore address spaces in pointee type. This is to disallow overloading
3314 // on __ptr32/__ptr64 address spaces.
3315 QualType OldType =
3316 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3317 QualType NewType =
3318 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3319
3320 if (!Context.hasSameType(OldType, NewType)) {
3321 if (ArgPos)
3322 *ArgPos = Idx;
3323 return false;
3324 }
3325 }
3326 return true;
3327}
3328
3330 const FunctionProtoType *NewType,
3331 unsigned *ArgPos, bool Reversed) {
3332 return FunctionParamTypesAreEqual(OldType->param_types(),
3333 NewType->param_types(), ArgPos, Reversed);
3334}
3335
3337 const FunctionDecl *NewFunction,
3338 unsigned *ArgPos,
3339 bool Reversed) {
3340
3341 if (OldFunction->getNumNonObjectParams() !=
3342 NewFunction->getNumNonObjectParams())
3343 return false;
3344
3345 unsigned OldIgnore =
3347 unsigned NewIgnore =
3349
3350 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3351 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3352
3353 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3354 NewPT->param_types().slice(NewIgnore),
3355 ArgPos, Reversed);
3356}
3357
3359 CastKind &Kind,
3360 CXXCastPath& BasePath,
3361 bool IgnoreBaseAccess,
3362 bool Diagnose) {
3363 QualType FromType = From->getType();
3364 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3365
3366 Kind = CK_BitCast;
3367
3368 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3371 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3372 DiagRuntimeBehavior(From->getExprLoc(), From,
3373 PDiag(diag::warn_impcast_bool_to_null_pointer)
3374 << ToType << From->getSourceRange());
3375 else if (!isUnevaluatedContext())
3376 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3377 << ToType << From->getSourceRange();
3378 }
3379 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3380 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3381 QualType FromPointeeType = FromPtrType->getPointeeType(),
3382 ToPointeeType = ToPtrType->getPointeeType();
3383
3384 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3385 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3386 // We must have a derived-to-base conversion. Check an
3387 // ambiguous or inaccessible conversion.
3388 unsigned InaccessibleID = 0;
3389 unsigned AmbiguousID = 0;
3390 if (Diagnose) {
3391 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3392 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3393 }
3394 if (CheckDerivedToBaseConversion(
3395 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3396 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3397 &BasePath, IgnoreBaseAccess))
3398 return true;
3399
3400 // The conversion was successful.
3401 Kind = CK_DerivedToBase;
3402 }
3403
3404 if (Diagnose && !IsCStyleOrFunctionalCast &&
3405 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3406 assert(getLangOpts().MSVCCompat &&
3407 "this should only be possible with MSVCCompat!");
3408 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3409 << From->getSourceRange();
3410 }
3411 }
3412 } else if (const ObjCObjectPointerType *ToPtrType =
3413 ToType->getAs<ObjCObjectPointerType>()) {
3414 if (const ObjCObjectPointerType *FromPtrType =
3415 FromType->getAs<ObjCObjectPointerType>()) {
3416 // Objective-C++ conversions are always okay.
3417 // FIXME: We should have a different class of conversions for the
3418 // Objective-C++ implicit conversions.
3419 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3420 return false;
3421 } else if (FromType->isBlockPointerType()) {
3422 Kind = CK_BlockPointerToObjCPointerCast;
3423 } else {
3424 Kind = CK_CPointerToObjCPointerCast;
3425 }
3426 } else if (ToType->isBlockPointerType()) {
3427 if (!FromType->isBlockPointerType())
3428 Kind = CK_AnyPointerToBlockPointerCast;
3429 }
3430
3431 // We shouldn't fall into this case unless it's valid for other
3432 // reasons.
3434 Kind = CK_NullToPointer;
3435
3436 return false;
3437}
3438
3440 QualType ToType,
3441 bool InOverloadResolution,
3442 QualType &ConvertedType) {
3443 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3444 if (!ToTypePtr)
3445 return false;
3446
3447 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3448 if (From->isNullPointerConstant(Context,
3449 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3451 ConvertedType = ToType;
3452 return true;
3453 }
3454
3455 // Otherwise, both types have to be member pointers.
3456 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3457 if (!FromTypePtr)
3458 return false;
3459
3460 // A pointer to member of B can be converted to a pointer to member of D,
3461 // where D is derived from B (C++ 4.11p2).
3462 QualType FromClass(FromTypePtr->getClass(), 0);
3463 QualType ToClass(ToTypePtr->getClass(), 0);
3464
3465 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3466 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3467 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3468 ToClass.getTypePtr());
3469 return true;
3470 }
3471
3472 return false;
3473}
3474
3476 CastKind &Kind,
3477 CXXCastPath &BasePath,
3478 bool IgnoreBaseAccess) {
3479 QualType FromType = From->getType();
3480 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3481 if (!FromPtrType) {
3482 // This must be a null pointer to member pointer conversion
3483 assert(From->isNullPointerConstant(Context,
3485 "Expr must be null pointer constant!");
3486 Kind = CK_NullToMemberPointer;
3487 return false;
3488 }
3489
3490 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3491 assert(ToPtrType && "No member pointer cast has a target type "
3492 "that is not a member pointer.");
3493
3494 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3495 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3496
3497 // FIXME: What about dependent types?
3498 assert(FromClass->isRecordType() && "Pointer into non-class.");
3499 assert(ToClass->isRecordType() && "Pointer into non-class.");
3500
3501 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3502 /*DetectVirtual=*/true);
3503 bool DerivationOkay =
3504 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3505 assert(DerivationOkay &&
3506 "Should not have been called if derivation isn't OK.");
3507 (void)DerivationOkay;
3508
3509 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3510 getUnqualifiedType())) {
3511 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3512 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3513 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3514 return true;
3515 }
3516
3517 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3518 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3519 << FromClass << ToClass << QualType(VBase, 0)
3520 << From->getSourceRange();
3521 return true;
3522 }
3523
3524 if (!IgnoreBaseAccess)
3525 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3526 Paths.front(),
3527 diag::err_downcast_from_inaccessible_base);
3528
3529 // Must be a base to derived member conversion.
3530 BuildBasePathArray(Paths, BasePath);
3531 Kind = CK_BaseToDerivedMemberPointer;
3532 return false;
3533}
3534
3535/// Determine whether the lifetime conversion between the two given
3536/// qualifiers sets is nontrivial.
3538 Qualifiers ToQuals) {
3539 // Converting anything to const __unsafe_unretained is trivial.
3540 if (ToQuals.hasConst() &&
3542 return false;
3543
3544 return true;
3545}
3546
3547/// Perform a single iteration of the loop for checking if a qualification
3548/// conversion is valid.
3549///
3550/// Specifically, check whether any change between the qualifiers of \p
3551/// FromType and \p ToType is permissible, given knowledge about whether every
3552/// outer layer is const-qualified.
3554 bool CStyle, bool IsTopLevel,
3555 bool &PreviousToQualsIncludeConst,
3556 bool &ObjCLifetimeConversion) {
3557 Qualifiers FromQuals = FromType.getQualifiers();
3558 Qualifiers ToQuals = ToType.getQualifiers();
3559
3560 // Ignore __unaligned qualifier.
3561 FromQuals.removeUnaligned();
3562
3563 // Objective-C ARC:
3564 // Check Objective-C lifetime conversions.
3565 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3566 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3567 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3568 ObjCLifetimeConversion = true;
3569 FromQuals.removeObjCLifetime();
3570 ToQuals.removeObjCLifetime();
3571 } else {
3572 // Qualification conversions cannot cast between different
3573 // Objective-C lifetime qualifiers.
3574 return false;
3575 }
3576 }
3577
3578 // Allow addition/removal of GC attributes but not changing GC attributes.
3579 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3580 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3581 FromQuals.removeObjCGCAttr();
3582 ToQuals.removeObjCGCAttr();
3583 }
3584
3585 // -- for every j > 0, if const is in cv 1,j then const is in cv
3586 // 2,j, and similarly for volatile.
3587 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3588 return false;
3589
3590 // If address spaces mismatch:
3591 // - in top level it is only valid to convert to addr space that is a
3592 // superset in all cases apart from C-style casts where we allow
3593 // conversions between overlapping address spaces.
3594 // - in non-top levels it is not a valid conversion.
3595 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3596 (!IsTopLevel ||
3597 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3598 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3599 return false;
3600
3601 // -- if the cv 1,j and cv 2,j are different, then const is in
3602 // every cv for 0 < k < j.
3603 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3604 !PreviousToQualsIncludeConst)
3605 return false;
3606
3607 // The following wording is from C++20, where the result of the conversion
3608 // is T3, not T2.
3609 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3610 // "array of unknown bound of"
3611 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3612 return false;
3613
3614 // -- if the resulting P3,i is different from P1,i [...], then const is
3615 // added to every cv 3_k for 0 < k < i.
3616 if (!CStyle && FromType->isConstantArrayType() &&
3617 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3618 return false;
3619
3620 // Keep track of whether all prior cv-qualifiers in the "to" type
3621 // include const.
3622 PreviousToQualsIncludeConst =
3623 PreviousToQualsIncludeConst && ToQuals.hasConst();
3624 return true;
3625}
3626
3627bool
3629 bool CStyle, bool &ObjCLifetimeConversion) {
3630 FromType = Context.getCanonicalType(FromType);
3631 ToType = Context.getCanonicalType(ToType);
3632 ObjCLifetimeConversion = false;
3633
3634 // If FromType and ToType are the same type, this is not a
3635 // qualification conversion.
3636 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3637 return false;
3638
3639 // (C++ 4.4p4):
3640 // A conversion can add cv-qualifiers at levels other than the first
3641 // in multi-level pointers, subject to the following rules: [...]
3642 bool PreviousToQualsIncludeConst = true;
3643 bool UnwrappedAnyPointer = false;
3644 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3646 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3647 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3648 return false;
3649 UnwrappedAnyPointer = true;
3650 }
3651
3652 // We are left with FromType and ToType being the pointee types
3653 // after unwrapping the original FromType and ToType the same number
3654 // of times. If we unwrapped any pointers, and if FromType and
3655 // ToType have the same unqualified type (since we checked
3656 // qualifiers above), then this is a qualification conversion.
3657 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3658}
3659
3660/// - Determine whether this is a conversion from a scalar type to an
3661/// atomic type.
3662///
3663/// If successful, updates \c SCS's second and third steps in the conversion
3664/// sequence to finish the conversion.
3665static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3666 bool InOverloadResolution,
3668 bool CStyle) {
3669 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3670 if (!ToAtomic)
3671 return false;
3672
3674 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3675 InOverloadResolution, InnerSCS,
3676 CStyle, /*AllowObjCWritebackConversion=*/false))
3677 return false;
3678
3679 SCS.Second = InnerSCS.Second;
3680 SCS.setToType(1, InnerSCS.getToType(1));
3681 SCS.Third = InnerSCS.Third;
3684 SCS.setToType(2, InnerSCS.getToType(2));
3685 return true;
3686}
3687
3689 CXXConstructorDecl *Constructor,
3690 QualType Type) {
3691 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3692 if (CtorType->getNumParams() > 0) {
3693 QualType FirstArg = CtorType->getParamType(0);
3694 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3695 return true;
3696 }
3697 return false;
3698}
3699
3700static OverloadingResult
3702 CXXRecordDecl *To,
3704 OverloadCandidateSet &CandidateSet,
3705 bool AllowExplicit) {
3707 for (auto *D : S.LookupConstructors(To)) {
3708 auto Info = getConstructorInfo(D);
3709 if (!Info)
3710 continue;
3711
3712 bool Usable = !Info.Constructor->isInvalidDecl() &&
3713 S.isInitListConstructor(Info.Constructor);
3714 if (Usable) {
3715 bool SuppressUserConversions = false;
3716 if (Info.ConstructorTmpl)
3717 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3718 /*ExplicitArgs*/ nullptr, From,
3719 CandidateSet, SuppressUserConversions,
3720 /*PartialOverloading*/ false,
3721 AllowExplicit);
3722 else
3723 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3724 CandidateSet, SuppressUserConversions,
3725 /*PartialOverloading*/ false, AllowExplicit);
3726 }
3727 }
3728
3729 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3730
3732 switch (auto Result =
3733 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3734 case OR_Deleted:
3735 case OR_Success: {
3736 // Record the standard conversion we used and the conversion function.
3737 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3738 QualType ThisType = Constructor->getFunctionObjectParameterType();
3739 // Initializer lists don't have conversions as such.
3741 User.HadMultipleCandidates = HadMultipleCandidates;
3742 User.ConversionFunction = Constructor;
3743 User.FoundConversionFunction = Best->FoundDecl;
3745 User.After.setFromType(ThisType);
3746 User.After.setAllToTypes(ToType);
3747 return Result;
3748 }
3749
3751 return OR_No_Viable_Function;
3752 case OR_Ambiguous:
3753 return OR_Ambiguous;
3754 }
3755
3756 llvm_unreachable("Invalid OverloadResult!");
3757}
3758
3759/// Determines whether there is a user-defined conversion sequence
3760/// (C++ [over.ics.user]) that converts expression From to the type
3761/// ToType. If such a conversion exists, User will contain the
3762/// user-defined conversion sequence that performs such a conversion
3763/// and this routine will return true. Otherwise, this routine returns
3764/// false and User is unspecified.
3765///
3766/// \param AllowExplicit true if the conversion should consider C++0x
3767/// "explicit" conversion functions as well as non-explicit conversion
3768/// functions (C++0x [class.conv.fct]p2).
3769///
3770/// \param AllowObjCConversionOnExplicit true if the conversion should
3771/// allow an extra Objective-C pointer conversion on uses of explicit
3772/// constructors. Requires \c AllowExplicit to also be set.
3773static OverloadingResult
3776 OverloadCandidateSet &CandidateSet,
3777 AllowedExplicit AllowExplicit,
3778 bool AllowObjCConversionOnExplicit) {
3779 assert(AllowExplicit != AllowedExplicit::None ||
3780 !AllowObjCConversionOnExplicit);
3782
3783 // Whether we will only visit constructors.
3784 bool ConstructorsOnly = false;
3785
3786 // If the type we are conversion to is a class type, enumerate its
3787 // constructors.
3788 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3789 // C++ [over.match.ctor]p1:
3790 // When objects of class type are direct-initialized (8.5), or
3791 // copy-initialized from an expression of the same or a
3792 // derived class type (8.5), overload resolution selects the
3793 // constructor. [...] For copy-initialization, the candidate
3794 // functions are all the converting constructors (12.3.1) of
3795 // that class. The argument list is the expression-list within
3796 // the parentheses of the initializer.
3797 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3798 (From->getType()->getAs<RecordType>() &&
3799 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3800 ConstructorsOnly = true;
3801
3802 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3803 // We're not going to find any constructors.
3804 } else if (CXXRecordDecl *ToRecordDecl
3805 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3806
3807 Expr **Args = &From;
3808 unsigned NumArgs = 1;
3809 bool ListInitializing = false;
3810 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3811 // But first, see if there is an init-list-constructor that will work.
3813 S, From, ToType, ToRecordDecl, User, CandidateSet,
3814 AllowExplicit == AllowedExplicit::All);
3816 return Result;
3817 // Never mind.
3818 CandidateSet.clear(
3820
3821 // If we're list-initializing, we pass the individual elements as
3822 // arguments, not the entire list.
3823 Args = InitList->getInits();
3824 NumArgs = InitList->getNumInits();
3825 ListInitializing = true;
3826 }
3827
3828 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3829 auto Info = getConstructorInfo(D);
3830 if (!Info)
3831 continue;
3832
3833 bool Usable = !Info.Constructor->isInvalidDecl();
3834 if (!ListInitializing)
3835 Usable = Usable && Info.Constructor->isConvertingConstructor(
3836 /*AllowExplicit*/ true);
3837 if (Usable) {
3838 bool SuppressUserConversions = !ConstructorsOnly;
3839 // C++20 [over.best.ics.general]/4.5:
3840 // if the target is the first parameter of a constructor [of class
3841 // X] and the constructor [...] is a candidate by [...] the second
3842 // phase of [over.match.list] when the initializer list has exactly
3843 // one element that is itself an initializer list, [...] and the
3844 // conversion is to X or reference to cv X, user-defined conversion
3845 // sequences are not cnosidered.
3846 if (SuppressUserConversions && ListInitializing) {
3847 SuppressUserConversions =
3848 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3849 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3850 ToType);
3851 }
3852 if (Info.ConstructorTmpl)
3854 Info.ConstructorTmpl, Info.FoundDecl,
3855 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3856 CandidateSet, SuppressUserConversions,
3857 /*PartialOverloading*/ false,
3858 AllowExplicit == AllowedExplicit::All);
3859 else
3860 // Allow one user-defined conversion when user specifies a
3861 // From->ToType conversion via an static cast (c-style, etc).
3862 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3863 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3864 SuppressUserConversions,
3865 /*PartialOverloading*/ false,
3866 AllowExplicit == AllowedExplicit::All);
3867 }
3868 }
3869 }
3870 }
3871
3872 // Enumerate conversion functions, if we're allowed to.
3873 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3874 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3875 // No conversion functions from incomplete types.
3876 } else if (const RecordType *FromRecordType =
3877 From->getType()->getAs<RecordType>()) {
3878 if (CXXRecordDecl *FromRecordDecl
3879 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3880 // Add all of the conversion functions as candidates.
3881 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3882 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3883 DeclAccessPair FoundDecl = I.getPair();
3884 NamedDecl *D = FoundDecl.getDecl();
3885 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3886 if (isa<UsingShadowDecl>(D))
3887 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3888
3889 CXXConversionDecl *Conv;
3890 FunctionTemplateDecl *ConvTemplate;
3891 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3892 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3893 else
3894 Conv = cast<CXXConversionDecl>(D);
3895
3896 if (ConvTemplate)
3898 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3899 CandidateSet, AllowObjCConversionOnExplicit,
3900 AllowExplicit != AllowedExplicit::None);
3901 else
3902 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3903 CandidateSet, AllowObjCConversionOnExplicit,
3904 AllowExplicit != AllowedExplicit::None);
3905 }
3906 }
3907 }
3908
3909 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3910
3912 switch (auto Result =
3913 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3914 case OR_Success:
3915 case OR_Deleted:
3916 // Record the standard conversion we used and the conversion function.
3917 if (CXXConstructorDecl *Constructor
3918 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3919 // C++ [over.ics.user]p1:
3920 // If the user-defined conversion is specified by a
3921 // constructor (12.3.1), the initial standard conversion
3922 // sequence converts the source type to the type required by
3923 // the argument of the constructor.
3924 //
3925 if (isa<InitListExpr>(From)) {
3926 // Initializer lists don't have conversions as such.
3928 } else {
3929 if (Best->Conversions[0].isEllipsis())
3930 User.EllipsisConversion = true;
3931 else {
3932 User.Before = Best->Conversions[0].Standard;
3933 User.EllipsisConversion = false;
3934 }
3935 }
3936 User.HadMultipleCandidates = HadMultipleCandidates;
3937 User.ConversionFunction = Constructor;
3938 User.FoundConversionFunction = Best->FoundDecl;
3940 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3941 User.After.setAllToTypes(ToType);
3942 return Result;
3943 }
3944 if (CXXConversionDecl *Conversion
3945 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3946 // C++ [over.ics.user]p1:
3947 //
3948 // [...] If the user-defined conversion is specified by a
3949 // conversion function (12.3.2), the initial standard
3950 // conversion sequence converts the source type to the
3951 // implicit object parameter of the conversion function.
3952 User.Before = Best->Conversions[0].Standard;
3953 User.HadMultipleCandidates = HadMultipleCandidates;
3954 User.ConversionFunction = Conversion;
3955 User.FoundConversionFunction = Best->FoundDecl;
3956 User.EllipsisConversion = false;
3957
3958 // C++ [over.ics.user]p2:
3959 // The second standard conversion sequence converts the
3960 // result of the user-defined conversion to the target type
3961 // for the sequence. Since an implicit conversion sequence
3962 // is an initialization, the special rules for
3963 // initialization by user-defined conversion apply when
3964 // selecting the best user-defined conversion for a
3965 // user-defined conversion sequence (see 13.3.3 and
3966 // 13.3.3.1).
3967 User.After = Best->FinalConversion;
3968 return Result;
3969 }
3970 llvm_unreachable("Not a constructor or conversion function?");
3971
3973 return OR_No_Viable_Function;
3974
3975 case OR_Ambiguous:
3976 return OR_Ambiguous;
3977 }
3978
3979 llvm_unreachable("Invalid OverloadResult!");
3980}
3981
3982bool
3985 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3987 OverloadingResult OvResult =
3988 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3989 CandidateSet, AllowedExplicit::None, false);
3990
3991 if (!(OvResult == OR_Ambiguous ||
3992 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3993 return false;
3994
3995 auto Cands = CandidateSet.CompleteCandidates(
3996 *this,
3998 From);
3999 if (OvResult == OR_Ambiguous)
4000 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4001 << From->getType() << ToType << From->getSourceRange();
4002 else { // OR_No_Viable_Function && !CandidateSet.empty()
4003 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4004 diag::err_typecheck_nonviable_condition_incomplete,
4005 From->getType(), From->getSourceRange()))
4006 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4007 << false << From->getType() << From->getSourceRange() << ToType;
4008 }
4009
4010 CandidateSet.NoteCandidates(
4011 *this, From, Cands);
4012 return true;
4013}
4014
4015// Helper for compareConversionFunctions that gets the FunctionType that the
4016// conversion-operator return value 'points' to, or nullptr.
4017static const FunctionType *
4019 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4020 const PointerType *RetPtrTy =
4021 ConvFuncTy->getReturnType()->getAs<PointerType>();
4022
4023 if (!RetPtrTy)
4024 return nullptr;
4025
4026 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4027}
4028
4029/// Compare the user-defined conversion functions or constructors
4030/// of two user-defined conversion sequences to determine whether any ordering
4031/// is possible.
4034 FunctionDecl *Function2) {
4035 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4036 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4037 if (!Conv1 || !Conv2)
4039
4040 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4042
4043 // Objective-C++:
4044 // If both conversion functions are implicitly-declared conversions from
4045 // a lambda closure type to a function pointer and a block pointer,
4046 // respectively, always prefer the conversion to a function pointer,
4047 // because the function pointer is more lightweight and is more likely
4048 // to keep code working.
4049 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4050 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4051 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4052 if (Block1 != Block2)
4053 return Block1 ? ImplicitConversionSequence::Worse
4055 }
4056
4057 // In order to support multiple calling conventions for the lambda conversion
4058 // operator (such as when the free and member function calling convention is
4059 // different), prefer the 'free' mechanism, followed by the calling-convention
4060 // of operator(). The latter is in place to support the MSVC-like solution of
4061 // defining ALL of the possible conversions in regards to calling-convention.
4062 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4063 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4064
4065 if (Conv1FuncRet && Conv2FuncRet &&
4066 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4067 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4068 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4069
4070 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4071 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4072
4073 CallingConv CallOpCC =
4074 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4076 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4078 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4079
4080 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4081 for (CallingConv CC : PrefOrder) {
4082 if (Conv1CC == CC)
4084 if (Conv2CC == CC)
4086 }
4087 }
4088
4090}
4091
4093 const ImplicitConversionSequence &ICS) {
4095 (ICS.isUserDefined() &&
4097}
4098
4099/// CompareImplicitConversionSequences - Compare two implicit
4100/// conversion sequences to determine whether one is better than the
4101/// other or if they are indistinguishable (C++ 13.3.3.2).
4104 const ImplicitConversionSequence& ICS1,
4105 const ImplicitConversionSequence& ICS2)
4106{
4107 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4108 // conversion sequences (as defined in 13.3.3.1)
4109 // -- a standard conversion sequence (13.3.3.1.1) is a better
4110 // conversion sequence than a user-defined conversion sequence or
4111 // an ellipsis conversion sequence, and
4112 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4113 // conversion sequence than an ellipsis conversion sequence
4114 // (13.3.3.1.3).
4115 //
4116 // C++0x [over.best.ics]p10:
4117 // For the purpose of ranking implicit conversion sequences as
4118 // described in 13.3.3.2, the ambiguous conversion sequence is
4119 // treated as a user-defined sequence that is indistinguishable
4120 // from any other user-defined conversion sequence.
4121
4122 // String literal to 'char *' conversion has been deprecated in C++03. It has
4123 // been removed from C++11. We still accept this conversion, if it happens at
4124 // the best viable function. Otherwise, this conversion is considered worse
4125 // than ellipsis conversion. Consider this as an extension; this is not in the
4126 // standard. For example:
4127 //
4128 // int &f(...); // #1
4129 // void f(char*); // #2
4130 // void g() { int &r = f("foo"); }
4131 //
4132 // In C++03, we pick #2 as the best viable function.
4133 // In C++11, we pick #1 as the best viable function, because ellipsis
4134 // conversion is better than string-literal to char* conversion (since there
4135 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4136 // convert arguments, #2 would be the best viable function in C++11.
4137 // If the best viable function has this conversion, a warning will be issued
4138 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4139
4140 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4143 // Ill-formedness must not differ
4144 ICS1.isBad() == ICS2.isBad())
4148
4149 if (ICS1.getKindRank() < ICS2.getKindRank())
4151 if (ICS2.getKindRank() < ICS1.getKindRank())
4153
4154 // The following checks require both conversion sequences to be of
4155 // the same kind.
4156 if (ICS1.getKind() != ICS2.getKind())
4158
4161
4162 // Two implicit conversion sequences of the same form are
4163 // indistinguishable conversion sequences unless one of the
4164 // following rules apply: (C++ 13.3.3.2p3):
4165
4166 // List-initialization sequence L1 is a better conversion sequence than
4167 // list-initialization sequence L2 if:
4168 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4169 // if not that,
4170 // — L1 and L2 convert to arrays of the same element type, and either the
4171 // number of elements n_1 initialized by L1 is less than the number of
4172 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4173 // an array of unknown bound and L1 does not,
4174 // even if one of the other rules in this paragraph would otherwise apply.
4175 if (!ICS1.isBad()) {
4176 bool StdInit1 = false, StdInit2 = false;
4179 nullptr);
4182 nullptr);
4183 if (StdInit1 != StdInit2)
4184 return StdInit1 ? ImplicitConversionSequence::Better
4186
4189 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4191 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4193 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4194 CAT2->getElementType())) {
4195 // Both to arrays of the same element type
4196 if (CAT1->getSize() != CAT2->getSize())
4197 // Different sized, the smaller wins
4198 return CAT1->getSize().ult(CAT2->getSize())
4203 // One is incomplete, it loses
4207 }
4208 }
4209 }
4210
4211 if (ICS1.isStandard())
4212 // Standard conversion sequence S1 is a better conversion sequence than
4213 // standard conversion sequence S2 if [...]
4215 ICS1.Standard, ICS2.Standard);
4216 else if (ICS1.isUserDefined()) {
4217 // User-defined conversion sequence U1 is a better conversion
4218 // sequence than another user-defined conversion sequence U2 if
4219 // they contain the same user-defined conversion function or
4220 // constructor and if the second standard conversion sequence of
4221 // U1 is better than the second standard conversion sequence of
4222 // U2 (C++ 13.3.3.2p3).
4226 ICS1.UserDefined.After,
4227 ICS2.UserDefined.After);
4228 else
4232 }
4233
4234 return Result;
4235}
4236
4237// Per 13.3.3.2p3, compare the given standard conversion sequences to
4238// determine if one is a proper subset of the other.
4241 const StandardConversionSequence& SCS1,
4242 const StandardConversionSequence& SCS2) {
4245
4246 // the identity conversion sequence is considered to be a subsequence of
4247 // any non-identity conversion sequence
4248 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4250 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4252
4253 if (SCS1.Second != SCS2.Second) {
4254 if (SCS1.Second == ICK_Identity)
4256 else if (SCS2.Second == ICK_Identity)
4258 else
4260 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4262
4263 if (SCS1.Third == SCS2.Third) {
4264 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4266 }
4267
4268 if (SCS1.Third == ICK_Identity)
4272
4273 if (SCS2.Third == ICK_Identity)
4277
4279}
4280
4281/// Determine whether one of the given reference bindings is better
4282/// than the other based on what kind of bindings they are.
4283static bool
4285 const StandardConversionSequence &SCS2) {
4286 // C++0x [over.ics.rank]p3b4:
4287 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4288 // implicit object parameter of a non-static member function declared
4289 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4290 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4291 // lvalue reference to a function lvalue and S2 binds an rvalue
4292 // reference*.
4293 //
4294 // FIXME: Rvalue references. We're going rogue with the above edits,
4295 // because the semantics in the current C++0x working paper (N3225 at the
4296 // time of this writing) break the standard definition of std::forward
4297 // and std::reference_wrapper when dealing with references to functions.
4298 // Proposed wording changes submitted to CWG for consideration.
4301 return false;
4302
4303 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4304 SCS2.IsLvalueReference) ||
4307}
4308
4310 None,
4313};
4314
4315/// Returns kind of fixed enum promotion the \a SCS uses.
4316static FixedEnumPromotion
4318
4319 if (SCS.Second != ICK_Integral_Promotion)
4320 return FixedEnumPromotion::None;
4321
4322 QualType FromType = SCS.getFromType();
4323 if (!FromType->isEnumeralType())
4324 return FixedEnumPromotion::None;
4325
4326 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4327 if (!Enum->isFixed())
4328 return FixedEnumPromotion::None;
4329
4330 QualType UnderlyingType = Enum->getIntegerType();
4331 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4332 return FixedEnumPromotion::ToUnderlyingType;
4333
4334 return FixedEnumPromotion::ToPromotedUnderlyingType;
4335}
4336
4337/// CompareStandardConversionSequences - Compare two standard
4338/// conversion sequences to determine whether one is better than the
4339/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4342 const StandardConversionSequence& SCS1,
4343 const StandardConversionSequence& SCS2)
4344{
4345 // Standard conversion sequence S1 is a better conversion sequence
4346 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4347
4348 // -- S1 is a proper subsequence of S2 (comparing the conversion
4349 // sequences in the canonical form defined by 13.3.3.1.1,
4350 // excluding any Lvalue Transformation; the identity conversion
4351 // sequence is considered to be a subsequence of any
4352 // non-identity conversion sequence) or, if not that,
4355 return CK;
4356
4357 // -- the rank of S1 is better than the rank of S2 (by the rules
4358 // defined below), or, if not that,
4359 ImplicitConversionRank Rank1 = SCS1.getRank();
4360 ImplicitConversionRank Rank2 = SCS2.getRank();
4361 if (Rank1 < Rank2)
4363 else if (Rank2 < Rank1)
4365
4366 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4367 // are indistinguishable unless one of the following rules
4368 // applies:
4369
4370 // A conversion that is not a conversion of a pointer, or
4371 // pointer to member, to bool is better than another conversion
4372 // that is such a conversion.
4374 return SCS2.isPointerConversionToBool()
4377
4378 // C++14 [over.ics.rank]p4b2:
4379 // This is retroactively applied to C++11 by CWG 1601.
4380 //
4381 // A conversion that promotes an enumeration whose underlying type is fixed
4382 // to its underlying type is better than one that promotes to the promoted
4383 // underlying type, if the two are different.
4386 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4387 FEP1 != FEP2)
4388 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4391
4392 // C++ [over.ics.rank]p4b2:
4393 //
4394 // If class B is derived directly or indirectly from class A,
4395 // conversion of B* to A* is better than conversion of B* to
4396 // void*, and conversion of A* to void* is better than conversion
4397 // of B* to void*.
4398 bool SCS1ConvertsToVoid
4400 bool SCS2ConvertsToVoid
4402 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4403 // Exactly one of the conversion sequences is a conversion to
4404 // a void pointer; it's the worse conversion.
4405 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4407 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4408 // Neither conversion sequence converts to a void pointer; compare
4409 // their derived-to-base conversions.
4411 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4412 return DerivedCK;
4413 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4414 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4415 // Both conversion sequences are conversions to void
4416 // pointers. Compare the source types to determine if there's an
4417 // inheritance relationship in their sources.
4418 QualType FromType1 = SCS1.getFromType();
4419 QualType FromType2 = SCS2.getFromType();
4420
4421 // Adjust the types we're converting from via the array-to-pointer
4422 // conversion, if we need to.
4423 if (SCS1.First == ICK_Array_To_Pointer)
4424 FromType1 = S.Context.getArrayDecayedType(FromType1);
4425 if (SCS2.First == ICK_Array_To_Pointer)
4426 FromType2 = S.Context.getArrayDecayedType(FromType2);
4427
4428 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4429 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4430
4431 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4433 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4435
4436 // Objective-C++: If one interface is more specific than the
4437 // other, it is the better one.
4438 const ObjCObjectPointerType* FromObjCPtr1
4439 = FromType1->getAs<ObjCObjectPointerType>();
4440 const ObjCObjectPointerType* FromObjCPtr2
4441 = FromType2->getAs<ObjCObjectPointerType>();
4442 if (FromObjCPtr1 && FromObjCPtr2) {
4443 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4444 FromObjCPtr2);
4445 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4446 FromObjCPtr1);
4447 if (AssignLeft != AssignRight) {
4448 return AssignLeft? ImplicitConversionSequence::Better
4450 }
4451 }
4452 }
4453
4454 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4455 // Check for a better reference binding based on the kind of bindings.
4456 if (isBetterReferenceBindingKind(SCS1, SCS2))
4458 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4460 }
4461
4462 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4463 // bullet 3).
4465 = CompareQualificationConversions(S, SCS1, SCS2))
4466 return QualCK;
4467
4468 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4469 // C++ [over.ics.rank]p3b4:
4470 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4471 // which the references refer are the same type except for
4472 // top-level cv-qualifiers, and the type to which the reference
4473 // initialized by S2 refers is more cv-qualified than the type
4474 // to which the reference initialized by S1 refers.
4475 QualType T1 = SCS1.getToType(2);
4476 QualType T2 = SCS2.getToType(2);
4477 T1 = S.Context.getCanonicalType(T1);
4478 T2 = S.Context.getCanonicalType(T2);
4479 Qualifiers T1Quals, T2Quals;
4480 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4481 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4482 if (UnqualT1 == UnqualT2) {
4483 // Objective-C++ ARC: If the references refer to objects with different
4484 // lifetimes, prefer bindings that don't change lifetime.
4490 }
4491
4492 // If the type is an array type, promote the element qualifiers to the
4493 // type for comparison.
4494 if (isa<ArrayType>(T1) && T1Quals)
4495 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4496 if (isa<ArrayType>(T2) && T2Quals)
4497 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4498 if (T2.isMoreQualifiedThan(T1))
4500 if (T1.isMoreQualifiedThan(T2))
4502 }
4503 }
4504
4505 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4506 // floating-to-integral conversion if the integral conversion
4507 // is between types of the same size.
4508 // For example:
4509 // void f(float);
4510 // void f(int);
4511 // int main {
4512 // long a;
4513 // f(a);
4514 // }
4515 // Here, MSVC will call f(int) instead of generating a compile error
4516 // as clang will do in standard mode.
4517 if (S.getLangOpts().MSVCCompat &&
4520 SCS2.Second == ICK_Floating_Integral &&
4521 S.Context.getTypeSize(SCS1.getFromType()) ==
4522 S.Context.getTypeSize(SCS1.getToType(2)))
4524
4525 // Prefer a compatible vector conversion over a lax vector conversion
4526 // For example:
4527 //
4528 // typedef float __v4sf __attribute__((__vector_size__(16)));
4529 // void f(vector float);
4530 // void f(vector signed int);
4531 // int main() {
4532 // __v4sf a;
4533 // f(a);
4534 // }
4535 // Here, we'd like to choose f(vector float) and not
4536 // report an ambiguous call error
4537 if (SCS1.Second == ICK_Vector_Conversion &&
4538 SCS2.Second == ICK_Vector_Conversion) {
4539 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4540 SCS1.getFromType(), SCS1.getToType(2));
4541 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4542 SCS2.getFromType(), SCS2.getToType(2));
4543
4544 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4545 return SCS1IsCompatibleVectorConversion
4548 }
4549
4550 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4552 bool SCS1IsCompatibleSVEVectorConversion =
4554 bool SCS2IsCompatibleSVEVectorConversion =
4556
4557 if (SCS1IsCompatibleSVEVectorConversion !=
4558 SCS2IsCompatibleSVEVectorConversion)
4559 return SCS1IsCompatibleSVEVectorConversion
4562 }
4563
4564 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4566 bool SCS1IsCompatibleRVVVectorConversion =
4568 bool SCS2IsCompatibleRVVVectorConversion =
4570
4571 if (SCS1IsCompatibleRVVVectorConversion !=
4572 SCS2IsCompatibleRVVVectorConversion)
4573 return SCS1IsCompatibleRVVVectorConversion
4576 }
4578}
4579
4580/// CompareQualificationConversions - Compares two standard conversion
4581/// sequences to determine whether they can be ranked based on their
4582/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4585 const StandardConversionSequence& SCS1,
4586 const StandardConversionSequence& SCS2) {
4587 // C++ [over.ics.rank]p3:
4588 // -- S1 and S2 differ only in their qualification conversion and
4589 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4590 // [C++98]
4591 // [...] and the cv-qualification signature of type T1 is a proper subset
4592 // of the cv-qualification signature of type T2, and S1 is not the
4593 // deprecated string literal array-to-pointer conversion (4.2).
4594 // [C++2a]
4595 // [...] where T1 can be converted to T2 by a qualification conversion.
4596 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4597 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4599
4600 // FIXME: the example in the standard doesn't use a qualification
4601 // conversion (!)
4602 QualType T1 = SCS1.getToType(2);
4603 QualType T2 = SCS2.getToType(2);
4604 T1 = S.Context.getCanonicalType(T1);
4605 T2 = S.Context.getCanonicalType(T2);
4606 assert(!T1->isReferenceType() && !T2->isReferenceType());
4607 Qualifiers T1Quals, T2Quals;
4608 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4609 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4610
4611 // If the types are the same, we won't learn anything by unwrapping
4612 // them.
4613 if (UnqualT1 == UnqualT2)
4615
4616 // Don't ever prefer a standard conversion sequence that uses the deprecated
4617 // string literal array to pointer conversion.
4618 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4619 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4620
4621 // Objective-C++ ARC:
4622 // Prefer qualification conversions not involving a change in lifetime
4623 // to qualification conversions that do change lifetime.
4626 CanPick1 = false;
4629 CanPick2 = false;
4630
4631 bool ObjCLifetimeConversion;
4632 if (CanPick1 &&
4633 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4634 CanPick1 = false;
4635 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4636 // directions, so we can't short-cut this second check in general.
4637 if (CanPick2 &&
4638 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4639 CanPick2 = false;
4640
4641 if (CanPick1 != CanPick2)
4642 return CanPick1 ? ImplicitConversionSequence::Better
4645}
4646
4647/// CompareDerivedToBaseConversions - Compares two standard conversion
4648/// sequences to determine whether they can be ranked based on their
4649/// various kinds of derived-to-base conversions (C++
4650/// [over.ics.rank]p4b3). As part of these checks, we also look at
4651/// conversions between Objective-C interface types.
4654 const StandardConversionSequence& SCS1,
4655 const StandardConversionSequence& SCS2) {
4656 QualType FromType1 = SCS1.getFromType();
4657 QualType ToType1 = SCS1.getToType(1);
4658 QualType FromType2 = SCS2.getFromType();
4659 QualType ToType2 = SCS2.getToType(1);
4660
4661 // Adjust the types we're converting from via the array-to-pointer
4662 // conversion, if we need to.
4663 if (SCS1.First == ICK_Array_To_Pointer)
4664 FromType1 = S.Context.getArrayDecayedType(FromType1);
4665 if (SCS2.First == ICK_Array_To_Pointer)
4666 FromType2 = S.Context.getArrayDecayedType(FromType2);
4667
4668 // Canonicalize all of the types.
4669 FromType1 = S.Context.getCanonicalType(FromType1);
4670 ToType1 = S.Context.getCanonicalType(ToType1);
4671 FromType2 = S.Context.getCanonicalType(FromType2);
4672 ToType2 = S.Context.getCanonicalType(ToType2);
4673
4674 // C++ [over.ics.rank]p4b3:
4675 //
4676 // If class B is derived directly or indirectly from class A and
4677 // class C is derived directly or indirectly from B,
4678 //
4679 // Compare based on pointer conversions.
4680 if (SCS1.Second == ICK_Pointer_Conversion &&
4682 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4683 FromType1->isPointerType() && FromType2->isPointerType() &&
4684 ToType1->isPointerType() && ToType2->isPointerType()) {
4685 QualType FromPointee1 =
4687 QualType ToPointee1 =
4689 QualType FromPointee2 =
4691 QualType ToPointee2 =
4693
4694 // -- conversion of C* to B* is better than conversion of C* to A*,
4695 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4696 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4698 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4700 }
4701
4702 // -- conversion of B* to A* is better than conversion of C* to A*,
4703 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4704 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4706 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4708 }
4709 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4711 const ObjCObjectPointerType *FromPtr1
4712 = FromType1->getAs<ObjCObjectPointerType>();
4713 const ObjCObjectPointerType *FromPtr2
4714 = FromType2->getAs<ObjCObjectPointerType>();
4715 const ObjCObjectPointerType *ToPtr1
4716 = ToType1->getAs<ObjCObjectPointerType>();
4717 const ObjCObjectPointerType *ToPtr2
4718 = ToType2->getAs<ObjCObjectPointerType>();
4719
4720 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4721 // Apply the same conversion ranking rules for Objective-C pointer types
4722 // that we do for C++ pointers to class types. However, we employ the
4723 // Objective-C pseudo-subtyping relationship used for assignment of
4724 // Objective-C pointer types.
4725 bool FromAssignLeft
4726 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4727 bool FromAssignRight
4728 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4729 bool ToAssignLeft
4730 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4731 bool ToAssignRight
4732 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4733
4734 // A conversion to an a non-id object pointer type or qualified 'id'
4735 // type is better than a conversion to 'id'.
4736 if (ToPtr1->isObjCIdType() &&
4737 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4739 if (ToPtr2->isObjCIdType() &&
4740 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4742
4743 // A conversion to a non-id object pointer type is better than a
4744 // conversion to a qualified 'id' type
4745 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4747 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4749
4750 // A conversion to an a non-Class object pointer type or qualified 'Class'
4751 // type is better than a conversion to 'Class'.
4752 if (ToPtr1->isObjCClassType() &&
4753 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4755 if (ToPtr2->isObjCClassType() &&
4756 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4758
4759 // A conversion to a non-Class object pointer type is better than a
4760 // conversion to a qualified 'Class' type.
4761 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4763 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4765
4766 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4767 if (S.Context.hasSameType(FromType1, FromType2) &&
4768 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4769 (ToAssignLeft != ToAssignRight)) {
4770 if (FromPtr1->isSpecialized()) {
4771 // "conversion of B<A> * to B * is better than conversion of B * to
4772 // C *.
4773 bool IsFirstSame =
4774 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4775 bool IsSecondSame =
4776 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4777 if (IsFirstSame) {
4778 if (!IsSecondSame)
4780 } else if (IsSecondSame)
4782 }
4783 return ToAssignLeft? ImplicitConversionSequence::Worse
4785 }
4786
4787 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4788 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4789 (FromAssignLeft != FromAssignRight))
4790 return FromAssignLeft? ImplicitConversionSequence::Better
4792 }
4793 }
4794
4795 // Ranking of member-pointer types.
4796 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4797 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4798 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4799 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4800 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4801 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4802 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4803 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4804 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4805 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4806 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4807 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4808 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4809 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4810 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4811 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4812 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4813 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4815 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4817 }
4818 // conversion of B::* to C::* is better than conversion of A::* to C::*
4819 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4820 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4822 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4824 }
4825 }
4826
4827 if (SCS1.Second == ICK_Derived_To_Base) {
4828 // -- conversion of C to B is better than conversion of C to A,
4829 // -- binding of an expression of type C to a reference of type
4830 // B& is better than binding an expression of type C to a
4831 // reference of type A&,
4832 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4833 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4834 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4836 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4838 }
4839
4840 // -- conversion of B to A is better than conversion of C to A.
4841 // -- binding of an expression of type B to a reference of type
4842 // A& is better than binding an expression of type C to a
4843 // reference of type A&,
4844 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4845 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4846 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4848 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4849