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