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