Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.h"
36#include "clang/Sema/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
167 };
168 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
169 return Rank[(int)Kind];
170}
171
190
191/// GetImplicitConversionName - Return the name of this kind of
192/// implicit conversion.
194 static const char *const Name[] = {
195 "No conversion",
196 "Lvalue-to-rvalue",
197 "Array-to-pointer",
198 "Function-to-pointer",
199 "Function pointer conversion",
200 "Qualification",
201 "Integral promotion",
202 "Floating point promotion",
203 "Complex promotion",
204 "Integral conversion",
205 "Floating conversion",
206 "Complex conversion",
207 "Floating-integral conversion",
208 "Pointer conversion",
209 "Pointer-to-member conversion",
210 "Boolean conversion",
211 "Compatible-types conversion",
212 "Derived-to-base conversion",
213 "Vector conversion",
214 "SVE Vector conversion",
215 "RVV Vector conversion",
216 "Vector splat",
217 "Complex-real conversion",
218 "Block Pointer conversion",
219 "Transparent Union Conversion",
220 "Writeback conversion",
221 "OpenCL Zero Event Conversion",
222 "OpenCL Zero Queue Conversion",
223 "C specific type conversion",
224 "Incompatible pointer conversion",
225 "Fixed point conversion",
226 "HLSL vector truncation",
227 "Non-decaying array conversion",
228 "HLSL vector splat",
229 };
230 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
231 return Name[Kind];
232}
233
234/// StandardConversionSequence - Set the standard conversion
235/// sequence to the identity conversion.
253
254/// getRank - Retrieve the rank of this standard conversion sequence
255/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
256/// implicit conversions.
269
270/// isPointerConversionToBool - Determines whether this conversion is
271/// a conversion of a pointer or pointer-to-member to bool. This is
272/// used as part of the ranking of standard conversion sequences
273/// (C++ 13.3.3.2p4).
275 // Note that FromType has not necessarily been transformed by the
276 // array-to-pointer or function-to-pointer implicit conversions, so
277 // check for their presence as well as checking whether FromType is
278 // a pointer.
279 if (getToType(1)->isBooleanType() &&
280 (getFromType()->isPointerType() ||
281 getFromType()->isMemberPointerType() ||
282 getFromType()->isObjCObjectPointerType() ||
283 getFromType()->isBlockPointerType() ||
285 return true;
286
287 return false;
288}
289
290/// isPointerConversionToVoidPointer - Determines whether this
291/// conversion is a conversion of a pointer to a void pointer. This is
292/// used as part of the ranking of standard conversion sequences (C++
293/// 13.3.3.2p4).
294bool
297 QualType FromType = getFromType();
298 QualType ToType = getToType(1);
299
300 // Note that FromType has not necessarily been transformed by the
301 // array-to-pointer implicit conversion, so check for its presence
302 // and redo the conversion to get a pointer.
304 FromType = Context.getArrayDecayedType(FromType);
305
306 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
307 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
308 return ToPtrType->getPointeeType()->isVoidType();
309
310 return false;
311}
312
313/// Skip any implicit casts which could be either part of a narrowing conversion
314/// or after one in an implicit conversion.
316 const Expr *Converted) {
317 // We can have cleanups wrapping the converted expression; these need to be
318 // preserved so that destructors run if necessary.
319 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
320 Expr *Inner =
321 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
322 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
323 EWC->getObjects());
324 }
325
326 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
327 switch (ICE->getCastKind()) {
328 case CK_NoOp:
329 case CK_IntegralCast:
330 case CK_IntegralToBoolean:
331 case CK_IntegralToFloating:
332 case CK_BooleanToSignedIntegral:
333 case CK_FloatingToIntegral:
334 case CK_FloatingToBoolean:
335 case CK_FloatingCast:
336 Converted = ICE->getSubExpr();
337 continue;
338
339 default:
340 return Converted;
341 }
342 }
343
344 return Converted;
345}
346
347/// Check if this standard conversion sequence represents a narrowing
348/// conversion, according to C++11 [dcl.init.list]p7.
349///
350/// \param Ctx The AST context.
351/// \param Converted The result of applying this standard conversion sequence.
352/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
353/// value of the expression prior to the narrowing conversion.
354/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
355/// type of the expression prior to the narrowing conversion.
356/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
357/// from floating point types to integral types should be ignored.
359 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
360 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
361 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
362 "narrowing check outside C++");
363
364 // C++11 [dcl.init.list]p7:
365 // A narrowing conversion is an implicit conversion ...
366 QualType FromType = getToType(0);
367 QualType ToType = getToType(1);
368
369 // A conversion to an enumeration type is narrowing if the conversion to
370 // the underlying type is narrowing. This only arises for expressions of
371 // the form 'Enum{init}'.
372 if (const auto *ED = ToType->getAsEnumDecl())
373 ToType = ED->getIntegerType();
374
375 switch (Second) {
376 // 'bool' is an integral type; dispatch to the right place to handle it.
378 if (FromType->isRealFloatingType())
379 goto FloatingIntegralConversion;
381 goto IntegralConversion;
382 // -- from a pointer type or pointer-to-member type to bool, or
383 return NK_Type_Narrowing;
384
385 // -- from a floating-point type to an integer type, or
386 //
387 // -- from an integer type or unscoped enumeration type to a floating-point
388 // type, except where the source is a constant expression and the actual
389 // value after conversion will fit into the target type and will produce
390 // the original value when converted back to the original type, or
392 FloatingIntegralConversion:
393 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
394 return NK_Type_Narrowing;
395 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
396 ToType->isRealFloatingType()) {
397 if (IgnoreFloatToIntegralConversion)
398 return NK_Not_Narrowing;
399 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
400 assert(Initializer && "Unknown conversion expression");
401
402 // If it's value-dependent, we can't tell whether it's narrowing.
403 if (Initializer->isValueDependent())
405
406 if (std::optional<llvm::APSInt> IntConstantValue =
407 Initializer->getIntegerConstantExpr(Ctx)) {
408 // Convert the integer to the floating type.
409 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
410 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
411 llvm::APFloat::rmNearestTiesToEven);
412 // And back.
413 llvm::APSInt ConvertedValue = *IntConstantValue;
414 bool ignored;
415 llvm::APFloat::opStatus Status = Result.convertToInteger(
416 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
417 // If the converted-back integer has unspecified value, or if the
418 // resulting value is different, this was a narrowing conversion.
419 if (Status == llvm::APFloat::opInvalidOp ||
420 *IntConstantValue != ConvertedValue) {
421 ConstantValue = APValue(*IntConstantValue);
422 ConstantType = Initializer->getType();
424 }
425 } else {
426 // Variables are always narrowings.
428 }
429 }
430 return NK_Not_Narrowing;
431
432 // -- from long double to double or float, or from double to float, except
433 // where the source is a constant expression and the actual value after
434 // conversion is within the range of values that can be represented (even
435 // if it cannot be represented exactly), or
437 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
438 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
439 // FromType is larger than ToType.
440 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
441
442 // If it's value-dependent, we can't tell whether it's narrowing.
443 if (Initializer->isValueDependent())
445
447 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
448 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
449 // Constant!
450 if (Ctx.getLangOpts().C23)
451 ConstantValue = R.Val;
452 assert(ConstantValue.isFloat());
453 llvm::APFloat FloatVal = ConstantValue.getFloat();
454 // Convert the source value into the target type.
455 bool ignored;
456 llvm::APFloat Converted = FloatVal;
457 llvm::APFloat::opStatus ConvertStatus =
458 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
459 llvm::APFloat::rmNearestTiesToEven, &ignored);
460 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
461 llvm::APFloat::rmNearestTiesToEven, &ignored);
462 if (Ctx.getLangOpts().C23) {
463 if (FloatVal.isNaN() && Converted.isNaN() &&
464 !FloatVal.isSignaling() && !Converted.isSignaling()) {
465 // Quiet NaNs are considered the same value, regardless of
466 // payloads.
467 return NK_Not_Narrowing;
468 }
469 // For normal values, check exact equality.
470 if (!Converted.bitwiseIsEqual(FloatVal)) {
471 ConstantType = Initializer->getType();
473 }
474 } else {
475 // If there was no overflow, the source value is within the range of
476 // values that can be represented.
477 if (ConvertStatus & llvm::APFloat::opOverflow) {
478 ConstantType = Initializer->getType();
480 }
481 }
482 } else {
484 }
485 }
486 return NK_Not_Narrowing;
487
488 // -- from an integer type or unscoped enumeration type to an integer type
489 // that cannot represent all the values of the original type, except where
490 // (CWG2627) -- the source is a bit-field whose width w is less than that
491 // of its type (or, for an enumeration type, its underlying type) and the
492 // target type can represent all the values of a hypothetical extended
493 // integer type with width w and with the same signedness as the original
494 // type or
495 // -- the source is a constant expression and the actual value after
496 // conversion will fit into the target type and will produce the original
497 // value when converted back to the original type.
499 IntegralConversion: {
500 assert(FromType->isIntegralOrUnscopedEnumerationType());
501 assert(ToType->isIntegralOrUnscopedEnumerationType());
502 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
503 unsigned FromWidth = Ctx.getIntWidth(FromType);
504 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
505 const unsigned ToWidth = Ctx.getIntWidth(ToType);
506
507 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
508 bool ToSigned, unsigned ToWidth) {
509 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
510 !(FromSigned && !ToSigned);
511 };
512
513 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
514 return NK_Not_Narrowing;
515
516 // Not all values of FromType can be represented in ToType.
517 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
518
519 bool DependentBitField = false;
520 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
521 if (BitField->getBitWidth()->isValueDependent())
522 DependentBitField = true;
523 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
524 BitFieldWidth < FromWidth) {
525 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // The initializer will be truncated to the bit-field width
529 FromWidth = BitFieldWidth;
530 }
531 }
532
533 // If it's value-dependent, we can't tell whether it's narrowing.
534 if (Initializer->isValueDependent())
536
537 std::optional<llvm::APSInt> OptInitializerValue =
538 Initializer->getIntegerConstantExpr(Ctx);
539 if (!OptInitializerValue) {
540 // If the bit-field width was dependent, it might end up being small
541 // enough to fit in the target type (unless the target type is unsigned
542 // and the source type is signed, in which case it will never fit)
543 if (DependentBitField && !(FromSigned && !ToSigned))
545
546 // Otherwise, such a conversion is always narrowing
548 }
549 llvm::APSInt &InitializerValue = *OptInitializerValue;
550 bool Narrowing = false;
551 if (FromWidth < ToWidth) {
552 // Negative -> unsigned is narrowing. Otherwise, more bits is never
553 // narrowing.
554 if (InitializerValue.isSigned() && InitializerValue.isNegative())
555 Narrowing = true;
556 } else {
557 // Add a bit to the InitializerValue so we don't have to worry about
558 // signed vs. unsigned comparisons.
559 InitializerValue =
560 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
561 // Convert the initializer to and from the target width and signed-ness.
562 llvm::APSInt ConvertedValue = InitializerValue;
563 ConvertedValue = ConvertedValue.trunc(ToWidth);
564 ConvertedValue.setIsSigned(ToSigned);
565 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
566 ConvertedValue.setIsSigned(InitializerValue.isSigned());
567 // If the result is different, this was a narrowing conversion.
568 if (ConvertedValue != InitializerValue)
569 Narrowing = true;
570 }
571 if (Narrowing) {
572 ConstantType = Initializer->getType();
573 ConstantValue = APValue(InitializerValue);
575 }
576
577 return NK_Not_Narrowing;
578 }
579 case ICK_Complex_Real:
580 if (FromType->isComplexType() && !ToType->isComplexType())
581 return NK_Type_Narrowing;
582 return NK_Not_Narrowing;
583
585 if (Ctx.getLangOpts().C23) {
586 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
588 if (Initializer->EvaluateAsRValue(R, Ctx)) {
589 ConstantValue = R.Val;
590 assert(ConstantValue.isFloat());
591 llvm::APFloat FloatVal = ConstantValue.getFloat();
592 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
593 // value, the unqualified versions of the type of the initializer and
594 // the corresponding real type of the object declared shall be
595 // compatible.
596 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
597 ConstantType = Initializer->getType();
599 }
600 }
601 }
602 return NK_Not_Narrowing;
603 default:
604 // Other kinds of conversions are not narrowings.
605 return NK_Not_Narrowing;
606 }
607}
608
609/// dump - Print this standard conversion sequence to standard
610/// error. Useful for debugging overloading issues.
611LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
612 raw_ostream &OS = llvm::errs();
613 bool PrintedSomething = false;
614 if (First != ICK_Identity) {
616 PrintedSomething = true;
617 }
618
619 if (Second != ICK_Identity) {
620 if (PrintedSomething) {
621 OS << " -> ";
622 }
624
625 if (CopyConstructor) {
626 OS << " (by copy constructor)";
627 } else if (DirectBinding) {
628 OS << " (direct reference binding)";
629 } else if (ReferenceBinding) {
630 OS << " (reference binding)";
631 }
632 PrintedSomething = true;
633 }
634
635 if (Third != ICK_Identity) {
636 if (PrintedSomething) {
637 OS << " -> ";
638 }
640 PrintedSomething = true;
641 }
642
643 if (!PrintedSomething) {
644 OS << "No conversions required";
645 }
646}
647
648/// dump - Print this user-defined conversion sequence to standard
649/// error. Useful for debugging overloading issues.
651 raw_ostream &OS = llvm::errs();
652 if (Before.First || Before.Second || Before.Third) {
653 Before.dump();
654 OS << " -> ";
655 }
657 OS << '\'' << *ConversionFunction << '\'';
658 else
659 OS << "aggregate initialization";
660 if (After.First || After.Second || After.Third) {
661 OS << " -> ";
662 After.dump();
663 }
664}
665
666/// dump - Print this implicit conversion sequence to standard
667/// error. Useful for debugging overloading issues.
669 raw_ostream &OS = llvm::errs();
671 OS << "Worst list element conversion: ";
672 switch (ConversionKind) {
674 OS << "Standard conversion: ";
675 Standard.dump();
676 break;
678 OS << "User-defined conversion: ";
679 UserDefined.dump();
680 break;
682 OS << "Ellipsis conversion";
683 break;
685 OS << "Ambiguous conversion";
686 break;
687 case BadConversion:
688 OS << "Bad conversion";
689 break;
690 }
691
692 OS << "\n";
693}
694
698
700 conversions().~ConversionSet();
701}
702
703void
709
710namespace {
711 // Structure used by DeductionFailureInfo to store
712 // template argument information.
713 struct DFIArguments {
714 TemplateArgument FirstArg;
715 TemplateArgument SecondArg;
716 };
717 // Structure used by DeductionFailureInfo to store
718 // template parameter and template argument information.
719 struct DFIParamWithArguments : DFIArguments {
720 TemplateParameter Param;
721 };
722 // Structure used by DeductionFailureInfo to store template argument
723 // information and the index of the problematic call argument.
724 struct DFIDeducedMismatchArgs : DFIArguments {
725 TemplateArgumentList *TemplateArgs;
726 unsigned CallArgIndex;
727 };
728 // Structure used by DeductionFailureInfo to store information about
729 // unsatisfied constraints.
730 struct CNSInfo {
731 TemplateArgumentList *TemplateArgs;
732 ConstraintSatisfaction Satisfaction;
733 };
734}
735
736/// Convert from Sema's representation of template deduction information
737/// to the form used in overload-candidate information.
741 TemplateDeductionInfo &Info) {
743 Result.Result = static_cast<unsigned>(TDK);
744 Result.HasDiagnostic = false;
745 switch (TDK) {
752 Result.Data = nullptr;
753 break;
754
757 Result.Data = Info.Param.getOpaqueValue();
758 break;
759
762 // FIXME: Should allocate from normal heap so that we can free this later.
763 auto *Saved = new (Context) DFIDeducedMismatchArgs;
764 Saved->FirstArg = Info.FirstArg;
765 Saved->SecondArg = Info.SecondArg;
766 Saved->TemplateArgs = Info.takeSugared();
767 Saved->CallArgIndex = Info.CallArgIndex;
768 Result.Data = Saved;
769 break;
770 }
771
773 // FIXME: Should allocate from normal heap so that we can free this later.
774 DFIArguments *Saved = new (Context) DFIArguments;
775 Saved->FirstArg = Info.FirstArg;
776 Saved->SecondArg = Info.SecondArg;
777 Result.Data = Saved;
778 break;
779 }
780
782 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
785 // FIXME: Should allocate from normal heap so that we can free this later.
786 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
787 Saved->Param = Info.Param;
788 Saved->FirstArg = Info.FirstArg;
789 Saved->SecondArg = Info.SecondArg;
790 Result.Data = Saved;
791 break;
792 }
793
795 Result.Data = Info.takeSugared();
796 if (Info.hasSFINAEDiagnostic()) {
800 Result.HasDiagnostic = true;
801 }
802 break;
803
805 CNSInfo *Saved = new (Context) CNSInfo;
806 Saved->TemplateArgs = Info.takeSugared();
807 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
808 Result.Data = Saved;
809 break;
810 }
811
815 llvm_unreachable("not a deduction failure");
816 }
817
818 return Result;
819}
820
822 switch (static_cast<TemplateDeductionResult>(Result)) {
832 break;
833
840 // FIXME: Destroy the data?
841 Data = nullptr;
842 break;
843
845 // FIXME: Destroy the template argument list?
846 Data = nullptr;
848 Diag->~PartialDiagnosticAt();
849 HasDiagnostic = false;
850 }
851 break;
852
854 // FIXME: Destroy the template argument list?
855 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
856 Data = nullptr;
858 Diag->~PartialDiagnosticAt();
859 HasDiagnostic = false;
860 }
861 break;
862
863 // Unhandled
866 break;
867 }
868}
869
871 if (HasDiagnostic)
872 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
873 return nullptr;
874}
875
909
945
977
1009
1011 switch (static_cast<TemplateDeductionResult>(Result)) {
1014 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1015
1016 default:
1017 return std::nullopt;
1018 }
1019}
1020
1022 const FunctionDecl *Y) {
1023 if (!X || !Y)
1024 return false;
1025 if (X->getNumParams() != Y->getNumParams())
1026 return false;
1027 // FIXME: when do rewritten comparison operators
1028 // with explicit object parameters correspond?
1029 // https://cplusplus.github.io/CWG/issues/2797.html
1030 for (unsigned I = 0; I < X->getNumParams(); ++I)
1031 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1032 Y->getParamDecl(I)->getType()))
1033 return false;
1034 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1035 auto *FTY = Y->getDescribedFunctionTemplate();
1036 if (!FTY)
1037 return false;
1038 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1039 FTY->getTemplateParameters()))
1040 return false;
1041 }
1042 return true;
1043}
1044
1046 Expr *FirstOperand, FunctionDecl *EqFD) {
1047 assert(EqFD->getOverloadedOperator() ==
1048 OverloadedOperatorKind::OO_EqualEqual);
1049 // C++2a [over.match.oper]p4:
1050 // A non-template function or function template F named operator== is a
1051 // rewrite target with first operand o unless a search for the name operator!=
1052 // in the scope S from the instantiation context of the operator expression
1053 // finds a function or function template that would correspond
1054 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1055 // scope of the class type of o if F is a class member, and the namespace
1056 // scope of which F is a member otherwise. A function template specialization
1057 // named operator== is a rewrite target if its function template is a rewrite
1058 // target.
1060 OverloadedOperatorKind::OO_ExclaimEqual);
1061 if (isa<CXXMethodDecl>(EqFD)) {
1062 // If F is a class member, search scope is class type of first operand.
1063 QualType RHS = FirstOperand->getType();
1064 auto *RHSRec = RHS->getAsCXXRecordDecl();
1065 if (!RHSRec)
1066 return true;
1067 LookupResult Members(S, NotEqOp, OpLoc,
1069 S.LookupQualifiedName(Members, RHSRec);
1070 Members.suppressAccessDiagnostics();
1071 for (NamedDecl *Op : Members)
1072 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1073 return false;
1074 return true;
1075 }
1076 // Otherwise the search scope is the namespace scope of which F is a member.
1077 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1078 auto *NotEqFD = Op->getAsFunction();
1079 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1080 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1081 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1083 cast<Decl>(Op->getLexicalDeclContext())))
1084 return false;
1085 }
1086 return true;
1087}
1088
1092 return false;
1093 return Op == OO_EqualEqual || Op == OO_Spaceship;
1094}
1095
1097 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1098 auto Op = FD->getOverloadedOperator();
1099 if (!allowsReversed(Op))
1100 return false;
1101 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1102 assert(OriginalArgs.size() == 2);
1104 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1105 return false;
1106 }
1107 // Don't bother adding a reversed candidate that can never be a better
1108 // match than the non-reversed version.
1109 return FD->getNumNonObjectParams() != 2 ||
1111 FD->getParamDecl(1)->getType()) ||
1112 FD->hasAttr<EnableIfAttr>();
1113}
1114
1115void OverloadCandidateSet::destroyCandidates() {
1116 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1117 for (auto &C : i->Conversions)
1118 C.~ImplicitConversionSequence();
1119 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1120 i->DeductionFailure.Destroy();
1121 }
1122}
1123
1125 destroyCandidates();
1126 SlabAllocator.Reset();
1127 NumInlineBytesUsed = 0;
1128 Candidates.clear();
1129 Functions.clear();
1130 Kind = CSK;
1131 FirstDeferredCandidate = nullptr;
1132 DeferredCandidatesCount = 0;
1133 HasDeferredTemplateConstructors = false;
1134 ResolutionByPerfectCandidateIsDisabled = false;
1135}
1136
1137namespace {
1138 class UnbridgedCastsSet {
1139 struct Entry {
1140 Expr **Addr;
1141 Expr *Saved;
1142 };
1143 SmallVector<Entry, 2> Entries;
1144
1145 public:
1146 void save(Sema &S, Expr *&E) {
1147 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1148 Entry entry = { &E, E };
1149 Entries.push_back(entry);
1150 E = S.ObjC().stripARCUnbridgedCast(E);
1151 }
1152
1153 void restore() {
1154 for (SmallVectorImpl<Entry>::iterator
1155 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1156 *i->Addr = i->Saved;
1157 }
1158 };
1159}
1160
1161/// checkPlaceholderForOverload - Do any interesting placeholder-like
1162/// preprocessing on the given expression.
1163///
1164/// \param unbridgedCasts a collection to which to add unbridged casts;
1165/// without this, they will be immediately diagnosed as errors
1166///
1167/// Return true on unrecoverable error.
1168static bool
1170 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1171 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1172 // We can't handle overloaded expressions here because overload
1173 // resolution might reasonably tweak them.
1174 if (placeholder->getKind() == BuiltinType::Overload) return false;
1175
1176 // If the context potentially accepts unbridged ARC casts, strip
1177 // the unbridged cast and add it to the collection for later restoration.
1178 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1179 unbridgedCasts) {
1180 unbridgedCasts->save(S, E);
1181 return false;
1182 }
1183
1184 // Go ahead and check everything else.
1185 ExprResult result = S.CheckPlaceholderExpr(E);
1186 if (result.isInvalid())
1187 return true;
1188
1189 E = result.get();
1190 return false;
1191 }
1192
1193 // Nothing to do.
1194 return false;
1195}
1196
1197/// checkArgPlaceholdersForOverload - Check a set of call operands for
1198/// placeholders.
1200 UnbridgedCastsSet &unbridged) {
1201 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1202 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1203 return true;
1204
1205 return false;
1206}
1207
1209 const LookupResult &Old, NamedDecl *&Match,
1210 bool NewIsUsingDecl) {
1211 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1212 I != E; ++I) {
1213 NamedDecl *OldD = *I;
1214
1215 bool OldIsUsingDecl = false;
1216 if (isa<UsingShadowDecl>(OldD)) {
1217 OldIsUsingDecl = true;
1218
1219 // We can always introduce two using declarations into the same
1220 // context, even if they have identical signatures.
1221 if (NewIsUsingDecl) continue;
1222
1223 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1224 }
1225
1226 // A using-declaration does not conflict with another declaration
1227 // if one of them is hidden.
1228 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1229 continue;
1230
1231 // If either declaration was introduced by a using declaration,
1232 // we'll need to use slightly different rules for matching.
1233 // Essentially, these rules are the normal rules, except that
1234 // function templates hide function templates with different
1235 // return types or template parameter lists.
1236 bool UseMemberUsingDeclRules =
1237 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1238 !New->getFriendObjectKind();
1239
1240 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1241 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1242 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1244 continue;
1245 }
1246
1247 if (!isa<FunctionTemplateDecl>(OldD) &&
1248 !shouldLinkPossiblyHiddenDecl(*I, New))
1249 continue;
1250
1251 Match = *I;
1252 return OverloadKind::Match;
1253 }
1254
1255 // Builtins that have custom typechecking or have a reference should
1256 // not be overloadable or redeclarable.
1257 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1258 Match = *I;
1260 }
1261 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1262 // We can overload with these, which can show up when doing
1263 // redeclaration checks for UsingDecls.
1264 assert(Old.getLookupKind() == LookupUsingDeclName);
1265 } else if (isa<TagDecl>(OldD)) {
1266 // We can always overload with tags by hiding them.
1267 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1268 // Optimistically assume that an unresolved using decl will
1269 // overload; if it doesn't, we'll have to diagnose during
1270 // template instantiation.
1271 //
1272 // Exception: if the scope is dependent and this is not a class
1273 // member, the using declaration can only introduce an enumerator.
1274 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1275 Match = *I;
1277 }
1278 } else {
1279 // (C++ 13p1):
1280 // Only function declarations can be overloaded; object and type
1281 // declarations cannot be overloaded.
1282 Match = *I;
1284 }
1285 }
1286
1287 // C++ [temp.friend]p1:
1288 // For a friend function declaration that is not a template declaration:
1289 // -- if the name of the friend is a qualified or unqualified template-id,
1290 // [...], otherwise
1291 // -- if the name of the friend is a qualified-id and a matching
1292 // non-template function is found in the specified class or namespace,
1293 // the friend declaration refers to that function, otherwise,
1294 // -- if the name of the friend is a qualified-id and a matching function
1295 // template is found in the specified class or namespace, the friend
1296 // declaration refers to the deduced specialization of that function
1297 // template, otherwise
1298 // -- the name shall be an unqualified-id [...]
1299 // If we get here for a qualified friend declaration, we've just reached the
1300 // third bullet. If the type of the friend is dependent, skip this lookup
1301 // until instantiation.
1302 if (New->getFriendObjectKind() && New->getQualifier() &&
1303 !New->getDescribedFunctionTemplate() &&
1304 !New->getDependentSpecializationInfo() &&
1305 !New->getType()->isDependentType()) {
1306 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1307 TemplateSpecResult.addAllDecls(Old);
1308 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1309 /*QualifiedFriend*/true)) {
1310 New->setInvalidDecl();
1312 }
1313
1314 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1315 return OverloadKind::Match;
1316 }
1317
1319}
1320
1321template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1322 assert(D && "function decl should not be null");
1323 if (auto *A = D->getAttr<AttrT>())
1324 return !A->isImplicit();
1325 return false;
1326}
1327
1329 FunctionDecl *Old,
1330 bool UseMemberUsingDeclRules,
1331 bool ConsiderCudaAttrs,
1332 bool UseOverrideRules = false) {
1333 // C++ [basic.start.main]p2: This function shall not be overloaded.
1334 if (New->isMain())
1335 return false;
1336
1337 // MSVCRT user defined entry points cannot be overloaded.
1338 if (New->isMSVCRTEntryPoint())
1339 return false;
1340
1341 NamedDecl *OldDecl = Old;
1342 NamedDecl *NewDecl = New;
1344 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1345
1346 // C++ [temp.fct]p2:
1347 // A function template can be overloaded with other function templates
1348 // and with normal (non-template) functions.
1349 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1350 return true;
1351
1352 // Is the function New an overload of the function Old?
1353 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1354 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1355
1356 // Compare the signatures (C++ 1.3.10) of the two functions to
1357 // determine whether they are overloads. If we find any mismatch
1358 // in the signature, they are overloads.
1359
1360 // If either of these functions is a K&R-style function (no
1361 // prototype), then we consider them to have matching signatures.
1362 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1364 return false;
1365
1366 const auto *OldType = cast<FunctionProtoType>(OldQType);
1367 const auto *NewType = cast<FunctionProtoType>(NewQType);
1368
1369 // The signature of a function includes the types of its
1370 // parameters (C++ 1.3.10), which includes the presence or absence
1371 // of the ellipsis; see C++ DR 357).
1372 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1373 return true;
1374
1375 // For member-like friends, the enclosing class is part of the signature.
1376 if ((New->isMemberLikeConstrainedFriend() ||
1378 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1379 return true;
1380
1381 // Compare the parameter lists.
1382 // This can only be done once we have establish that friend functions
1383 // inhabit the same context, otherwise we might tried to instantiate
1384 // references to non-instantiated entities during constraint substitution.
1385 // GH78101.
1386 if (NewTemplate) {
1387 OldDecl = OldTemplate;
1388 NewDecl = NewTemplate;
1389 // C++ [temp.over.link]p4:
1390 // The signature of a function template consists of its function
1391 // signature, its return type and its template parameter list. The names
1392 // of the template parameters are significant only for establishing the
1393 // relationship between the template parameters and the rest of the
1394 // signature.
1395 //
1396 // We check the return type and template parameter lists for function
1397 // templates first; the remaining checks follow.
1398 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1399 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1400 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1401 bool SameReturnType = SemaRef.Context.hasSameType(
1402 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1403 // FIXME(GH58571): Match template parameter list even for non-constrained
1404 // template heads. This currently ensures that the code prior to C++20 is
1405 // not newly broken.
1406 bool ConstraintsInTemplateHead =
1409 // C++ [namespace.udecl]p11:
1410 // The set of declarations named by a using-declarator that inhabits a
1411 // class C does not include member functions and member function
1412 // templates of a base class that "correspond" to (and thus would
1413 // conflict with) a declaration of a function or function template in
1414 // C.
1415 // Comparing return types is not required for the "correspond" check to
1416 // decide whether a member introduced by a shadow declaration is hidden.
1417 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1418 !SameTemplateParameterList)
1419 return true;
1420 if (!UseMemberUsingDeclRules &&
1421 (!SameTemplateParameterList || !SameReturnType))
1422 return true;
1423 }
1424
1425 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1426 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1427
1428 int OldParamsOffset = 0;
1429 int NewParamsOffset = 0;
1430
1431 // When determining if a method is an overload from a base class, act as if
1432 // the implicit object parameter are of the same type.
1433
1434 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1436 auto ThisType = M->getFunctionObjectParameterReferenceType();
1437 if (ThisType.isConstQualified())
1438 Q.removeConst();
1439 return Q;
1440 }
1441
1442 // We do not allow overloading based off of '__restrict'.
1443 Q.removeRestrict();
1444
1445 // We may not have applied the implicit const for a constexpr member
1446 // function yet (because we haven't yet resolved whether this is a static
1447 // or non-static member function). Add it now, on the assumption that this
1448 // is a redeclaration of OldMethod.
1449 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1450 (M->isConstexpr() || M->isConsteval()) &&
1451 !isa<CXXConstructorDecl>(NewMethod))
1452 Q.addConst();
1453 return Q;
1454 };
1455
1456 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1457 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1458 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1459
1460 if (OldMethod->isExplicitObjectMemberFunction()) {
1461 BS.Quals.removeVolatile();
1462 DS.Quals.removeVolatile();
1463 }
1464
1465 return BS.Quals == DS.Quals;
1466 };
1467
1468 auto CompareType = [&](QualType Base, QualType D) {
1469 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1470 auto DS = D.getNonReferenceType().getCanonicalType().split();
1471
1472 if (!AreQualifiersEqual(BS, DS))
1473 return false;
1474
1475 if (OldMethod->isImplicitObjectMemberFunction() &&
1476 OldMethod->getParent() != NewMethod->getParent()) {
1477 CanQualType ParentType =
1478 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1479 if (ParentType.getTypePtr() != BS.Ty)
1480 return false;
1481 BS.Ty = DS.Ty;
1482 }
1483
1484 // FIXME: should we ignore some type attributes here?
1485 if (BS.Ty != DS.Ty)
1486 return false;
1487
1488 if (Base->isLValueReferenceType())
1489 return D->isLValueReferenceType();
1490 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1491 };
1492
1493 // If the function is a class member, its signature includes the
1494 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1495 auto DiagnoseInconsistentRefQualifiers = [&]() {
1496 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1497 return false;
1498 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1499 return false;
1500 if (OldMethod->isExplicitObjectMemberFunction() ||
1501 NewMethod->isExplicitObjectMemberFunction())
1502 return false;
1503 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1504 NewMethod->getRefQualifier() == RQ_None)) {
1505 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1506 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1507 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1508 return true;
1509 }
1510 return false;
1511 };
1512
1513 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1514 OldParamsOffset++;
1515 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1516 NewParamsOffset++;
1517
1518 if (OldType->getNumParams() - OldParamsOffset !=
1519 NewType->getNumParams() - NewParamsOffset ||
1521 {OldType->param_type_begin() + OldParamsOffset,
1522 OldType->param_type_end()},
1523 {NewType->param_type_begin() + NewParamsOffset,
1524 NewType->param_type_end()},
1525 nullptr)) {
1526 return true;
1527 }
1528
1529 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1530 !NewMethod->isStatic()) {
1531 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1532 const CXXMethodDecl *New) {
1533 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1534 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1535
1536 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1537 return F->getRefQualifier() == RQ_None &&
1538 !F->isExplicitObjectMemberFunction();
1539 };
1540
1541 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1542 CompareType(OldObjectType.getNonReferenceType(),
1543 NewObjectType.getNonReferenceType()))
1544 return true;
1545 return CompareType(OldObjectType, NewObjectType);
1546 }(OldMethod, NewMethod);
1547
1548 if (!HaveCorrespondingObjectParameters) {
1549 if (DiagnoseInconsistentRefQualifiers())
1550 return true;
1551 // CWG2554
1552 // and, if at least one is an explicit object member function, ignoring
1553 // object parameters
1554 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1555 !OldMethod->isExplicitObjectMemberFunction()))
1556 return true;
1557 }
1558 }
1559
1560 if (!UseOverrideRules &&
1561 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1562 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1563 OldRC = Old->getTrailingRequiresClause();
1564 if (!NewRC != !OldRC)
1565 return true;
1566 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1567 return true;
1568 if (NewRC &&
1569 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1570 NewDecl, NewRC.ConstraintExpr))
1571 return true;
1572 }
1573
1574 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1575 NewMethod->isImplicitObjectMemberFunction()) {
1576 if (DiagnoseInconsistentRefQualifiers())
1577 return true;
1578 }
1579
1580 // Though pass_object_size is placed on parameters and takes an argument, we
1581 // consider it to be a function-level modifier for the sake of function
1582 // identity. Either the function has one or more parameters with
1583 // pass_object_size or it doesn't.
1586 return true;
1587
1588 // enable_if attributes are an order-sensitive part of the signature.
1590 NewI = New->specific_attr_begin<EnableIfAttr>(),
1591 NewE = New->specific_attr_end<EnableIfAttr>(),
1592 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1593 OldE = Old->specific_attr_end<EnableIfAttr>();
1594 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1595 if (NewI == NewE || OldI == OldE)
1596 return true;
1597 llvm::FoldingSetNodeID NewID, OldID;
1598 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1599 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1600 if (NewID != OldID)
1601 return true;
1602 }
1603
1604 // At this point, it is known that the two functions have the same signature.
1605 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1606 // Don't allow overloading of destructors. (In theory we could, but it
1607 // would be a giant change to clang.)
1609 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1610 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1611 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1612 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1613 "Unexpected invalid target.");
1614
1615 // Allow overloading of functions with same signature and different CUDA
1616 // target attributes.
1617 if (NewTarget != OldTarget) {
1618 // Special case: non-constexpr function is allowed to override
1619 // constexpr virtual function
1620 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1621 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1626 return false;
1627 }
1628 return true;
1629 }
1630 }
1631 }
1632 }
1633
1634 // The signatures match; this is not an overload.
1635 return false;
1636}
1637
1639 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1640 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1641 ConsiderCudaAttrs);
1642}
1643
1645 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1646 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1647 /*UseMemberUsingDeclRules=*/false,
1648 /*ConsiderCudaAttrs=*/true,
1649 /*UseOverrideRules=*/true);
1650}
1651
1652/// Tries a user-defined conversion from From to ToType.
1653///
1654/// Produces an implicit conversion sequence for when a standard conversion
1655/// is not an option. See TryImplicitConversion for more information.
1658 bool SuppressUserConversions,
1659 AllowedExplicit AllowExplicit,
1660 bool InOverloadResolution,
1661 bool CStyle,
1662 bool AllowObjCWritebackConversion,
1663 bool AllowObjCConversionOnExplicit) {
1665
1666 if (SuppressUserConversions) {
1667 // We're not in the case above, so there is no conversion that
1668 // we can perform.
1670 return ICS;
1671 }
1672
1673 // Attempt user-defined conversion.
1674 OverloadCandidateSet Conversions(From->getExprLoc(),
1676 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1677 Conversions, AllowExplicit,
1678 AllowObjCConversionOnExplicit)) {
1679 case OR_Success:
1680 case OR_Deleted:
1681 ICS.setUserDefined();
1682 // C++ [over.ics.user]p4:
1683 // A conversion of an expression of class type to the same class
1684 // type is given Exact Match rank, and a conversion of an
1685 // expression of class type to a base class of that type is
1686 // given Conversion rank, in spite of the fact that a copy
1687 // constructor (i.e., a user-defined conversion function) is
1688 // called for those cases.
1690 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1691 QualType FromType;
1692 SourceLocation FromLoc;
1693 // C++11 [over.ics.list]p6, per DR2137:
1694 // C++17 [over.ics.list]p6:
1695 // If C is not an initializer-list constructor and the initializer list
1696 // has a single element of type cv U, where U is X or a class derived
1697 // from X, the implicit conversion sequence has Exact Match rank if U is
1698 // X, or Conversion rank if U is derived from X.
1699 bool FromListInit = false;
1700 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1701 InitList && InitList->getNumInits() == 1 &&
1703 const Expr *SingleInit = InitList->getInit(0);
1704 FromType = SingleInit->getType();
1705 FromLoc = SingleInit->getBeginLoc();
1706 FromListInit = true;
1707 } else {
1708 FromType = From->getType();
1709 FromLoc = From->getBeginLoc();
1710 }
1711 QualType FromCanon =
1713 QualType ToCanon
1715 if ((FromCanon == ToCanon ||
1716 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1717 // Turn this into a "standard" conversion sequence, so that it
1718 // gets ranked with standard conversion sequences.
1720 ICS.setStandard();
1722 ICS.Standard.setFromType(FromType);
1723 ICS.Standard.setAllToTypes(ToType);
1724 ICS.Standard.FromBracedInitList = FromListInit;
1727 if (ToCanon != FromCanon)
1729 }
1730 }
1731 break;
1732
1733 case OR_Ambiguous:
1734 ICS.setAmbiguous();
1735 ICS.Ambiguous.setFromType(From->getType());
1736 ICS.Ambiguous.setToType(ToType);
1737 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1738 Cand != Conversions.end(); ++Cand)
1739 if (Cand->Best)
1740 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1741 break;
1742
1743 // Fall through.
1746 break;
1747 }
1748
1749 return ICS;
1750}
1751
1752/// TryImplicitConversion - Attempt to perform an implicit conversion
1753/// from the given expression (Expr) to the given type (ToType). This
1754/// function returns an implicit conversion sequence that can be used
1755/// to perform the initialization. Given
1756///
1757/// void f(float f);
1758/// void g(int i) { f(i); }
1759///
1760/// this routine would produce an implicit conversion sequence to
1761/// describe the initialization of f from i, which will be a standard
1762/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1763/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1764//
1765/// Note that this routine only determines how the conversion can be
1766/// performed; it does not actually perform the conversion. As such,
1767/// it will not produce any diagnostics if no conversion is available,
1768/// but will instead return an implicit conversion sequence of kind
1769/// "BadConversion".
1770///
1771/// If @p SuppressUserConversions, then user-defined conversions are
1772/// not permitted.
1773/// If @p AllowExplicit, then explicit user-defined conversions are
1774/// permitted.
1775///
1776/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1777/// writeback conversion, which allows __autoreleasing id* parameters to
1778/// be initialized with __strong id* or __weak id* arguments.
1779static ImplicitConversionSequence
1781 bool SuppressUserConversions,
1782 AllowedExplicit AllowExplicit,
1783 bool InOverloadResolution,
1784 bool CStyle,
1785 bool AllowObjCWritebackConversion,
1786 bool AllowObjCConversionOnExplicit) {
1788 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1789 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1790 ICS.setStandard();
1791 return ICS;
1792 }
1793
1794 if (!S.getLangOpts().CPlusPlus) {
1796 return ICS;
1797 }
1798
1799 // C++ [over.ics.user]p4:
1800 // A conversion of an expression of class type to the same class
1801 // type is given Exact Match rank, and a conversion of an
1802 // expression of class type to a base class of that type is
1803 // given Conversion rank, in spite of the fact that a copy/move
1804 // constructor (i.e., a user-defined conversion function) is
1805 // called for those cases.
1806 QualType FromType = From->getType();
1807 if (ToType->isRecordType() &&
1808 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1809 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1810 ICS.setStandard();
1812 ICS.Standard.setFromType(FromType);
1813 ICS.Standard.setAllToTypes(ToType);
1814
1815 // We don't actually check at this point whether there is a valid
1816 // copy/move constructor, since overloading just assumes that it
1817 // exists. When we actually perform initialization, we'll find the
1818 // appropriate constructor to copy the returned object, if needed.
1819 ICS.Standard.CopyConstructor = nullptr;
1820
1821 // Determine whether this is considered a derived-to-base conversion.
1822 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1824
1825 return ICS;
1826 }
1827
1828 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1829 FromType->isHLSLAttributedResourceType()) {
1830 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1831 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1832 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1833 FromResType->getWrappedType()) &&
1834 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1835 FromResType->getContainedType()) &&
1836 ToResType->getAttrs() == FromResType->getAttrs()) {
1837 ICS.setStandard();
1839 ICS.Standard.setFromType(FromType);
1840 ICS.Standard.setAllToTypes(ToType);
1841 return ICS;
1842 }
1843 }
1844
1845 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1846 AllowExplicit, InOverloadResolution, CStyle,
1847 AllowObjCWritebackConversion,
1848 AllowObjCConversionOnExplicit);
1849}
1850
1851ImplicitConversionSequence
1853 bool SuppressUserConversions,
1854 AllowedExplicit AllowExplicit,
1855 bool InOverloadResolution,
1856 bool CStyle,
1857 bool AllowObjCWritebackConversion) {
1858 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1859 AllowExplicit, InOverloadResolution, CStyle,
1860 AllowObjCWritebackConversion,
1861 /*AllowObjCConversionOnExplicit=*/false);
1862}
1863
1865 AssignmentAction Action,
1866 bool AllowExplicit) {
1867 if (checkPlaceholderForOverload(*this, From))
1868 return ExprError();
1869
1870 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1871 bool AllowObjCWritebackConversion =
1872 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1873 Action == AssignmentAction::Sending);
1874 if (getLangOpts().ObjC)
1875 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1876 From->getType(), From);
1878 *this, From, ToType,
1879 /*SuppressUserConversions=*/false,
1880 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1881 /*InOverloadResolution=*/false,
1882 /*CStyle=*/false, AllowObjCWritebackConversion,
1883 /*AllowObjCConversionOnExplicit=*/false);
1884 return PerformImplicitConversion(From, ToType, ICS, Action);
1885}
1886
1888 QualType &ResultTy) const {
1889 bool Changed = IsFunctionConversion(FromType, ToType);
1890 if (Changed)
1891 ResultTy = ToType;
1892 return Changed;
1893}
1894
1897 bool *AddingCFIUncheckedCallee) const {
1901 *AddingCFIUncheckedCallee = false;
1902
1903 if (Context.hasSameUnqualifiedType(FromType, ToType))
1904 return false;
1905
1906 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1907 // or F(t noexcept) -> F(t)
1908 // where F adds one of the following at most once:
1909 // - a pointer
1910 // - a member pointer
1911 // - a block pointer
1912 // Changes here need matching changes in FindCompositePointerType.
1913 CanQualType CanTo = Context.getCanonicalType(ToType);
1914 CanQualType CanFrom = Context.getCanonicalType(FromType);
1915 Type::TypeClass TyClass = CanTo->getTypeClass();
1916 if (TyClass != CanFrom->getTypeClass()) return false;
1917 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1918 if (TyClass == Type::Pointer) {
1919 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1920 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1921 } else if (TyClass == Type::BlockPointer) {
1922 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1923 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1924 } else if (TyClass == Type::MemberPointer) {
1925 auto ToMPT = CanTo.castAs<MemberPointerType>();
1926 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1927 // A function pointer conversion cannot change the class of the function.
1928 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1929 FromMPT->getMostRecentCXXRecordDecl()))
1930 return false;
1931 CanTo = ToMPT->getPointeeType();
1932 CanFrom = FromMPT->getPointeeType();
1933 } else {
1934 return false;
1935 }
1936
1937 TyClass = CanTo->getTypeClass();
1938 if (TyClass != CanFrom->getTypeClass()) return false;
1939 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1940 return false;
1941 }
1942
1943 const auto *FromFn = cast<FunctionType>(CanFrom);
1944 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1945
1946 const auto *ToFn = cast<FunctionType>(CanTo);
1947 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1948
1949 bool Changed = false;
1950
1951 // Drop 'noreturn' if not present in target type.
1952 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1953 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1954 Changed = true;
1955 }
1956
1957 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1958 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1959
1960 if (FromFPT && ToFPT) {
1961 if (FromFPT->hasCFIUncheckedCallee() && !ToFPT->hasCFIUncheckedCallee()) {
1962 QualType NewTy = Context.getFunctionType(
1963 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1964 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(false));
1965 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1966 FromFn = FromFPT;
1967 Changed = true;
1970 } else if (!FromFPT->hasCFIUncheckedCallee() &&
1971 ToFPT->hasCFIUncheckedCallee()) {
1972 QualType NewTy = Context.getFunctionType(
1973 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1974 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(true));
1975 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1976 FromFn = FromFPT;
1977 Changed = true;
1980 }
1981 }
1982
1983 // Drop 'noexcept' if not present in target type.
1984 if (FromFPT && ToFPT) {
1985 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1986 FromFn = cast<FunctionType>(
1987 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1988 EST_None)
1989 .getTypePtr());
1990 Changed = true;
1991 }
1992
1993 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1994 // only if the ExtParameterInfo lists of the two function prototypes can be
1995 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1997 bool CanUseToFPT, CanUseFromFPT;
1998 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1999 CanUseFromFPT, NewParamInfos) &&
2000 CanUseToFPT && !CanUseFromFPT) {
2001 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2002 ExtInfo.ExtParameterInfos =
2003 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2004 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2005 FromFPT->getParamTypes(), ExtInfo);
2006 FromFn = QT->getAs<FunctionType>();
2007 Changed = true;
2008 }
2009
2010 // For C, when called from checkPointerTypesForAssignment,
2011 // we need to not alter FromFn, or else even an innocuous cast
2012 // like dropping effects will fail. In C++ however we do want to
2013 // alter FromFn (because of the way PerformImplicitConversion works).
2014 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
2015 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2016
2017 // Transparently add/drop effects; here we are concerned with
2018 // language rules/canonicalization. Adding/dropping effects is a warning.
2019 const auto FromFX = FromFPT->getFunctionEffects();
2020 const auto ToFX = ToFPT->getFunctionEffects();
2021 if (FromFX != ToFX) {
2022 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2023 ExtInfo.FunctionEffects = ToFX;
2024 QualType QT = Context.getFunctionType(
2025 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2026 FromFn = QT->getAs<FunctionType>();
2027 Changed = true;
2028 }
2029 }
2030 }
2031
2032 if (!Changed)
2033 return false;
2034
2035 assert(QualType(FromFn, 0).isCanonical());
2036 if (QualType(FromFn, 0) != CanTo) return false;
2037
2038 return true;
2039}
2040
2041/// Determine whether the conversion from FromType to ToType is a valid
2042/// floating point conversion.
2043///
2044static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2045 QualType ToType) {
2046 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2047 return false;
2048 // FIXME: disable conversions between long double, __ibm128 and __float128
2049 // if their representation is different until there is back end support
2050 // We of course allow this conversion if long double is really double.
2051
2052 // Conversions between bfloat16 and float16 are currently not supported.
2053 if ((FromType->isBFloat16Type() &&
2054 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2055 (ToType->isBFloat16Type() &&
2056 (FromType->isFloat16Type() || FromType->isHalfType())))
2057 return false;
2058
2059 // Conversions between IEEE-quad and IBM-extended semantics are not
2060 // permitted.
2061 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2062 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2063 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2064 &ToSem == &llvm::APFloat::IEEEquad()) ||
2065 (&FromSem == &llvm::APFloat::IEEEquad() &&
2066 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2067 return false;
2068 return true;
2069}
2070
2071static bool IsVectorElementConversion(Sema &S, QualType FromType,
2072 QualType ToType,
2073 ImplicitConversionKind &ICK, Expr *From) {
2074 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2075 return true;
2076
2077 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2079 return true;
2080 }
2081
2082 if (IsFloatingPointConversion(S, FromType, ToType)) {
2084 return true;
2085 }
2086
2087 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2089 return true;
2090 }
2091
2092 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2094 ToType->isRealFloatingType())) {
2096 return true;
2097 }
2098
2099 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2101 return true;
2102 }
2103
2104 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2105 ToType->isIntegralType(S.Context)) {
2107 return true;
2108 }
2109
2110 return false;
2111}
2112
2113/// Determine whether the conversion from FromType to ToType is a valid
2114/// vector conversion.
2115///
2116/// \param ICK Will be set to the vector conversion kind, if this is a vector
2117/// conversion.
2118static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2120 ImplicitConversionKind &ElConv, Expr *From,
2121 bool InOverloadResolution, bool CStyle) {
2122 // We need at least one of these types to be a vector type to have a vector
2123 // conversion.
2124 if (!ToType->isVectorType() && !FromType->isVectorType())
2125 return false;
2126
2127 // Identical types require no conversions.
2128 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2129 return false;
2130
2131 // HLSL allows implicit truncation of vector types.
2132 if (S.getLangOpts().HLSL) {
2133 auto *ToExtType = ToType->getAs<ExtVectorType>();
2134 auto *FromExtType = FromType->getAs<ExtVectorType>();
2135
2136 // If both arguments are vectors, handle possible vector truncation and
2137 // element conversion.
2138 if (ToExtType && FromExtType) {
2139 unsigned FromElts = FromExtType->getNumElements();
2140 unsigned ToElts = ToExtType->getNumElements();
2141 if (FromElts < ToElts)
2142 return false;
2143 if (FromElts == ToElts)
2144 ElConv = ICK_Identity;
2145 else
2147
2148 QualType FromElTy = FromExtType->getElementType();
2149 QualType ToElTy = ToExtType->getElementType();
2150 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2151 return true;
2152 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2153 }
2154 if (FromExtType && !ToExtType) {
2156 QualType FromElTy = FromExtType->getElementType();
2157 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2158 return true;
2159 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2160 }
2161 // Fallthrough for the case where ToType is a vector and FromType is not.
2162 }
2163
2164 // There are no conversions between extended vector types, only identity.
2165 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2166 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2167 // Implicit conversions require the same number of elements.
2168 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2169 return false;
2170
2171 // Permit implicit conversions from integral values to boolean vectors.
2172 if (ToType->isExtVectorBoolType() &&
2173 FromExtType->getElementType()->isIntegerType()) {
2175 return true;
2176 }
2177 // There are no other conversions between extended vector types.
2178 return false;
2179 }
2180
2181 // Vector splat from any arithmetic type to a vector.
2182 if (FromType->isArithmeticType()) {
2183 if (S.getLangOpts().HLSL) {
2184 ElConv = ICK_HLSL_Vector_Splat;
2185 QualType ToElTy = ToExtType->getElementType();
2186 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2187 }
2188 ICK = ICK_Vector_Splat;
2189 return true;
2190 }
2191 }
2192
2193 if (ToType->isSVESizelessBuiltinType() ||
2194 FromType->isSVESizelessBuiltinType())
2195 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2196 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2198 return true;
2199 }
2200
2201 if (ToType->isRVVSizelessBuiltinType() ||
2202 FromType->isRVVSizelessBuiltinType())
2203 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2204 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2206 return true;
2207 }
2208
2209 // We can perform the conversion between vector types in the following cases:
2210 // 1)vector types are equivalent AltiVec and GCC vector types
2211 // 2)lax vector conversions are permitted and the vector types are of the
2212 // same size
2213 // 3)the destination type does not have the ARM MVE strict-polymorphism
2214 // attribute, which inhibits lax vector conversion for overload resolution
2215 // only
2216 if (ToType->isVectorType() && FromType->isVectorType()) {
2217 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2218 (S.isLaxVectorConversion(FromType, ToType) &&
2219 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2220 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2221 S.isLaxVectorConversion(FromType, ToType) &&
2222 S.anyAltivecTypes(FromType, ToType) &&
2223 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2224 !InOverloadResolution && !CStyle) {
2225 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2226 << FromType << ToType;
2227 }
2229 return true;
2230 }
2231 }
2232
2233 return false;
2234}
2235
2236static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2237 bool InOverloadResolution,
2238 StandardConversionSequence &SCS,
2239 bool CStyle);
2240
2241/// IsStandardConversion - Determines whether there is a standard
2242/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2243/// expression From to the type ToType. Standard conversion sequences
2244/// only consider non-class types; for conversions that involve class
2245/// types, use TryImplicitConversion. If a conversion exists, SCS will
2246/// contain the standard conversion sequence required to perform this
2247/// conversion and this routine will return true. Otherwise, this
2248/// routine will return false and the value of SCS is unspecified.
2249static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2250 bool InOverloadResolution,
2252 bool CStyle,
2253 bool AllowObjCWritebackConversion) {
2254 QualType FromType = From->getType();
2255
2256 // Standard conversions (C++ [conv])
2258 SCS.IncompatibleObjC = false;
2259 SCS.setFromType(FromType);
2260 SCS.CopyConstructor = nullptr;
2261
2262 // There are no standard conversions for class types in C++, so
2263 // abort early. When overloading in C, however, we do permit them.
2264 if (S.getLangOpts().CPlusPlus &&
2265 (FromType->isRecordType() || ToType->isRecordType()))
2266 return false;
2267
2268 // The first conversion can be an lvalue-to-rvalue conversion,
2269 // array-to-pointer conversion, or function-to-pointer conversion
2270 // (C++ 4p1).
2271
2272 if (FromType == S.Context.OverloadTy) {
2273 DeclAccessPair AccessPair;
2274 if (FunctionDecl *Fn
2275 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2276 AccessPair)) {
2277 // We were able to resolve the address of the overloaded function,
2278 // so we can convert to the type of that function.
2279 FromType = Fn->getType();
2280 SCS.setFromType(FromType);
2281
2282 // we can sometimes resolve &foo<int> regardless of ToType, so check
2283 // if the type matches (identity) or we are converting to bool
2285 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2286 // if the function type matches except for [[noreturn]], it's ok
2287 if (!S.IsFunctionConversion(FromType,
2289 // otherwise, only a boolean conversion is standard
2290 if (!ToType->isBooleanType())
2291 return false;
2292 }
2293
2294 // Check if the "from" expression is taking the address of an overloaded
2295 // function and recompute the FromType accordingly. Take advantage of the
2296 // fact that non-static member functions *must* have such an address-of
2297 // expression.
2298 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2299 if (Method && !Method->isStatic() &&
2300 !Method->isExplicitObjectMemberFunction()) {
2301 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2302 "Non-unary operator on non-static member address");
2303 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2304 == UO_AddrOf &&
2305 "Non-address-of operator on non-static member address");
2306 FromType = S.Context.getMemberPointerType(
2307 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2308 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2309 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2310 UO_AddrOf &&
2311 "Non-address-of operator for overloaded function expression");
2312 FromType = S.Context.getPointerType(FromType);
2313 }
2314 } else {
2315 return false;
2316 }
2317 }
2318
2319 bool argIsLValue = From->isGLValue();
2320 // To handle conversion from ArrayParameterType to ConstantArrayType
2321 // this block must be above the one below because Array parameters
2322 // do not decay and when handling HLSLOutArgExprs and
2323 // the From expression is an LValue.
2324 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2325 ToType->isConstantArrayType()) {
2326 // HLSL constant array parameters do not decay, so if the argument is a
2327 // constant array and the parameter is an ArrayParameterType we have special
2328 // handling here.
2329 if (ToType->isArrayParameterType()) {
2330 FromType = S.Context.getArrayParameterType(FromType);
2331 } else if (FromType->isArrayParameterType()) {
2332 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2333 FromType = APT->getConstantArrayType(S.Context);
2334 }
2335
2337
2338 // Don't consider qualifiers, which include things like address spaces
2339 if (FromType.getCanonicalType().getUnqualifiedType() !=
2341 return false;
2342
2343 SCS.setAllToTypes(ToType);
2344 return true;
2345 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2346 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2347 // Lvalue-to-rvalue conversion (C++11 4.1):
2348 // A glvalue (3.10) of a non-function, non-array type T can
2349 // be converted to a prvalue.
2350
2352
2353 // C11 6.3.2.1p2:
2354 // ... if the lvalue has atomic type, the value has the non-atomic version
2355 // of the type of the lvalue ...
2356 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2357 FromType = Atomic->getValueType();
2358
2359 // If T is a non-class type, the type of the rvalue is the
2360 // cv-unqualified version of T. Otherwise, the type of the rvalue
2361 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2362 // just strip the qualifiers because they don't matter.
2363 FromType = FromType.getUnqualifiedType();
2364 } else if (FromType->isArrayType()) {
2365 // Array-to-pointer conversion (C++ 4.2)
2367
2368 // An lvalue or rvalue of type "array of N T" or "array of unknown
2369 // bound of T" can be converted to an rvalue of type "pointer to
2370 // T" (C++ 4.2p1).
2371 FromType = S.Context.getArrayDecayedType(FromType);
2372
2373 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2374 // This conversion is deprecated in C++03 (D.4)
2376
2377 // For the purpose of ranking in overload resolution
2378 // (13.3.3.1.1), this conversion is considered an
2379 // array-to-pointer conversion followed by a qualification
2380 // conversion (4.4). (C++ 4.2p2)
2381 SCS.Second = ICK_Identity;
2384 SCS.setAllToTypes(FromType);
2385 return true;
2386 }
2387 } else if (FromType->isFunctionType() && argIsLValue) {
2388 // Function-to-pointer conversion (C++ 4.3).
2390
2391 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2392 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2394 return false;
2395
2396 // An lvalue of function type T can be converted to an rvalue of
2397 // type "pointer to T." The result is a pointer to the
2398 // function. (C++ 4.3p1).
2399 FromType = S.Context.getPointerType(FromType);
2400 } else {
2401 // We don't require any conversions for the first step.
2402 SCS.First = ICK_Identity;
2403 }
2404 SCS.setToType(0, FromType);
2405
2406 // The second conversion can be an integral promotion, floating
2407 // point promotion, integral conversion, floating point conversion,
2408 // floating-integral conversion, pointer conversion,
2409 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2410 // For overloading in C, this can also be a "compatible-type"
2411 // conversion.
2412 bool IncompatibleObjC = false;
2414 ImplicitConversionKind DimensionICK = ICK_Identity;
2415 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2416 // The unqualified versions of the types are the same: there's no
2417 // conversion to do.
2418 SCS.Second = ICK_Identity;
2419 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2420 // Integral promotion (C++ 4.5).
2422 FromType = ToType.getUnqualifiedType();
2423 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2424 // Floating point promotion (C++ 4.6).
2426 FromType = ToType.getUnqualifiedType();
2427 } else if (S.IsComplexPromotion(FromType, ToType)) {
2428 // Complex promotion (Clang extension)
2430 FromType = ToType.getUnqualifiedType();
2431 } else if (ToType->isBooleanType() &&
2432 (FromType->isArithmeticType() ||
2433 FromType->isAnyPointerType() ||
2434 FromType->isBlockPointerType() ||
2435 FromType->isMemberPointerType())) {
2436 // Boolean conversions (C++ 4.12).
2438 FromType = S.Context.BoolTy;
2439 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2440 ToType->isIntegralType(S.Context)) {
2441 // Integral conversions (C++ 4.7).
2443 FromType = ToType.getUnqualifiedType();
2444 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2445 // Complex conversions (C99 6.3.1.6)
2447 FromType = ToType.getUnqualifiedType();
2448 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2449 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2450 // Complex-real conversions (C99 6.3.1.7)
2452 FromType = ToType.getUnqualifiedType();
2453 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2454 // Floating point conversions (C++ 4.8).
2456 FromType = ToType.getUnqualifiedType();
2457 } else if ((FromType->isRealFloatingType() &&
2458 ToType->isIntegralType(S.Context)) ||
2460 ToType->isRealFloatingType())) {
2461
2462 // Floating-integral conversions (C++ 4.9).
2464 FromType = ToType.getUnqualifiedType();
2465 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2467 } else if (AllowObjCWritebackConversion &&
2468 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2470 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2471 FromType, IncompatibleObjC)) {
2472 // Pointer conversions (C++ 4.10).
2474 SCS.IncompatibleObjC = IncompatibleObjC;
2475 FromType = FromType.getUnqualifiedType();
2476 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2477 InOverloadResolution, FromType)) {
2478 // Pointer to member conversions (4.11).
2480 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2481 From, InOverloadResolution, CStyle)) {
2482 SCS.Second = SecondICK;
2483 SCS.Dimension = DimensionICK;
2484 FromType = ToType.getUnqualifiedType();
2485 } else if (!S.getLangOpts().CPlusPlus &&
2486 S.Context.typesAreCompatible(ToType, FromType)) {
2487 // Compatible conversions (Clang extension for C function overloading)
2489 FromType = ToType.getUnqualifiedType();
2491 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2493 FromType = ToType;
2494 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2495 CStyle)) {
2496 // tryAtomicConversion has updated the standard conversion sequence
2497 // appropriately.
2498 return true;
2499 } else if (ToType->isEventT() &&
2501 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2503 FromType = ToType;
2504 } else if (ToType->isQueueT() &&
2506 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2508 FromType = ToType;
2509 } else if (ToType->isSamplerT() &&
2512 FromType = ToType;
2513 } else if ((ToType->isFixedPointType() &&
2514 FromType->isConvertibleToFixedPointType()) ||
2515 (FromType->isFixedPointType() &&
2516 ToType->isConvertibleToFixedPointType())) {
2518 FromType = ToType;
2519 } else {
2520 // No second conversion required.
2521 SCS.Second = ICK_Identity;
2522 }
2523 SCS.setToType(1, FromType);
2524
2525 // The third conversion can be a function pointer conversion or a
2526 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2527 bool ObjCLifetimeConversion;
2528 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2529 // Function pointer conversions (removing 'noexcept') including removal of
2530 // 'noreturn' (Clang extension).
2532 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2533 ObjCLifetimeConversion)) {
2535 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2536 FromType = ToType;
2537 } else {
2538 // No conversion required
2539 SCS.Third = ICK_Identity;
2540 }
2541
2542 // C++ [over.best.ics]p6:
2543 // [...] Any difference in top-level cv-qualification is
2544 // subsumed by the initialization itself and does not constitute
2545 // a conversion. [...]
2546 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2547 QualType CanonTo = S.Context.getCanonicalType(ToType);
2548 if (CanonFrom.getLocalUnqualifiedType()
2549 == CanonTo.getLocalUnqualifiedType() &&
2550 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2551 FromType = ToType;
2552 CanonFrom = CanonTo;
2553 }
2554
2555 SCS.setToType(2, FromType);
2556
2557 // If we have not converted the argument type to the parameter type,
2558 // this is a bad conversion sequence, unless we're resolving an overload in C.
2559 //
2560 // Permit conversions from a function without `cfi_unchecked_callee` to a
2561 // function with `cfi_unchecked_callee`.
2562 if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(CanonFrom, CanonTo))
2563 return true;
2564
2565 if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2566 return false;
2567
2568 ExprResult ER = ExprResult{From};
2569 AssignConvertType Conv =
2571 /*Diagnose=*/false,
2572 /*DiagnoseCFAudited=*/false,
2573 /*ConvertRHS=*/false);
2574 ImplicitConversionKind SecondConv;
2575 switch (Conv) {
2577 case AssignConvertType::
2578 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2579 SecondConv = ICK_C_Only_Conversion;
2580 break;
2581 // For our purposes, discarding qualifiers is just as bad as using an
2582 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2583 // qualifiers, as well.
2588 break;
2589 default:
2590 return false;
2591 }
2592
2593 // First can only be an lvalue conversion, so we pretend that this was the
2594 // second conversion. First should already be valid from earlier in the
2595 // function.
2596 SCS.Second = SecondConv;
2597 SCS.setToType(1, ToType);
2598
2599 // Third is Identity, because Second should rank us worse than any other
2600 // conversion. This could also be ICK_Qualification, but it's simpler to just
2601 // lump everything in with the second conversion, and we don't gain anything
2602 // from making this ICK_Qualification.
2603 SCS.Third = ICK_Identity;
2604 SCS.setToType(2, ToType);
2605 return true;
2606}
2607
2608static bool
2610 QualType &ToType,
2611 bool InOverloadResolution,
2613 bool CStyle) {
2614
2615 const RecordType *UT = ToType->getAsUnionType();
2616 if (!UT)
2617 return false;
2618 // The field to initialize within the transparent union.
2619 const RecordDecl *UD = UT->getOriginalDecl()->getDefinitionOrSelf();
2620 if (!UD->hasAttr<TransparentUnionAttr>())
2621 return false;
2622 // It's compatible if the expression matches any of the fields.
2623 for (const auto *it : UD->fields()) {
2624 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2625 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2626 ToType = it->getType();
2627 return true;
2628 }
2629 }
2630 return false;
2631}
2632
2633bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2634 const BuiltinType *To = ToType->getAs<BuiltinType>();
2635 // All integers are built-in.
2636 if (!To) {
2637 return false;
2638 }
2639
2640 // An rvalue of type char, signed char, unsigned char, short int, or
2641 // unsigned short int can be converted to an rvalue of type int if
2642 // int can represent all the values of the source type; otherwise,
2643 // the source rvalue can be converted to an rvalue of type unsigned
2644 // int (C++ 4.5p1).
2645 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2646 !FromType->isEnumeralType()) {
2647 if ( // We can promote any signed, promotable integer type to an int
2648 (FromType->isSignedIntegerType() ||
2649 // We can promote any unsigned integer type whose size is
2650 // less than int to an int.
2651 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2652 return To->getKind() == BuiltinType::Int;
2653 }
2654
2655 return To->getKind() == BuiltinType::UInt;
2656 }
2657
2658 // C++11 [conv.prom]p3:
2659 // A prvalue of an unscoped enumeration type whose underlying type is not
2660 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2661 // following types that can represent all the values of the enumeration
2662 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2663 // unsigned int, long int, unsigned long int, long long int, or unsigned
2664 // long long int. If none of the types in that list can represent all the
2665 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2666 // type can be converted to an rvalue a prvalue of the extended integer type
2667 // with lowest integer conversion rank (4.13) greater than the rank of long
2668 // long in which all the values of the enumeration can be represented. If
2669 // there are two such extended types, the signed one is chosen.
2670 // C++11 [conv.prom]p4:
2671 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2672 // can be converted to a prvalue of its underlying type. Moreover, if
2673 // integral promotion can be applied to its underlying type, a prvalue of an
2674 // unscoped enumeration type whose underlying type is fixed can also be
2675 // converted to a prvalue of the promoted underlying type.
2676 if (const auto *FromED = FromType->getAsEnumDecl()) {
2677 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2678 // provided for a scoped enumeration.
2679 if (FromED->isScoped())
2680 return false;
2681
2682 // We can perform an integral promotion to the underlying type of the enum,
2683 // even if that's not the promoted type. Note that the check for promoting
2684 // the underlying type is based on the type alone, and does not consider
2685 // the bitfield-ness of the actual source expression.
2686 if (FromED->isFixed()) {
2687 QualType Underlying = FromED->getIntegerType();
2688 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2689 IsIntegralPromotion(nullptr, Underlying, ToType);
2690 }
2691
2692 // We have already pre-calculated the promotion type, so this is trivial.
2693 if (ToType->isIntegerType() &&
2694 isCompleteType(From->getBeginLoc(), FromType))
2695 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2696
2697 // C++ [conv.prom]p5:
2698 // If the bit-field has an enumerated type, it is treated as any other
2699 // value of that type for promotion purposes.
2700 //
2701 // ... so do not fall through into the bit-field checks below in C++.
2702 if (getLangOpts().CPlusPlus)
2703 return false;
2704 }
2705
2706 // C++0x [conv.prom]p2:
2707 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2708 // to an rvalue a prvalue of the first of the following types that can
2709 // represent all the values of its underlying type: int, unsigned int,
2710 // long int, unsigned long int, long long int, or unsigned long long int.
2711 // If none of the types in that list can represent all the values of its
2712 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2713 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2714 // type.
2715 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2716 ToType->isIntegerType()) {
2717 // Determine whether the type we're converting from is signed or
2718 // unsigned.
2719 bool FromIsSigned = FromType->isSignedIntegerType();
2720 uint64_t FromSize = Context.getTypeSize(FromType);
2721
2722 // The types we'll try to promote to, in the appropriate
2723 // order. Try each of these types.
2724 QualType PromoteTypes[6] = {
2725 Context.IntTy, Context.UnsignedIntTy,
2726 Context.LongTy, Context.UnsignedLongTy ,
2727 Context.LongLongTy, Context.UnsignedLongLongTy
2728 };
2729 for (int Idx = 0; Idx < 6; ++Idx) {
2730 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2731 if (FromSize < ToSize ||
2732 (FromSize == ToSize &&
2733 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2734 // We found the type that we can promote to. If this is the
2735 // type we wanted, we have a promotion. Otherwise, no
2736 // promotion.
2737 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2738 }
2739 }
2740 }
2741
2742 // An rvalue for an integral bit-field (9.6) can be converted to an
2743 // rvalue of type int if int can represent all the values of the
2744 // bit-field; otherwise, it can be converted to unsigned int if
2745 // unsigned int can represent all the values of the bit-field. If
2746 // the bit-field is larger yet, no integral promotion applies to
2747 // it. If the bit-field has an enumerated type, it is treated as any
2748 // other value of that type for promotion purposes (C++ 4.5p3).
2749 // FIXME: We should delay checking of bit-fields until we actually perform the
2750 // conversion.
2751 //
2752 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2753 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2754 // bit-fields and those whose underlying type is larger than int) for GCC
2755 // compatibility.
2756 if (From) {
2757 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2758 std::optional<llvm::APSInt> BitWidth;
2759 if (FromType->isIntegralType(Context) &&
2760 (BitWidth =
2761 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2762 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2763 ToSize = Context.getTypeSize(ToType);
2764
2765 // Are we promoting to an int from a bitfield that fits in an int?
2766 if (*BitWidth < ToSize ||
2767 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2768 return To->getKind() == BuiltinType::Int;
2769 }
2770
2771 // Are we promoting to an unsigned int from an unsigned bitfield
2772 // that fits into an unsigned int?
2773 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2774 return To->getKind() == BuiltinType::UInt;
2775 }
2776
2777 return false;
2778 }
2779 }
2780 }
2781
2782 // An rvalue of type bool can be converted to an rvalue of type int,
2783 // with false becoming zero and true becoming one (C++ 4.5p4).
2784 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2785 return true;
2786 }
2787
2788 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2789 // integral type.
2790 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2791 ToType->isIntegerType())
2792 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2793
2794 return false;
2795}
2796
2798 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2799 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2800 /// An rvalue of type float can be converted to an rvalue of type
2801 /// double. (C++ 4.6p1).
2802 if (FromBuiltin->getKind() == BuiltinType::Float &&
2803 ToBuiltin->getKind() == BuiltinType::Double)
2804 return true;
2805
2806 // C99 6.3.1.5p1:
2807 // When a float is promoted to double or long double, or a
2808 // double is promoted to long double [...].
2809 if (!getLangOpts().CPlusPlus &&
2810 (FromBuiltin->getKind() == BuiltinType::Float ||
2811 FromBuiltin->getKind() == BuiltinType::Double) &&
2812 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2813 ToBuiltin->getKind() == BuiltinType::Float128 ||
2814 ToBuiltin->getKind() == BuiltinType::Ibm128))
2815 return true;
2816
2817 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2818 // or not native half types are enabled.
2819 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2820 (ToBuiltin->getKind() == BuiltinType::Float ||
2821 ToBuiltin->getKind() == BuiltinType::Double))
2822 return true;
2823
2824 // Half can be promoted to float.
2825 if (!getLangOpts().NativeHalfType &&
2826 FromBuiltin->getKind() == BuiltinType::Half &&
2827 ToBuiltin->getKind() == BuiltinType::Float)
2828 return true;
2829 }
2830
2831 return false;
2832}
2833
2835 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2836 if (!FromComplex)
2837 return false;
2838
2839 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2840 if (!ToComplex)
2841 return false;
2842
2843 return IsFloatingPointPromotion(FromComplex->getElementType(),
2844 ToComplex->getElementType()) ||
2845 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2846 ToComplex->getElementType());
2847}
2848
2849/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2850/// the pointer type FromPtr to a pointer to type ToPointee, with the
2851/// same type qualifiers as FromPtr has on its pointee type. ToType,
2852/// if non-empty, will be a pointer to ToType that may or may not have
2853/// the right set of qualifiers on its pointee.
2854///
2855static QualType
2857 QualType ToPointee, QualType ToType,
2858 ASTContext &Context,
2859 bool StripObjCLifetime = false) {
2860 assert((FromPtr->getTypeClass() == Type::Pointer ||
2861 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2862 "Invalid similarly-qualified pointer type");
2863
2864 /// Conversions to 'id' subsume cv-qualifier conversions.
2865 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2866 return ToType.getUnqualifiedType();
2867
2868 QualType CanonFromPointee
2869 = Context.getCanonicalType(FromPtr->getPointeeType());
2870 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2871 Qualifiers Quals = CanonFromPointee.getQualifiers();
2872
2873 if (StripObjCLifetime)
2874 Quals.removeObjCLifetime();
2875
2876 // Exact qualifier match -> return the pointer type we're converting to.
2877 if (CanonToPointee.getLocalQualifiers() == Quals) {
2878 // ToType is exactly what we need. Return it.
2879 if (!ToType.isNull())
2880 return ToType.getUnqualifiedType();
2881
2882 // Build a pointer to ToPointee. It has the right qualifiers
2883 // already.
2884 if (isa<ObjCObjectPointerType>(ToType))
2885 return Context.getObjCObjectPointerType(ToPointee);
2886 return Context.getPointerType(ToPointee);
2887 }
2888
2889 // Just build a canonical type that has the right qualifiers.
2890 QualType QualifiedCanonToPointee
2891 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2892
2893 if (isa<ObjCObjectPointerType>(ToType))
2894 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2895 return Context.getPointerType(QualifiedCanonToPointee);
2896}
2897
2899 bool InOverloadResolution,
2900 ASTContext &Context) {
2901 // Handle value-dependent integral null pointer constants correctly.
2902 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2903 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2905 return !InOverloadResolution;
2906
2907 return Expr->isNullPointerConstant(Context,
2908 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2910}
2911
2913 bool InOverloadResolution,
2914 QualType& ConvertedType,
2915 bool &IncompatibleObjC) {
2916 IncompatibleObjC = false;
2917 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2918 IncompatibleObjC))
2919 return true;
2920
2921 // Conversion from a null pointer constant to any Objective-C pointer type.
2922 if (ToType->isObjCObjectPointerType() &&
2923 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2924 ConvertedType = ToType;
2925 return true;
2926 }
2927
2928 // Blocks: Block pointers can be converted to void*.
2929 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2930 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2931 ConvertedType = ToType;
2932 return true;
2933 }
2934 // Blocks: A null pointer constant can be converted to a block
2935 // pointer type.
2936 if (ToType->isBlockPointerType() &&
2937 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2938 ConvertedType = ToType;
2939 return true;
2940 }
2941
2942 // If the left-hand-side is nullptr_t, the right side can be a null
2943 // pointer constant.
2944 if (ToType->isNullPtrType() &&
2945 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2946 ConvertedType = ToType;
2947 return true;
2948 }
2949
2950 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2951 if (!ToTypePtr)
2952 return false;
2953
2954 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2955 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2956 ConvertedType = ToType;
2957 return true;
2958 }
2959
2960 // Beyond this point, both types need to be pointers
2961 // , including objective-c pointers.
2962 QualType ToPointeeType = ToTypePtr->getPointeeType();
2963 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2964 !getLangOpts().ObjCAutoRefCount) {
2965 ConvertedType = BuildSimilarlyQualifiedPointerType(
2966 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2967 Context);
2968 return true;
2969 }
2970 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2971 if (!FromTypePtr)
2972 return false;
2973
2974 QualType FromPointeeType = FromTypePtr->getPointeeType();
2975
2976 // If the unqualified pointee types are the same, this can't be a
2977 // pointer conversion, so don't do all of the work below.
2978 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2979 return false;
2980
2981 // An rvalue of type "pointer to cv T," where T is an object type,
2982 // can be converted to an rvalue of type "pointer to cv void" (C++
2983 // 4.10p2).
2984 if (FromPointeeType->isIncompleteOrObjectType() &&
2985 ToPointeeType->isVoidType()) {
2986 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2987 ToPointeeType,
2988 ToType, Context,
2989 /*StripObjCLifetime=*/true);
2990 return true;
2991 }
2992
2993 // MSVC allows implicit function to void* type conversion.
2994 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2995 ToPointeeType->isVoidType()) {
2996 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2997 ToPointeeType,
2998 ToType, Context);
2999 return true;
3000 }
3001
3002 // When we're overloading in C, we allow a special kind of pointer
3003 // conversion for compatible-but-not-identical pointee types.
3004 if (!getLangOpts().CPlusPlus &&
3005 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3007 ToPointeeType,
3008 ToType, Context);
3009 return true;
3010 }
3011
3012 // C++ [conv.ptr]p3:
3013 //
3014 // An rvalue of type "pointer to cv D," where D is a class type,
3015 // can be converted to an rvalue of type "pointer to cv B," where
3016 // B is a base class (clause 10) of D. If B is an inaccessible
3017 // (clause 11) or ambiguous (10.2) base class of D, a program that
3018 // necessitates this conversion is ill-formed. The result of the
3019 // conversion is a pointer to the base class sub-object of the
3020 // derived class object. The null pointer value is converted to
3021 // the null pointer value of the destination type.
3022 //
3023 // Note that we do not check for ambiguity or inaccessibility
3024 // here. That is handled by CheckPointerConversion.
3025 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3026 ToPointeeType->isRecordType() &&
3027 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3028 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3029 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3030 ToPointeeType,
3031 ToType, Context);
3032 return true;
3033 }
3034
3035 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3036 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3037 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3038 ToPointeeType,
3039 ToType, Context);
3040 return true;
3041 }
3042
3043 return false;
3044}
3045
3046/// Adopt the given qualifiers for the given type.
3048 Qualifiers TQs = T.getQualifiers();
3049
3050 // Check whether qualifiers already match.
3051 if (TQs == Qs)
3052 return T;
3053
3054 if (Qs.compatiblyIncludes(TQs, Context))
3055 return Context.getQualifiedType(T, Qs);
3056
3057 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3058}
3059
3061 QualType& ConvertedType,
3062 bool &IncompatibleObjC) {
3063 if (!getLangOpts().ObjC)
3064 return false;
3065
3066 // The set of qualifiers on the type we're converting from.
3067 Qualifiers FromQualifiers = FromType.getQualifiers();
3068
3069 // First, we handle all conversions on ObjC object pointer types.
3070 const ObjCObjectPointerType* ToObjCPtr =
3071 ToType->getAs<ObjCObjectPointerType>();
3072 const ObjCObjectPointerType *FromObjCPtr =
3073 FromType->getAs<ObjCObjectPointerType>();
3074
3075 if (ToObjCPtr && FromObjCPtr) {
3076 // If the pointee types are the same (ignoring qualifications),
3077 // then this is not a pointer conversion.
3078 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3079 FromObjCPtr->getPointeeType()))
3080 return false;
3081
3082 // Conversion between Objective-C pointers.
3083 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3084 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3085 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3086 if (getLangOpts().CPlusPlus && LHS && RHS &&
3088 FromObjCPtr->getPointeeType(), getASTContext()))
3089 return false;
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3091 ToObjCPtr->getPointeeType(),
3092 ToType, Context);
3093 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3094 return true;
3095 }
3096
3097 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3098 // Okay: this is some kind of implicit downcast of Objective-C
3099 // interfaces, which is permitted. However, we're going to
3100 // complain about it.
3101 IncompatibleObjC = true;
3102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3103 ToObjCPtr->getPointeeType(),
3104 ToType, Context);
3105 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3106 return true;
3107 }
3108 }
3109 // Beyond this point, both types need to be C pointers or block pointers.
3110 QualType ToPointeeType;
3111 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3112 ToPointeeType = ToCPtr->getPointeeType();
3113 else if (const BlockPointerType *ToBlockPtr =
3114 ToType->getAs<BlockPointerType>()) {
3115 // Objective C++: We're able to convert from a pointer to any object
3116 // to a block pointer type.
3117 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3118 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3119 return true;
3120 }
3121 ToPointeeType = ToBlockPtr->getPointeeType();
3122 }
3123 else if (FromType->getAs<BlockPointerType>() &&
3124 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3125 // Objective C++: We're able to convert from a block pointer type to a
3126 // pointer to any object.
3127 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3128 return true;
3129 }
3130 else
3131 return false;
3132
3133 QualType FromPointeeType;
3134 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3135 FromPointeeType = FromCPtr->getPointeeType();
3136 else if (const BlockPointerType *FromBlockPtr =
3137 FromType->getAs<BlockPointerType>())
3138 FromPointeeType = FromBlockPtr->getPointeeType();
3139 else
3140 return false;
3141
3142 // If we have pointers to pointers, recursively check whether this
3143 // is an Objective-C conversion.
3144 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3145 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3146 IncompatibleObjC)) {
3147 // We always complain about this conversion.
3148 IncompatibleObjC = true;
3149 ConvertedType = Context.getPointerType(ConvertedType);
3150 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3151 return true;
3152 }
3153 // Allow conversion of pointee being objective-c pointer to another one;
3154 // as in I* to id.
3155 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3156 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3157 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3158 IncompatibleObjC)) {
3159
3160 ConvertedType = Context.getPointerType(ConvertedType);
3161 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3162 return true;
3163 }
3164
3165 // If we have pointers to functions or blocks, check whether the only
3166 // differences in the argument and result types are in Objective-C
3167 // pointer conversions. If so, we permit the conversion (but
3168 // complain about it).
3169 const FunctionProtoType *FromFunctionType
3170 = FromPointeeType->getAs<FunctionProtoType>();
3171 const FunctionProtoType *ToFunctionType
3172 = ToPointeeType->getAs<FunctionProtoType>();
3173 if (FromFunctionType && ToFunctionType) {
3174 // If the function types are exactly the same, this isn't an
3175 // Objective-C pointer conversion.
3176 if (Context.getCanonicalType(FromPointeeType)
3177 == Context.getCanonicalType(ToPointeeType))
3178 return false;
3179
3180 // Perform the quick checks that will tell us whether these
3181 // function types are obviously different.
3182 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3183 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3184 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3185 return false;
3186
3187 bool HasObjCConversion = false;
3188 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3189 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3190 // Okay, the types match exactly. Nothing to do.
3191 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3192 ToFunctionType->getReturnType(),
3193 ConvertedType, IncompatibleObjC)) {
3194 // Okay, we have an Objective-C pointer conversion.
3195 HasObjCConversion = true;
3196 } else {
3197 // Function types are too different. Abort.
3198 return false;
3199 }
3200
3201 // Check argument types.
3202 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3203 ArgIdx != NumArgs; ++ArgIdx) {
3204 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3205 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3206 if (Context.getCanonicalType(FromArgType)
3207 == Context.getCanonicalType(ToArgType)) {
3208 // Okay, the types match exactly. Nothing to do.
3209 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3210 ConvertedType, IncompatibleObjC)) {
3211 // Okay, we have an Objective-C pointer conversion.
3212 HasObjCConversion = true;
3213 } else {
3214 // Argument types are too different. Abort.
3215 return false;
3216 }
3217 }
3218
3219 if (HasObjCConversion) {
3220 // We had an Objective-C conversion. Allow this pointer
3221 // conversion, but complain about it.
3222 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3223 IncompatibleObjC = true;
3224 return true;
3225 }
3226 }
3227
3228 return false;
3229}
3230
3232 QualType& ConvertedType) {
3233 QualType ToPointeeType;
3234 if (const BlockPointerType *ToBlockPtr =
3235 ToType->getAs<BlockPointerType>())
3236 ToPointeeType = ToBlockPtr->getPointeeType();
3237 else
3238 return false;
3239
3240 QualType FromPointeeType;
3241 if (const BlockPointerType *FromBlockPtr =
3242 FromType->getAs<BlockPointerType>())
3243 FromPointeeType = FromBlockPtr->getPointeeType();
3244 else
3245 return false;
3246 // We have pointer to blocks, check whether the only
3247 // differences in the argument and result types are in Objective-C
3248 // pointer conversions. If so, we permit the conversion.
3249
3250 const FunctionProtoType *FromFunctionType
3251 = FromPointeeType->getAs<FunctionProtoType>();
3252 const FunctionProtoType *ToFunctionType
3253 = ToPointeeType->getAs<FunctionProtoType>();
3254
3255 if (!FromFunctionType || !ToFunctionType)
3256 return false;
3257
3258 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3259 return true;
3260
3261 // Perform the quick checks that will tell us whether these
3262 // function types are obviously different.
3263 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3264 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3265 return false;
3266
3267 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3268 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3269 if (FromEInfo != ToEInfo)
3270 return false;
3271
3272 bool IncompatibleObjC = false;
3273 if (Context.hasSameType(FromFunctionType->getReturnType(),
3274 ToFunctionType->getReturnType())) {
3275 // Okay, the types match exactly. Nothing to do.
3276 } else {
3277 QualType RHS = FromFunctionType->getReturnType();
3278 QualType LHS = ToFunctionType->getReturnType();
3279 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3280 !RHS.hasQualifiers() && LHS.hasQualifiers())
3281 LHS = LHS.getUnqualifiedType();
3282
3283 if (Context.hasSameType(RHS,LHS)) {
3284 // OK exact match.
3285 } else if (isObjCPointerConversion(RHS, LHS,
3286 ConvertedType, IncompatibleObjC)) {
3287 if (IncompatibleObjC)
3288 return false;
3289 // Okay, we have an Objective-C pointer conversion.
3290 }
3291 else
3292 return false;
3293 }
3294
3295 // Check argument types.
3296 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3297 ArgIdx != NumArgs; ++ArgIdx) {
3298 IncompatibleObjC = false;
3299 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3300 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3301 if (Context.hasSameType(FromArgType, ToArgType)) {
3302 // Okay, the types match exactly. Nothing to do.
3303 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3304 ConvertedType, IncompatibleObjC)) {
3305 if (IncompatibleObjC)
3306 return false;
3307 // Okay, we have an Objective-C pointer conversion.
3308 } else
3309 // Argument types are too different. Abort.
3310 return false;
3311 }
3312
3314 bool CanUseToFPT, CanUseFromFPT;
3315 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3316 CanUseToFPT, CanUseFromFPT,
3317 NewParamInfos))
3318 return false;
3319
3320 ConvertedType = ToType;
3321 return true;
3322}
3323
3324enum {
3332};
3333
3334/// Attempts to get the FunctionProtoType from a Type. Handles
3335/// MemberFunctionPointers properly.
3337 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3338 return FPT;
3339
3340 if (auto *MPT = FromType->getAs<MemberPointerType>())
3341 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3342
3343 return nullptr;
3344}
3345
3347 QualType FromType, QualType ToType) {
3348 // If either type is not valid, include no extra info.
3349 if (FromType.isNull() || ToType.isNull()) {
3350 PDiag << ft_default;
3351 return;
3352 }
3353
3354 // Get the function type from the pointers.
3355 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3356 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3357 *ToMember = ToType->castAs<MemberPointerType>();
3358 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3359 ToMember->getMostRecentCXXRecordDecl())) {
3361 if (ToMember->isSugared())
3362 PDiag << Context.getCanonicalTagType(
3363 ToMember->getMostRecentCXXRecordDecl());
3364 else
3365 PDiag << ToMember->getQualifier();
3366 if (FromMember->isSugared())
3367 PDiag << Context.getCanonicalTagType(
3368 FromMember->getMostRecentCXXRecordDecl());
3369 else
3370 PDiag << FromMember->getQualifier();
3371 return;
3372 }
3373 FromType = FromMember->getPointeeType();
3374 ToType = ToMember->getPointeeType();
3375 }
3376
3377 if (FromType->isPointerType())
3378 FromType = FromType->getPointeeType();
3379 if (ToType->isPointerType())
3380 ToType = ToType->getPointeeType();
3381
3382 // Remove references.
3383 FromType = FromType.getNonReferenceType();
3384 ToType = ToType.getNonReferenceType();
3385
3386 // Don't print extra info for non-specialized template functions.
3387 if (FromType->isInstantiationDependentType() &&
3388 !FromType->getAs<TemplateSpecializationType>()) {
3389 PDiag << ft_default;
3390 return;
3391 }
3392
3393 // No extra info for same types.
3394 if (Context.hasSameType(FromType, ToType)) {
3395 PDiag << ft_default;
3396 return;
3397 }
3398
3399 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3400 *ToFunction = tryGetFunctionProtoType(ToType);
3401
3402 // Both types need to be function types.
3403 if (!FromFunction || !ToFunction) {
3404 PDiag << ft_default;
3405 return;
3406 }
3407
3408 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3409 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3410 << FromFunction->getNumParams();
3411 return;
3412 }
3413
3414 // Handle different parameter types.
3415 unsigned ArgPos;
3416 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3417 PDiag << ft_parameter_mismatch << ArgPos + 1
3418 << ToFunction->getParamType(ArgPos)
3419 << FromFunction->getParamType(ArgPos);
3420 return;
3421 }
3422
3423 // Handle different return type.
3424 if (!Context.hasSameType(FromFunction->getReturnType(),
3425 ToFunction->getReturnType())) {
3426 PDiag << ft_return_type << ToFunction->getReturnType()
3427 << FromFunction->getReturnType();
3428 return;
3429 }
3430
3431 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3432 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3433 << FromFunction->getMethodQuals();
3434 return;
3435 }
3436
3437 // Handle exception specification differences on canonical type (in C++17
3438 // onwards).
3440 ->isNothrow() !=
3441 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3442 ->isNothrow()) {
3443 PDiag << ft_noexcept;
3444 return;
3445 }
3446
3447 // Unable to find a difference, so add no extra info.
3448 PDiag << ft_default;
3449}
3450
3452 ArrayRef<QualType> New, unsigned *ArgPos,
3453 bool Reversed) {
3454 assert(llvm::size(Old) == llvm::size(New) &&
3455 "Can't compare parameters of functions with different number of "
3456 "parameters!");
3457
3458 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3459 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3460 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3461
3462 // Ignore address spaces in pointee type. This is to disallow overloading
3463 // on __ptr32/__ptr64 address spaces.
3464 QualType OldType =
3465 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3466 QualType NewType =
3467 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3468
3469 if (!Context.hasSameType(OldType, NewType)) {
3470 if (ArgPos)
3471 *ArgPos = Idx;
3472 return false;
3473 }
3474 }
3475 return true;
3476}
3477
3479 const FunctionProtoType *NewType,
3480 unsigned *ArgPos, bool Reversed) {
3481 return FunctionParamTypesAreEqual(OldType->param_types(),
3482 NewType->param_types(), ArgPos, Reversed);
3483}
3484
3486 const FunctionDecl *NewFunction,
3487 unsigned *ArgPos,
3488 bool Reversed) {
3489
3490 if (OldFunction->getNumNonObjectParams() !=
3491 NewFunction->getNumNonObjectParams())
3492 return false;
3493
3494 unsigned OldIgnore =
3496 unsigned NewIgnore =
3498
3499 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3500 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3501
3502 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3503 NewPT->param_types().slice(NewIgnore),
3504 ArgPos, Reversed);
3505}
3506
3508 CastKind &Kind,
3509 CXXCastPath& BasePath,
3510 bool IgnoreBaseAccess,
3511 bool Diagnose) {
3512 QualType FromType = From->getType();
3513 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3514
3515 Kind = CK_BitCast;
3516
3517 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3520 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3521 DiagRuntimeBehavior(From->getExprLoc(), From,
3522 PDiag(diag::warn_impcast_bool_to_null_pointer)
3523 << ToType << From->getSourceRange());
3524 else if (!isUnevaluatedContext())
3525 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3526 << ToType << From->getSourceRange();
3527 }
3528 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3529 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3530 QualType FromPointeeType = FromPtrType->getPointeeType(),
3531 ToPointeeType = ToPtrType->getPointeeType();
3532
3533 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3534 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3535 // We must have a derived-to-base conversion. Check an
3536 // ambiguous or inaccessible conversion.
3537 unsigned InaccessibleID = 0;
3538 unsigned AmbiguousID = 0;
3539 if (Diagnose) {
3540 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3541 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3542 }
3544 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3545 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3546 &BasePath, IgnoreBaseAccess))
3547 return true;
3548
3549 // The conversion was successful.
3550 Kind = CK_DerivedToBase;
3551 }
3552
3553 if (Diagnose && !IsCStyleOrFunctionalCast &&
3554 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3555 assert(getLangOpts().MSVCCompat &&
3556 "this should only be possible with MSVCCompat!");
3557 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3558 << From->getSourceRange();
3559 }
3560 }
3561 } else if (const ObjCObjectPointerType *ToPtrType =
3562 ToType->getAs<ObjCObjectPointerType>()) {
3563 if (const ObjCObjectPointerType *FromPtrType =
3564 FromType->getAs<ObjCObjectPointerType>()) {
3565 // Objective-C++ conversions are always okay.
3566 // FIXME: We should have a different class of conversions for the
3567 // Objective-C++ implicit conversions.
3568 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3569 return false;
3570 } else if (FromType->isBlockPointerType()) {
3571 Kind = CK_BlockPointerToObjCPointerCast;
3572 } else {
3573 Kind = CK_CPointerToObjCPointerCast;
3574 }
3575 } else if (ToType->isBlockPointerType()) {
3576 if (!FromType->isBlockPointerType())
3577 Kind = CK_AnyPointerToBlockPointerCast;
3578 }
3579
3580 // We shouldn't fall into this case unless it's valid for other
3581 // reasons.
3583 Kind = CK_NullToPointer;
3584
3585 return false;
3586}
3587
3589 QualType ToType,
3590 bool InOverloadResolution,
3591 QualType &ConvertedType) {
3592 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3593 if (!ToTypePtr)
3594 return false;
3595
3596 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3598 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3600 ConvertedType = ToType;
3601 return true;
3602 }
3603
3604 // Otherwise, both types have to be member pointers.
3605 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3606 if (!FromTypePtr)
3607 return false;
3608
3609 // A pointer to member of B can be converted to a pointer to member of D,
3610 // where D is derived from B (C++ 4.11p2).
3611 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3612 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3613
3614 if (!declaresSameEntity(FromClass, ToClass) &&
3615 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3616 ConvertedType = Context.getMemberPointerType(
3617 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3618 return true;
3619 }
3620
3621 return false;
3622}
3623
3625 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3626 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3627 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3628 // Lock down the inheritance model right now in MS ABI, whether or not the
3629 // pointee types are the same.
3630 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3631 (void)isCompleteType(CheckLoc, FromType);
3632 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3633 }
3634
3635 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3636 if (!FromPtrType) {
3637 // This must be a null pointer to member pointer conversion
3638 Kind = CK_NullToMemberPointer;
3640 }
3641
3642 // T == T, modulo cv
3644 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3645 ToPtrType->getPointeeType()))
3647
3648 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3649 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3650
3651 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3652 const CXXRecordDecl *Cls) {
3653 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3654 PD << Qual;
3655 else
3656 PD << Context.getCanonicalTagType(Cls);
3657 };
3658 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3659 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3660 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3661 return PD;
3662 };
3663
3664 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3666 std::swap(Base, Derived);
3667
3668 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3669 /*DetectVirtual=*/true);
3670 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3672
3673 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3674 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3675 PD << int(Direction);
3676 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3677 Diag(CheckLoc, PD);
3679 }
3680
3681 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3682 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3683 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3684 Diag(CheckLoc, PD);
3686 }
3687
3688 // Must be a base to derived member conversion.
3689 BuildBasePathArray(Paths, BasePath);
3691 ? CK_DerivedToBaseMemberPointer
3692 : CK_BaseToDerivedMemberPointer;
3693
3694 if (!IgnoreBaseAccess)
3695 switch (CheckBaseClassAccess(
3696 CheckLoc, Base, Derived, Paths.front(),
3698 ? diag::err_upcast_to_inaccessible_base
3699 : diag::err_downcast_from_inaccessible_base,
3700 [&](PartialDiagnostic &PD) {
3701 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3702 DerivedQual = ToPtrType->getQualifier();
3703 if (Direction == MemberPointerConversionDirection::Upcast)
3704 std::swap(BaseQual, DerivedQual);
3705 DiagCls(PD, DerivedQual, Derived);
3706 DiagCls(PD, BaseQual, Base);
3707 })) {
3709 case Sema::AR_delayed:
3710 case Sema::AR_dependent:
3711 // Optimistically assume that the delayed and dependent cases
3712 // will work out.
3713 break;
3714
3717 }
3718
3720}
3721
3722/// Determine whether the lifetime conversion between the two given
3723/// qualifiers sets is nontrivial.
3725 Qualifiers ToQuals) {
3726 // Converting anything to const __unsafe_unretained is trivial.
3727 if (ToQuals.hasConst() &&
3729 return false;
3730
3731 return true;
3732}
3733
3734/// Perform a single iteration of the loop for checking if a qualification
3735/// conversion is valid.
3736///
3737/// Specifically, check whether any change between the qualifiers of \p
3738/// FromType and \p ToType is permissible, given knowledge about whether every
3739/// outer layer is const-qualified.
3741 bool CStyle, bool IsTopLevel,
3742 bool &PreviousToQualsIncludeConst,
3743 bool &ObjCLifetimeConversion,
3744 const ASTContext &Ctx) {
3745 Qualifiers FromQuals = FromType.getQualifiers();
3746 Qualifiers ToQuals = ToType.getQualifiers();
3747
3748 // Ignore __unaligned qualifier.
3749 FromQuals.removeUnaligned();
3750
3751 // Objective-C ARC:
3752 // Check Objective-C lifetime conversions.
3753 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3754 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3755 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3756 ObjCLifetimeConversion = true;
3757 FromQuals.removeObjCLifetime();
3758 ToQuals.removeObjCLifetime();
3759 } else {
3760 // Qualification conversions cannot cast between different
3761 // Objective-C lifetime qualifiers.
3762 return false;
3763 }
3764 }
3765
3766 // Allow addition/removal of GC attributes but not changing GC attributes.
3767 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3768 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3769 FromQuals.removeObjCGCAttr();
3770 ToQuals.removeObjCGCAttr();
3771 }
3772
3773 // __ptrauth qualifiers must match exactly.
3774 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3775 return false;
3776
3777 // -- for every j > 0, if const is in cv 1,j then const is in cv
3778 // 2,j, and similarly for volatile.
3779 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3780 return false;
3781
3782 // If address spaces mismatch:
3783 // - in top level it is only valid to convert to addr space that is a
3784 // superset in all cases apart from C-style casts where we allow
3785 // conversions between overlapping address spaces.
3786 // - in non-top levels it is not a valid conversion.
3787 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3788 (!IsTopLevel ||
3789 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3790 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3791 return false;
3792
3793 // -- if the cv 1,j and cv 2,j are different, then const is in
3794 // every cv for 0 < k < j.
3795 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3796 !PreviousToQualsIncludeConst)
3797 return false;
3798
3799 // The following wording is from C++20, where the result of the conversion
3800 // is T3, not T2.
3801 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3802 // "array of unknown bound of"
3803 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3804 return false;
3805
3806 // -- if the resulting P3,i is different from P1,i [...], then const is
3807 // added to every cv 3_k for 0 < k < i.
3808 if (!CStyle && FromType->isConstantArrayType() &&
3809 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3810 return false;
3811
3812 // Keep track of whether all prior cv-qualifiers in the "to" type
3813 // include const.
3814 PreviousToQualsIncludeConst =
3815 PreviousToQualsIncludeConst && ToQuals.hasConst();
3816 return true;
3817}
3818
3819bool
3821 bool CStyle, bool &ObjCLifetimeConversion) {
3822 FromType = Context.getCanonicalType(FromType);
3823 ToType = Context.getCanonicalType(ToType);
3824 ObjCLifetimeConversion = false;
3825
3826 // If FromType and ToType are the same type, this is not a
3827 // qualification conversion.
3828 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3829 return false;
3830
3831 // (C++ 4.4p4):
3832 // A conversion can add cv-qualifiers at levels other than the first
3833 // in multi-level pointers, subject to the following rules: [...]
3834 bool PreviousToQualsIncludeConst = true;
3835 bool UnwrappedAnyPointer = false;
3836 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3837 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3838 !UnwrappedAnyPointer,
3839 PreviousToQualsIncludeConst,
3840 ObjCLifetimeConversion, getASTContext()))
3841 return false;
3842 UnwrappedAnyPointer = true;
3843 }
3844
3845 // We are left with FromType and ToType being the pointee types
3846 // after unwrapping the original FromType and ToType the same number
3847 // of times. If we unwrapped any pointers, and if FromType and
3848 // ToType have the same unqualified type (since we checked
3849 // qualifiers above), then this is a qualification conversion.
3850 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3851}
3852
3853/// - Determine whether this is a conversion from a scalar type to an
3854/// atomic type.
3855///
3856/// If successful, updates \c SCS's second and third steps in the conversion
3857/// sequence to finish the conversion.
3858static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3859 bool InOverloadResolution,
3861 bool CStyle) {
3862 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3863 if (!ToAtomic)
3864 return false;
3865
3867 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3868 InOverloadResolution, InnerSCS,
3869 CStyle, /*AllowObjCWritebackConversion=*/false))
3870 return false;
3871
3872 SCS.Second = InnerSCS.Second;
3873 SCS.setToType(1, InnerSCS.getToType(1));
3874 SCS.Third = InnerSCS.Third;
3877 SCS.setToType(2, InnerSCS.getToType(2));
3878 return true;
3879}
3880
3883 QualType Type) {
3884 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3885 if (CtorType->getNumParams() > 0) {
3886 QualType FirstArg = CtorType->getParamType(0);
3887 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3888 return true;
3889 }
3890 return false;
3891}
3892
3893static OverloadingResult
3895 CXXRecordDecl *To,
3897 OverloadCandidateSet &CandidateSet,
3898 bool AllowExplicit) {
3900 for (auto *D : S.LookupConstructors(To)) {
3901 auto Info = getConstructorInfo(D);
3902 if (!Info)
3903 continue;
3904
3905 bool Usable = !Info.Constructor->isInvalidDecl() &&
3906 S.isInitListConstructor(Info.Constructor);
3907 if (Usable) {
3908 bool SuppressUserConversions = false;
3909 if (Info.ConstructorTmpl)
3910 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3911 /*ExplicitArgs*/ nullptr, From,
3912 CandidateSet, SuppressUserConversions,
3913 /*PartialOverloading*/ false,
3914 AllowExplicit);
3915 else
3916 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3917 CandidateSet, SuppressUserConversions,
3918 /*PartialOverloading*/ false, AllowExplicit);
3919 }
3920 }
3921
3922 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3923
3925 switch (auto Result =
3926 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3927 case OR_Deleted:
3928 case OR_Success: {
3929 // Record the standard conversion we used and the conversion function.
3931 QualType ThisType = Constructor->getFunctionObjectParameterType();
3932 // Initializer lists don't have conversions as such.
3934 User.HadMultipleCandidates = HadMultipleCandidates;
3936 User.FoundConversionFunction = Best->FoundDecl;
3938 User.After.setFromType(ThisType);
3939 User.After.setAllToTypes(ToType);
3940 return Result;
3941 }
3942
3944 return OR_No_Viable_Function;
3945 case OR_Ambiguous:
3946 return OR_Ambiguous;
3947 }
3948
3949 llvm_unreachable("Invalid OverloadResult!");
3950}
3951
3952/// Determines whether there is a user-defined conversion sequence
3953/// (C++ [over.ics.user]) that converts expression From to the type
3954/// ToType. If such a conversion exists, User will contain the
3955/// user-defined conversion sequence that performs such a conversion
3956/// and this routine will return true. Otherwise, this routine returns
3957/// false and User is unspecified.
3958///
3959/// \param AllowExplicit true if the conversion should consider C++0x
3960/// "explicit" conversion functions as well as non-explicit conversion
3961/// functions (C++0x [class.conv.fct]p2).
3962///
3963/// \param AllowObjCConversionOnExplicit true if the conversion should
3964/// allow an extra Objective-C pointer conversion on uses of explicit
3965/// constructors. Requires \c AllowExplicit to also be set.
3966static OverloadingResult
3969 OverloadCandidateSet &CandidateSet,
3970 AllowedExplicit AllowExplicit,
3971 bool AllowObjCConversionOnExplicit) {
3972 assert(AllowExplicit != AllowedExplicit::None ||
3973 !AllowObjCConversionOnExplicit);
3975
3976 // Whether we will only visit constructors.
3977 bool ConstructorsOnly = false;
3978
3979 // If the type we are conversion to is a class type, enumerate its
3980 // constructors.
3981 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
3982 // C++ [over.match.ctor]p1:
3983 // When objects of class type are direct-initialized (8.5), or
3984 // copy-initialized from an expression of the same or a
3985 // derived class type (8.5), overload resolution selects the
3986 // constructor. [...] For copy-initialization, the candidate
3987 // functions are all the converting constructors (12.3.1) of
3988 // that class. The argument list is the expression-list within
3989 // the parentheses of the initializer.
3990 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3991 (From->getType()->isRecordType() &&
3992 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3993 ConstructorsOnly = true;
3994
3995 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3996 // We're not going to find any constructors.
3997 } else if (auto *ToRecordDecl =
3998 dyn_cast<CXXRecordDecl>(ToRecordType->getOriginalDecl())) {
3999 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4000
4001 Expr **Args = &From;
4002 unsigned NumArgs = 1;
4003 bool ListInitializing = false;
4004 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4005 // But first, see if there is an init-list-constructor that will work.
4007 S, From, ToType, ToRecordDecl, User, CandidateSet,
4008 AllowExplicit == AllowedExplicit::All);
4009 if (Result != OR_No_Viable_Function)
4010 return Result;
4011 // Never mind.
4012 CandidateSet.clear(
4014
4015 // If we're list-initializing, we pass the individual elements as
4016 // arguments, not the entire list.
4017 Args = InitList->getInits();
4018 NumArgs = InitList->getNumInits();
4019 ListInitializing = true;
4020 }
4021
4022 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4023 auto Info = getConstructorInfo(D);
4024 if (!Info)
4025 continue;
4026
4027 bool Usable = !Info.Constructor->isInvalidDecl();
4028 if (!ListInitializing)
4029 Usable = Usable && Info.Constructor->isConvertingConstructor(
4030 /*AllowExplicit*/ true);
4031 if (Usable) {
4032 bool SuppressUserConversions = !ConstructorsOnly;
4033 // C++20 [over.best.ics.general]/4.5:
4034 // if the target is the first parameter of a constructor [of class
4035 // X] and the constructor [...] is a candidate by [...] the second
4036 // phase of [over.match.list] when the initializer list has exactly
4037 // one element that is itself an initializer list, [...] and the
4038 // conversion is to X or reference to cv X, user-defined conversion
4039 // sequences are not considered.
4040 if (SuppressUserConversions && ListInitializing) {
4041 SuppressUserConversions =
4042 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4043 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4044 ToType);
4045 }
4046 if (Info.ConstructorTmpl)
4048 Info.ConstructorTmpl, Info.FoundDecl,
4049 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4050 CandidateSet, SuppressUserConversions,
4051 /*PartialOverloading*/ false,
4052 AllowExplicit == AllowedExplicit::All);
4053 else
4054 // Allow one user-defined conversion when user specifies a
4055 // From->ToType conversion via an static cast (c-style, etc).
4056 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4057 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4058 SuppressUserConversions,
4059 /*PartialOverloading*/ false,
4060 AllowExplicit == AllowedExplicit::All);
4061 }
4062 }
4063 }
4064 }
4065
4066 // Enumerate conversion functions, if we're allowed to.
4067 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4068 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4069 // No conversion functions from incomplete types.
4070 } else if (const RecordType *FromRecordType =
4071 From->getType()->getAsCanonical<RecordType>()) {
4072 if (auto *FromRecordDecl =
4073 dyn_cast<CXXRecordDecl>(FromRecordType->getOriginalDecl())) {
4074 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4075 // Add all of the conversion functions as candidates.
4076 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4077 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4078 DeclAccessPair FoundDecl = I.getPair();
4079 NamedDecl *D = FoundDecl.getDecl();
4080 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4081 if (isa<UsingShadowDecl>(D))
4082 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4083
4084 CXXConversionDecl *Conv;
4085 FunctionTemplateDecl *ConvTemplate;
4086 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4087 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4088 else
4089 Conv = cast<CXXConversionDecl>(D);
4090
4091 if (ConvTemplate)
4093 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4094 CandidateSet, AllowObjCConversionOnExplicit,
4095 AllowExplicit != AllowedExplicit::None);
4096 else
4097 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4098 CandidateSet, AllowObjCConversionOnExplicit,
4099 AllowExplicit != AllowedExplicit::None);
4100 }
4101 }
4102 }
4103
4104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4105
4107 switch (auto Result =
4108 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4109 case OR_Success:
4110 case OR_Deleted:
4111 // Record the standard conversion we used and the conversion function.
4113 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4114 // C++ [over.ics.user]p1:
4115 // If the user-defined conversion is specified by a
4116 // constructor (12.3.1), the initial standard conversion
4117 // sequence converts the source type to the type required by
4118 // the argument of the constructor.
4119 //
4120 if (isa<InitListExpr>(From)) {
4121 // Initializer lists don't have conversions as such.
4123 User.Before.FromBracedInitList = true;
4124 } else {
4125 if (Best->Conversions[0].isEllipsis())
4126 User.EllipsisConversion = true;
4127 else {
4128 User.Before = Best->Conversions[0].Standard;
4129 User.EllipsisConversion = false;
4130 }
4131 }
4132 User.HadMultipleCandidates = HadMultipleCandidates;
4134 User.FoundConversionFunction = Best->FoundDecl;
4136 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4137 User.After.setAllToTypes(ToType);
4138 return Result;
4139 }
4140 if (CXXConversionDecl *Conversion
4141 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4142
4143 assert(Best->HasFinalConversion);
4144
4145 // C++ [over.ics.user]p1:
4146 //
4147 // [...] If the user-defined conversion is specified by a
4148 // conversion function (12.3.2), the initial standard
4149 // conversion sequence converts the source type to the
4150 // implicit object parameter of the conversion function.
4151 User.Before = Best->Conversions[0].Standard;
4152 User.HadMultipleCandidates = HadMultipleCandidates;
4153 User.ConversionFunction = Conversion;
4154 User.FoundConversionFunction = Best->FoundDecl;
4155 User.EllipsisConversion = false;
4156
4157 // C++ [over.ics.user]p2:
4158 // The second standard conversion sequence converts the
4159 // result of the user-defined conversion to the target type
4160 // for the sequence. Since an implicit conversion sequence
4161 // is an initialization, the special rules for
4162 // initialization by user-defined conversion apply when
4163 // selecting the best user-defined conversion for a
4164 // user-defined conversion sequence (see 13.3.3 and
4165 // 13.3.3.1).
4166 User.After = Best->FinalConversion;
4167 return Result;
4168 }
4169 llvm_unreachable("Not a constructor or conversion function?");
4170
4172 return OR_No_Viable_Function;
4173
4174 case OR_Ambiguous:
4175 return OR_Ambiguous;
4176 }
4177
4178 llvm_unreachable("Invalid OverloadResult!");
4179}
4180
4181bool
4184 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4186 OverloadingResult OvResult =
4187 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4188 CandidateSet, AllowedExplicit::None, false);
4189
4190 if (!(OvResult == OR_Ambiguous ||
4191 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4192 return false;
4193
4194 auto Cands = CandidateSet.CompleteCandidates(
4195 *this,
4197 From);
4198 if (OvResult == OR_Ambiguous)
4199 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4200 << From->getType() << ToType << From->getSourceRange();
4201 else { // OR_No_Viable_Function && !CandidateSet.empty()
4202 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4203 diag::err_typecheck_nonviable_condition_incomplete,
4204 From->getType(), From->getSourceRange()))
4205 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4206 << false << From->getType() << From->getSourceRange() << ToType;
4207 }
4208
4209 CandidateSet.NoteCandidates(
4210 *this, From, Cands);
4211 return true;
4212}
4213
4214// Helper for compareConversionFunctions that gets the FunctionType that the
4215// conversion-operator return value 'points' to, or nullptr.
4216static const FunctionType *
4218 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4219 const PointerType *RetPtrTy =
4220 ConvFuncTy->getReturnType()->getAs<PointerType>();
4221
4222 if (!RetPtrTy)
4223 return nullptr;
4224
4225 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4226}
4227
4228/// Compare the user-defined conversion functions or constructors
4229/// of two user-defined conversion sequences to determine whether any ordering
4230/// is possible.
4233 FunctionDecl *Function2) {
4234 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4235 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4236 if (!Conv1 || !Conv2)
4238
4239 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4241
4242 // Objective-C++:
4243 // If both conversion functions are implicitly-declared conversions from
4244 // a lambda closure type to a function pointer and a block pointer,
4245 // respectively, always prefer the conversion to a function pointer,
4246 // because the function pointer is more lightweight and is more likely
4247 // to keep code working.
4248 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4249 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4250 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4251 if (Block1 != Block2)
4252 return Block1 ? ImplicitConversionSequence::Worse
4254 }
4255
4256 // In order to support multiple calling conventions for the lambda conversion
4257 // operator (such as when the free and member function calling convention is
4258 // different), prefer the 'free' mechanism, followed by the calling-convention
4259 // of operator(). The latter is in place to support the MSVC-like solution of
4260 // defining ALL of the possible conversions in regards to calling-convention.
4261 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4262 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4263
4264 if (Conv1FuncRet && Conv2FuncRet &&
4265 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4266 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4267 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4268
4269 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4270 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4271
4272 CallingConv CallOpCC =
4273 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4275 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4277 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4278
4279 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4280 for (CallingConv CC : PrefOrder) {
4281 if (Conv1CC == CC)
4283 if (Conv2CC == CC)
4285 }
4286 }
4287
4289}
4290
4297
4298/// CompareImplicitConversionSequences - Compare two implicit
4299/// conversion sequences to determine whether one is better than the
4300/// other or if they are indistinguishable (C++ 13.3.3.2).
4303 const ImplicitConversionSequence& ICS1,
4304 const ImplicitConversionSequence& ICS2)
4305{
4306 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4307 // conversion sequences (as defined in 13.3.3.1)
4308 // -- a standard conversion sequence (13.3.3.1.1) is a better
4309 // conversion sequence than a user-defined conversion sequence or
4310 // an ellipsis conversion sequence, and
4311 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4312 // conversion sequence than an ellipsis conversion sequence
4313 // (13.3.3.1.3).
4314 //
4315 // C++0x [over.best.ics]p10:
4316 // For the purpose of ranking implicit conversion sequences as
4317 // described in 13.3.3.2, the ambiguous conversion sequence is
4318 // treated as a user-defined sequence that is indistinguishable
4319 // from any other user-defined conversion sequence.
4320
4321 // String literal to 'char *' conversion has been deprecated in C++03. It has
4322 // been removed from C++11. We still accept this conversion, if it happens at
4323 // the best viable function. Otherwise, this conversion is considered worse
4324 // than ellipsis conversion. Consider this as an extension; this is not in the
4325 // standard. For example:
4326 //
4327 // int &f(...); // #1
4328 // void f(char*); // #2
4329 // void g() { int &r = f("foo"); }
4330 //
4331 // In C++03, we pick #2 as the best viable function.
4332 // In C++11, we pick #1 as the best viable function, because ellipsis
4333 // conversion is better than string-literal to char* conversion (since there
4334 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4335 // convert arguments, #2 would be the best viable function in C++11.
4336 // If the best viable function has this conversion, a warning will be issued
4337 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4338
4339 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4342 // Ill-formedness must not differ
4343 ICS1.isBad() == ICS2.isBad())
4347
4348 if (ICS1.getKindRank() < ICS2.getKindRank())
4350 if (ICS2.getKindRank() < ICS1.getKindRank())
4352
4353 // The following checks require both conversion sequences to be of
4354 // the same kind.
4355 if (ICS1.getKind() != ICS2.getKind())
4357
4360
4361 // Two implicit conversion sequences of the same form are
4362 // indistinguishable conversion sequences unless one of the
4363 // following rules apply: (C++ 13.3.3.2p3):
4364
4365 // List-initialization sequence L1 is a better conversion sequence than
4366 // list-initialization sequence L2 if:
4367 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4368 // if not that,
4369 // — L1 and L2 convert to arrays of the same element type, and either the
4370 // number of elements n_1 initialized by L1 is less than the number of
4371 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4372 // an array of unknown bound and L1 does not,
4373 // even if one of the other rules in this paragraph would otherwise apply.
4374 if (!ICS1.isBad()) {
4375 bool StdInit1 = false, StdInit2 = false;
4378 nullptr);
4381 nullptr);
4382 if (StdInit1 != StdInit2)
4383 return StdInit1 ? ImplicitConversionSequence::Better
4385
4388 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4390 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4392 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4393 CAT2->getElementType())) {
4394 // Both to arrays of the same element type
4395 if (CAT1->getSize() != CAT2->getSize())
4396 // Different sized, the smaller wins
4397 return CAT1->getSize().ult(CAT2->getSize())
4402 // One is incomplete, it loses
4406 }
4407 }
4408 }
4409
4410 if (ICS1.isStandard())
4411 // Standard conversion sequence S1 is a better conversion sequence than
4412 // standard conversion sequence S2 if [...]
4413 Result = CompareStandardConversionSequences(S, Loc,
4414 ICS1.Standard, ICS2.Standard);
4415 else if (ICS1.isUserDefined()) {
4416 // User-defined conversion sequence U1 is a better conversion
4417 // sequence than another user-defined conversion sequence U2 if
4418 // they contain the same user-defined conversion function or
4419 // constructor and if the second standard conversion sequence of
4420 // U1 is better than the second standard conversion sequence of
4421 // U2 (C++ 13.3.3.2p3).
4424 Result = CompareStandardConversionSequences(S, Loc,
4425 ICS1.UserDefined.After,
4426 ICS2.UserDefined.After);
4427 else
4428 Result = compareConversionFunctions(S,
4431 }
4432
4433 return Result;
4434}
4435
4436// Per 13.3.3.2p3, compare the given standard conversion sequences to
4437// determine if one is a proper subset of the other.
4440 const StandardConversionSequence& SCS1,
4441 const StandardConversionSequence& SCS2) {
4444
4445 // the identity conversion sequence is considered to be a subsequence of
4446 // any non-identity conversion sequence
4447 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4449 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4451
4452 if (SCS1.Second != SCS2.Second) {
4453 if (SCS1.Second == ICK_Identity)
4455 else if (SCS2.Second == ICK_Identity)
4457 else
4459 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4461
4462 if (SCS1.Third == SCS2.Third) {
4463 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4465 }
4466
4467 if (SCS1.Third == ICK_Identity)
4468 return Result == ImplicitConversionSequence::Worse
4471
4472 if (SCS2.Third == ICK_Identity)
4473 return Result == ImplicitConversionSequence::Better
4476
4478}
4479
4480/// Determine whether one of the given reference bindings is better
4481/// than the other based on what kind of bindings they are.
4482static bool
4484 const StandardConversionSequence &SCS2) {
4485 // C++0x [over.ics.rank]p3b4:
4486 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4487 // implicit object parameter of a non-static member function declared
4488 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4489 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4490 // lvalue reference to a function lvalue and S2 binds an rvalue
4491 // reference*.
4492 //
4493 // FIXME: Rvalue references. We're going rogue with the above edits,
4494 // because the semantics in the current C++0x working paper (N3225 at the
4495 // time of this writing) break the standard definition of std::forward
4496 // and std::reference_wrapper when dealing with references to functions.
4497 // Proposed wording changes submitted to CWG for consideration.
4500 return false;
4501
4502 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4503 SCS2.IsLvalueReference) ||
4506}
4507
4513
4514/// Returns kind of fixed enum promotion the \a SCS uses.
4515static FixedEnumPromotion
4517
4518 if (SCS.Second != ICK_Integral_Promotion)
4520
4521 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4522 if (!Enum)
4524
4525 if (!Enum->isFixed())
4527
4528 QualType UnderlyingType = Enum->getIntegerType();
4529 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4531
4533}
4534
4535/// CompareStandardConversionSequences - Compare two standard
4536/// conversion sequences to determine whether one is better than the
4537/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4540 const StandardConversionSequence& SCS1,
4541 const StandardConversionSequence& SCS2)
4542{
4543 // Standard conversion sequence S1 is a better conversion sequence
4544 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4545
4546 // -- S1 is a proper subsequence of S2 (comparing the conversion
4547 // sequences in the canonical form defined by 13.3.3.1.1,
4548 // excluding any Lvalue Transformation; the identity conversion
4549 // sequence is considered to be a subsequence of any
4550 // non-identity conversion sequence) or, if not that,
4553 return CK;
4554
4555 // -- the rank of S1 is better than the rank of S2 (by the rules
4556 // defined below), or, if not that,
4557 ImplicitConversionRank Rank1 = SCS1.getRank();
4558 ImplicitConversionRank Rank2 = SCS2.getRank();
4559 if (Rank1 < Rank2)
4561 else if (Rank2 < Rank1)
4563
4564 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4565 // are indistinguishable unless one of the following rules
4566 // applies:
4567
4568 // A conversion that is not a conversion of a pointer, or
4569 // pointer to member, to bool is better than another conversion
4570 // that is such a conversion.
4572 return SCS2.isPointerConversionToBool()
4575
4576 // C++14 [over.ics.rank]p4b2:
4577 // This is retroactively applied to C++11 by CWG 1601.
4578 //
4579 // A conversion that promotes an enumeration whose underlying type is fixed
4580 // to its underlying type is better than one that promotes to the promoted
4581 // underlying type, if the two are different.
4584 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4585 FEP1 != FEP2)
4589
4590 // C++ [over.ics.rank]p4b2:
4591 //
4592 // If class B is derived directly or indirectly from class A,
4593 // conversion of B* to A* is better than conversion of B* to
4594 // void*, and conversion of A* to void* is better than conversion
4595 // of B* to void*.
4596 bool SCS1ConvertsToVoid
4598 bool SCS2ConvertsToVoid
4600 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4601 // Exactly one of the conversion sequences is a conversion to
4602 // a void pointer; it's the worse conversion.
4603 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4605 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4606 // Neither conversion sequence converts to a void pointer; compare
4607 // their derived-to-base conversions.
4609 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4610 return DerivedCK;
4611 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4612 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4613 // Both conversion sequences are conversions to void
4614 // pointers. Compare the source types to determine if there's an
4615 // inheritance relationship in their sources.
4616 QualType FromType1 = SCS1.getFromType();
4617 QualType FromType2 = SCS2.getFromType();
4618
4619 // Adjust the types we're converting from via the array-to-pointer
4620 // conversion, if we need to.
4621 if (SCS1.First == ICK_Array_To_Pointer)
4622 FromType1 = S.Context.getArrayDecayedType(FromType1);
4623 if (SCS2.First == ICK_Array_To_Pointer)
4624 FromType2 = S.Context.getArrayDecayedType(FromType2);
4625
4626 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4627 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4628
4629 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4631 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4633
4634 // Objective-C++: If one interface is more specific than the
4635 // other, it is the better one.
4636 const ObjCObjectPointerType* FromObjCPtr1
4637 = FromType1->getAs<ObjCObjectPointerType>();
4638 const ObjCObjectPointerType* FromObjCPtr2
4639 = FromType2->getAs<ObjCObjectPointerType>();
4640 if (FromObjCPtr1 && FromObjCPtr2) {
4641 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4642 FromObjCPtr2);
4643 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4644 FromObjCPtr1);
4645 if (AssignLeft != AssignRight) {
4646 return AssignLeft? ImplicitConversionSequence::Better
4648 }
4649 }
4650 }
4651
4652 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4653 // Check for a better reference binding based on the kind of bindings.
4654 if (isBetterReferenceBindingKind(SCS1, SCS2))
4656 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4658 }
4659
4660 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4661 // bullet 3).
4663 = CompareQualificationConversions(S, SCS1, SCS2))
4664 return QualCK;
4665
4666 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4667 // C++ [over.ics.rank]p3b4:
4668 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4669 // which the references refer are the same type except for
4670 // top-level cv-qualifiers, and the type to which the reference
4671 // initialized by S2 refers is more cv-qualified than the type
4672 // to which the reference initialized by S1 refers.
4673 QualType T1 = SCS1.getToType(2);
4674 QualType T2 = SCS2.getToType(2);
4675 T1 = S.Context.getCanonicalType(T1);
4676 T2 = S.Context.getCanonicalType(T2);
4677 Qualifiers T1Quals, T2Quals;
4678 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4679 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4680 if (UnqualT1 == UnqualT2) {
4681 // Objective-C++ ARC: If the references refer to objects with different
4682 // lifetimes, prefer bindings that don't change lifetime.
4688 }
4689
4690 // If the type is an array type, promote the element qualifiers to the
4691 // type for comparison.
4692 if (isa<ArrayType>(T1) && T1Quals)
4693 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4694 if (isa<ArrayType>(T2) && T2Quals)
4695 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4696 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4698 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4700 }
4701 }
4702
4703 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4704 // floating-to-integral conversion if the integral conversion
4705 // is between types of the same size.
4706 // For example:
4707 // void f(float);
4708 // void f(int);
4709 // int main {
4710 // long a;
4711 // f(a);
4712 // }
4713 // Here, MSVC will call f(int) instead of generating a compile error
4714 // as clang will do in standard mode.
4715 if (S.getLangOpts().MSVCCompat &&
4718 SCS2.Second == ICK_Floating_Integral &&
4719 S.Context.getTypeSize(SCS1.getFromType()) ==
4720 S.Context.getTypeSize(SCS1.getToType(2)))
4722
4723 // Prefer a compatible vector conversion over a lax vector conversion
4724 // For example:
4725 //
4726 // typedef float __v4sf __attribute__((__vector_size__(16)));
4727 // void f(vector float);
4728 // void f(vector signed int);
4729 // int main() {
4730 // __v4sf a;
4731 // f(a);
4732 // }
4733 // Here, we'd like to choose f(vector float) and not
4734 // report an ambiguous call error
4735 if (SCS1.Second == ICK_Vector_Conversion &&
4736 SCS2.Second == ICK_Vector_Conversion) {
4737 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4738 SCS1.getFromType(), SCS1.getToType(2));
4739 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4740 SCS2.getFromType(), SCS2.getToType(2));
4741
4742 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4743 return SCS1IsCompatibleVectorConversion
4746 }
4747
4748 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4750 bool SCS1IsCompatibleSVEVectorConversion =
4751 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4752 bool SCS2IsCompatibleSVEVectorConversion =
4753 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4754
4755 if (SCS1IsCompatibleSVEVectorConversion !=
4756 SCS2IsCompatibleSVEVectorConversion)
4757 return SCS1IsCompatibleSVEVectorConversion
4760 }
4761
4762 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4764 bool SCS1IsCompatibleRVVVectorConversion =
4766 bool SCS2IsCompatibleRVVVectorConversion =
4768
4769 if (SCS1IsCompatibleRVVVectorConversion !=
4770 SCS2IsCompatibleRVVVectorConversion)
4771 return SCS1IsCompatibleRVVVectorConversion
4774 }
4776}
4777
4778/// CompareQualificationConversions - Compares two standard conversion
4779/// sequences to determine whether they can be ranked based on their
4780/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4783 const StandardConversionSequence& SCS1,
4784 const StandardConversionSequence& SCS2) {
4785 // C++ [over.ics.rank]p3:
4786 // -- S1 and S2 differ only in their qualification conversion and
4787 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4788 // [C++98]
4789 // [...] and the cv-qualification signature of type T1 is a proper subset
4790 // of the cv-qualification signature of type T2, and S1 is not the
4791 // deprecated string literal array-to-pointer conversion (4.2).
4792 // [C++2a]
4793 // [...] where T1 can be converted to T2 by a qualification conversion.
4794 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4795 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4797
4798 // FIXME: the example in the standard doesn't use a qualification
4799 // conversion (!)
4800 QualType T1 = SCS1.getToType(2);
4801 QualType T2 = SCS2.getToType(2);
4802 T1 = S.Context.getCanonicalType(T1);
4803 T2 = S.Context.getCanonicalType(T2);
4804 assert(!T1->isReferenceType() && !T2->isReferenceType());
4805 Qualifiers T1Quals, T2Quals;
4806 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4807 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4808
4809 // If the types are the same, we won't learn anything by unwrapping
4810 // them.
4811 if (UnqualT1 == UnqualT2)
4813
4814 // Don't ever prefer a standard conversion sequence that uses the deprecated
4815 // string literal array to pointer conversion.
4816 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4817 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4818
4819 // Objective-C++ ARC:
4820 // Prefer qualification conversions not involving a change in lifetime
4821 // to qualification conversions that do change lifetime.
4824 CanPick1 = false;
4827 CanPick2 = false;
4828
4829 bool ObjCLifetimeConversion;
4830 if (CanPick1 &&
4831 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4832 CanPick1 = false;
4833 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4834 // directions, so we can't short-cut this second check in general.
4835 if (CanPick2 &&
4836 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4837 CanPick2 = false;
4838
4839 if (CanPick1 != CanPick2)
4840 return CanPick1 ? ImplicitConversionSequence::Better
4843}
4844
4845/// CompareDerivedToBaseConversions - Compares two standard conversion
4846/// sequences to determine whether they can be ranked based on their
4847/// various kinds of derived-to-base conversions (C++
4848/// [over.ics.rank]p4b3). As part of these checks, we also look at
4849/// conversions between Objective-C interface types.
4852 const StandardConversionSequence& SCS1,
4853 const StandardConversionSequence& SCS2) {
4854 QualType FromType1 = SCS1.getFromType();
4855 QualType ToType1 = SCS1.getToType(1);
4856 QualType FromType2 = SCS2.getFromType();
4857 QualType ToType2 = SCS2.getToType(1);
4858
4859 // Adjust the types we're converting from via the array-to-pointer
4860 // conversion, if we need to.
4861 if (SCS1.First == ICK_Array_To_Pointer)
4862 FromType1 = S.Context.getArrayDecayedType(FromType1);
4863 if (SCS2.First == ICK_Array_To_Pointer)
4864 FromType2 = S.Context.getArrayDecayedType(FromType2);
4865
4866 // Canonicalize all of the types.
4867 FromType1 = S.Context.getCanonicalType(FromType1);
4868 ToType1 = S.Context.getCanonicalType(ToType1);
4869 FromType2 = S.Context.getCanonicalType(FromType2);
4870 ToType2 = S.Context.getCanonicalType(ToType2);
4871
4872 // C++ [over.ics.rank]p4b3:
4873 //
4874 // If class B is derived directly or indirectly from class A and
4875 // class C is derived directly or indirectly from B,
4876 //
4877 // Compare based on pointer conversions.
4878 if (SCS1.Second == ICK_Pointer_Conversion &&
4880 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4881 FromType1->isPointerType() && FromType2->isPointerType() &&
4882 ToType1->isPointerType() && ToType2->isPointerType()) {
4883 QualType FromPointee1 =
4885 QualType ToPointee1 =
4887 QualType FromPointee2 =
4889 QualType ToPointee2 =
4891
4892 // -- conversion of C* to B* is better than conversion of C* to A*,
4893 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4894 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4896 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4898 }
4899
4900 // -- conversion of B* to A* is better than conversion of C* to A*,
4901 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4902 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4904 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4906 }
4907 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4909 const ObjCObjectPointerType *FromPtr1
4910 = FromType1->getAs<ObjCObjectPointerType>();
4911 const ObjCObjectPointerType *FromPtr2
4912 = FromType2->getAs<ObjCObjectPointerType>();
4913 const ObjCObjectPointerType *ToPtr1
4914 = ToType1->getAs<ObjCObjectPointerType>();
4915 const ObjCObjectPointerType *ToPtr2
4916 = ToType2->getAs<ObjCObjectPointerType>();
4917
4918 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4919 // Apply the same conversion ranking rules for Objective-C pointer types
4920 // that we do for C++ pointers to class types. However, we employ the
4921 // Objective-C pseudo-subtyping relationship used for assignment of
4922 // Objective-C pointer types.
4923 bool FromAssignLeft
4924 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4925 bool FromAssignRight
4926 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4927 bool ToAssignLeft
4928 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4929 bool ToAssignRight
4930 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4931
4932 // A conversion to an a non-id object pointer type or qualified 'id'
4933 // type is better than a conversion to 'id'.
4934 if (ToPtr1->isObjCIdType() &&
4935 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4937 if (ToPtr2->isObjCIdType() &&
4938 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4940
4941 // A conversion to a non-id object pointer type is better than a
4942 // conversion to a qualified 'id' type
4943 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4945 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4947
4948 // A conversion to an a non-Class object pointer type or qualified 'Class'
4949 // type is better than a conversion to 'Class'.
4950 if (ToPtr1->isObjCClassType() &&
4951 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4953 if (ToPtr2->isObjCClassType() &&
4954 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4956
4957 // A conversion to a non-Class object pointer type is better than a
4958 // conversion to a qualified 'Class' type.
4959 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4961 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4963
4964 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4965 if (S.Context.hasSameType(FromType1, FromType2) &&
4966 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4967 (ToAssignLeft != ToAssignRight)) {
4968 if (FromPtr1->isSpecialized()) {
4969 // "conversion of B<A> * to B * is better than conversion of B * to
4970 // C *.
4971 bool IsFirstSame =
4972 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4973 bool IsSecondSame =
4974 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4975 if (IsFirstSame) {
4976 if (!IsSecondSame)
4978 } else if (IsSecondSame)
4980 }
4981 return ToAssignLeft? ImplicitConversionSequence::Worse
4983 }
4984
4985 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4986 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4987 (FromAssignLeft != FromAssignRight))
4988 return FromAssignLeft? ImplicitConversionSequence::Better
4990 }
4991 }
4992
4993 // Ranking of member-pointer types.
4994 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4995 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4996 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4997 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4998 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4999 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5000 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5001 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5002 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5003 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5004 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5005 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5006 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5007 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5009 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5011 }
5012 // conversion of B::* to C::* is better than conversion of A::* to C::*
5013 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5014 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5016 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5018 }
5019 }
5020
5021 if (SCS1.Second == ICK_Derived_To_Base) {
5022 // -- conversion of C to B is better than conversion of C to A,
5023 // -- binding of an expression of type C to a reference of type
5024 // B& is better than binding an expression of type C to a
5025 // reference of type A&,
5026 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5027 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5028 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5030 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5032 }
5033
5034 // -- conversion of B to A is better than conversion of C to A.
5035 // -- binding of an expression of type B to a reference of type
5036 // A& is better than binding an expression of type C to a
5037 // reference of type A&,
5038 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5039 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5040 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5042 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5044 }
5045 }
5046
5048}
5049
5051 if (!T.getQualifiers().hasUnaligned())
5052 return T;
5053
5054 Qualifiers Q;
5055 T = Ctx.getUnqualifiedArrayType(T, Q);
5056 Q.removeUnaligned();
5057 return Ctx.getQualifiedType(T, Q);
5058}
5059
5062 QualType OrigT1, QualType OrigT2,
5063 ReferenceConversions *ConvOut) {
5064 assert(!OrigT1->isReferenceType() &&
5065 "T1 must be the pointee type of the reference type");
5066 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5067
5068 QualType T1 = Context.getCanonicalType(OrigT1);
5069 QualType T2 = Context.getCanonicalType(OrigT2);
5070 Qualifiers T1Quals, T2Quals;
5071 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5072 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5073
5074 ReferenceConversions ConvTmp;
5075 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5076 Conv = ReferenceConversions();
5077
5078 // C++2a [dcl.init.ref]p4:
5079 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5080 // reference-related to "cv2 T2" if T1 is similar to T2, or
5081 // T1 is a base class of T2.
5082 // "cv1 T1" is reference-compatible with "cv2 T2" if
5083 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5084 // "pointer to cv1 T1" via a standard conversion sequence.
5085
5086 // Check for standard conversions we can apply to pointers: derived-to-base
5087 // conversions, ObjC pointer conversions, and function pointer conversions.
5088 // (Qualification conversions are checked last.)
5089 if (UnqualT1 == UnqualT2) {
5090 // Nothing to do.
5091 } else if (isCompleteType(Loc, OrigT2) &&
5092 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5093 Conv |= ReferenceConversions::DerivedToBase;
5094 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5095 UnqualT2->isObjCObjectOrInterfaceType() &&
5096 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5097 Conv |= ReferenceConversions::ObjC;
5098 else if (UnqualT2->isFunctionType() &&
5099 IsFunctionConversion(UnqualT2, UnqualT1)) {
5100 Conv |= ReferenceConversions::Function;
5101 // No need to check qualifiers; function types don't have them.
5102 return Ref_Compatible;
5103 }
5104 bool ConvertedReferent = Conv != 0;
5105
5106 // We can have a qualification conversion. Compute whether the types are
5107 // similar at the same time.
5108 bool PreviousToQualsIncludeConst = true;
5109 bool TopLevel = true;
5110 do {
5111 if (T1 == T2)
5112 break;
5113
5114 // We will need a qualification conversion.
5115 Conv |= ReferenceConversions::Qualification;
5116
5117 // Track whether we performed a qualification conversion anywhere other
5118 // than the top level. This matters for ranking reference bindings in
5119 // overload resolution.
5120 if (!TopLevel)
5121 Conv |= ReferenceConversions::NestedQualification;
5122
5123 // MS compiler ignores __unaligned qualifier for references; do the same.
5124 T1 = withoutUnaligned(Context, T1);
5125 T2 = withoutUnaligned(Context, T2);
5126
5127 // If we find a qualifier mismatch, the types are not reference-compatible,
5128 // but are still be reference-related if they're similar.
5129 bool ObjCLifetimeConversion = false;
5130 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5131 PreviousToQualsIncludeConst,
5132 ObjCLifetimeConversion, getASTContext()))
5133 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5134 ? Ref_Related
5136
5137 // FIXME: Should we track this for any level other than the first?
5138 if (ObjCLifetimeConversion)
5139 Conv |= ReferenceConversions::ObjCLifetime;
5140
5141 TopLevel = false;
5142 } while (Context.UnwrapSimilarTypes(T1, T2));
5143
5144 // At this point, if the types are reference-related, we must either have the
5145 // same inner type (ignoring qualifiers), or must have already worked out how
5146 // to convert the referent.
5147 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5150}
5151
5152/// Look for a user-defined conversion to a value reference-compatible
5153/// with DeclType. Return true if something definite is found.
5154static bool
5156 QualType DeclType, SourceLocation DeclLoc,
5157 Expr *Init, QualType T2, bool AllowRvalues,
5158 bool AllowExplicit) {
5159 assert(T2->isRecordType() && "Can only find conversions of record types.");
5160 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5161 OverloadCandidateSet CandidateSet(
5163 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5164 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5165 NamedDecl *D = *I;
5167 if (isa<UsingShadowDecl>(D))
5168 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5169
5170 FunctionTemplateDecl *ConvTemplate
5171 = dyn_cast<FunctionTemplateDecl>(D);
5172 CXXConversionDecl *Conv;
5173 if (ConvTemplate)
5174 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5175 else
5176 Conv = cast<CXXConversionDecl>(D);
5177
5178 if (AllowRvalues) {
5179 // If we are initializing an rvalue reference, don't permit conversion
5180 // functions that return lvalues.
5181 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5182 const ReferenceType *RefType
5184 if (RefType && !RefType->getPointeeType()->isFunctionType())
5185 continue;
5186 }
5187
5188 if (!ConvTemplate &&
5190 DeclLoc,
5191 Conv->getConversionType()
5196 continue;
5197 } else {
5198 // If the conversion function doesn't return a reference type,
5199 // it can't be considered for this conversion. An rvalue reference
5200 // is only acceptable if its referencee is a function type.
5201
5202 const ReferenceType *RefType =
5204 if (!RefType ||
5205 (!RefType->isLValueReferenceType() &&
5206 !RefType->getPointeeType()->isFunctionType()))
5207 continue;
5208 }
5209
5210 if (ConvTemplate)
5212 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5213 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5214 else
5216 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5217 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5218 }
5219
5220 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5221
5223 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5224 case OR_Success:
5225
5226 assert(Best->HasFinalConversion);
5227
5228 // C++ [over.ics.ref]p1:
5229 //
5230 // [...] If the parameter binds directly to the result of
5231 // applying a conversion function to the argument
5232 // expression, the implicit conversion sequence is a
5233 // user-defined conversion sequence (13.3.3.1.2), with the
5234 // second standard conversion sequence either an identity
5235 // conversion or, if the conversion function returns an
5236 // entity of a type that is a derived class of the parameter
5237 // type, a derived-to-base Conversion.
5238 if (!Best->FinalConversion.DirectBinding)
5239 return false;
5240
5241 ICS.setUserDefined();
5242 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5243 ICS.UserDefined.After = Best->FinalConversion;
5244 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5245 ICS.UserDefined.ConversionFunction = Best->Function;
5246 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5247 ICS.UserDefined.EllipsisConversion = false;
5248 assert(ICS.UserDefined.After.ReferenceBinding &&
5250 "Expected a direct reference binding!");
5251 return true;
5252
5253 case OR_Ambiguous:
5254 ICS.setAmbiguous();
5255 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5256 Cand != CandidateSet.end(); ++Cand)
5257 if (Cand->Best)
5258 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5259 return true;
5260
5262 case OR_Deleted:
5263 // There was no suitable conversion, or we found a deleted
5264 // conversion; continue with other checks.
5265 return false;
5266 }
5267
5268 llvm_unreachable("Invalid OverloadResult!");
5269}
5270
5271/// Compute an implicit conversion sequence for reference
5272/// initialization.
5273static ImplicitConversionSequence
5275 SourceLocation DeclLoc,
5276 bool SuppressUserConversions,
5277 bool AllowExplicit) {
5278 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5279
5280 // Most paths end in a failed conversion.
5283
5284 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5285 QualType T2 = Init->getType();
5286
5287 // If the initializer is the address of an overloaded function, try
5288 // to resolve the overloaded function. If all goes well, T2 is the
5289 // type of the resulting function.
5290 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5293 false, Found))
5294 T2 = Fn->getType();
5295 }
5296
5297 // Compute some basic properties of the types and the initializer.
5298 bool isRValRef = DeclType->isRValueReferenceType();
5299 Expr::Classification InitCategory = Init->Classify(S.Context);
5300
5302 Sema::ReferenceCompareResult RefRelationship =
5303 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5304
5305 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5306 ICS.setStandard();
5308 // FIXME: A reference binding can be a function conversion too. We should
5309 // consider that when ordering reference-to-function bindings.
5310 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5312 : (RefConv & Sema::ReferenceConversions::ObjC)
5314 : ICK_Identity;
5316 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5317 // a reference binding that performs a non-top-level qualification
5318 // conversion as a qualification conversion, not as an identity conversion.
5319 ICS.Standard.Third = (RefConv &
5320 Sema::ReferenceConversions::NestedQualification)
5322 : ICK_Identity;
5323 ICS.Standard.setFromType(T2);
5324 ICS.Standard.setToType(0, T2);
5325 ICS.Standard.setToType(1, T1);
5326 ICS.Standard.setToType(2, T1);
5327 ICS.Standard.ReferenceBinding = true;
5328 ICS.Standard.DirectBinding = BindsDirectly;
5329 ICS.Standard.IsLvalueReference = !isRValRef;
5331 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5334 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5335 ICS.Standard.FromBracedInitList = false;
5336 ICS.Standard.CopyConstructor = nullptr;
5338 };
5339
5340 // C++0x [dcl.init.ref]p5:
5341 // A reference to type "cv1 T1" is initialized by an expression
5342 // of type "cv2 T2" as follows:
5343
5344 // -- If reference is an lvalue reference and the initializer expression
5345 if (!isRValRef) {
5346 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5347 // reference-compatible with "cv2 T2," or
5348 //
5349 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5350 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5351 // C++ [over.ics.ref]p1:
5352 // When a parameter of reference type binds directly (8.5.3)
5353 // to an argument expression, the implicit conversion sequence
5354 // is the identity conversion, unless the argument expression
5355 // has a type that is a derived class of the parameter type,
5356 // in which case the implicit conversion sequence is a
5357 // derived-to-base Conversion (13.3.3.1).
5358 SetAsReferenceBinding(/*BindsDirectly=*/true);
5359
5360 // Nothing more to do: the inaccessibility/ambiguity check for
5361 // derived-to-base conversions is suppressed when we're
5362 // computing the implicit conversion sequence (C++
5363 // [over.best.ics]p2).
5364 return ICS;
5365 }
5366
5367 // -- has a class type (i.e., T2 is a class type), where T1 is
5368 // not reference-related to T2, and can be implicitly
5369 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5370 // is reference-compatible with "cv3 T3" 92) (this
5371 // conversion is selected by enumerating the applicable
5372 // conversion functions (13.3.1.6) and choosing the best
5373 // one through overload resolution (13.3)),
5374 if (!SuppressUserConversions && T2->isRecordType() &&
5375 S.isCompleteType(DeclLoc, T2) &&
5376 RefRelationship == Sema::Ref_Incompatible) {
5377 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5378 Init, T2, /*AllowRvalues=*/false,
5379 AllowExplicit))
5380 return ICS;
5381 }
5382 }
5383
5384 // -- Otherwise, the reference shall be an lvalue reference to a
5385 // non-volatile const type (i.e., cv1 shall be const), or the reference
5386 // shall be an rvalue reference.
5387 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5388 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5390 return ICS;
5391 }
5392
5393 // -- If the initializer expression
5394 //
5395 // -- is an xvalue, class prvalue, array prvalue or function
5396 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5397 if (RefRelationship == Sema::Ref_Compatible &&
5398 (InitCategory.isXValue() ||
5399 (InitCategory.isPRValue() &&
5400 (T2->isRecordType() || T2->isArrayType())) ||
5401 (InitCategory.isLValue() && T2->isFunctionType()))) {
5402 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5403 // binding unless we're binding to a class prvalue.
5404 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5405 // allow the use of rvalue references in C++98/03 for the benefit of
5406 // standard library implementors; therefore, we need the xvalue check here.
5407 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5408 !(InitCategory.isPRValue() || T2->isRecordType()));
5409 return ICS;
5410 }
5411
5412 // -- has a class type (i.e., T2 is a class type), where T1 is not
5413 // reference-related to T2, and can be implicitly converted to
5414 // an xvalue, class prvalue, or function lvalue of type
5415 // "cv3 T3", where "cv1 T1" is reference-compatible with
5416 // "cv3 T3",
5417 //
5418 // then the reference is bound to the value of the initializer
5419 // expression in the first case and to the result of the conversion
5420 // in the second case (or, in either case, to an appropriate base
5421 // class subobject).
5422 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5423 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5424 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5425 Init, T2, /*AllowRvalues=*/true,
5426 AllowExplicit)) {
5427 // In the second case, if the reference is an rvalue reference
5428 // and the second standard conversion sequence of the
5429 // user-defined conversion sequence includes an lvalue-to-rvalue
5430 // conversion, the program is ill-formed.
5431 if (ICS.isUserDefined() && isRValRef &&
5434
5435 return ICS;
5436 }
5437
5438 // A temporary of function type cannot be created; don't even try.
5439 if (T1->isFunctionType())
5440 return ICS;
5441
5442 // -- Otherwise, a temporary of type "cv1 T1" is created and
5443 // initialized from the initializer expression using the
5444 // rules for a non-reference copy initialization (8.5). The
5445 // reference is then bound to the temporary. If T1 is
5446 // reference-related to T2, cv1 must be the same
5447 // cv-qualification as, or greater cv-qualification than,
5448 // cv2; otherwise, the program is ill-formed.
5449 if (RefRelationship == Sema::Ref_Related) {
5450 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5451 // we would be reference-compatible or reference-compatible with
5452 // added qualification. But that wasn't the case, so the reference
5453 // initialization fails.
5454 //
5455 // Note that we only want to check address spaces and cvr-qualifiers here.
5456 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5457 Qualifiers T1Quals = T1.getQualifiers();
5458 Qualifiers T2Quals = T2.getQualifiers();
5459 T1Quals.removeObjCGCAttr();
5460 T1Quals.removeObjCLifetime();
5461 T2Quals.removeObjCGCAttr();
5462 T2Quals.removeObjCLifetime();
5463 // MS compiler ignores __unaligned qualifier for references; do the same.
5464 T1Quals.removeUnaligned();
5465 T2Quals.removeUnaligned();
5466 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5467 return ICS;
5468 }
5469
5470 // If at least one of the types is a class type, the types are not
5471 // related, and we aren't allowed any user conversions, the
5472 // reference binding fails. This case is important for breaking
5473 // recursion, since TryImplicitConversion below will attempt to
5474 // create a temporary through the use of a copy constructor.
5475 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5476 (T1->isRecordType() || T2->isRecordType()))
5477 return ICS;
5478
5479 // If T1 is reference-related to T2 and the reference is an rvalue
5480 // reference, the initializer expression shall not be an lvalue.
5481 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5482 Init->Classify(S.Context).isLValue()) {
5484 return ICS;
5485 }
5486
5487 // C++ [over.ics.ref]p2:
5488 // When a parameter of reference type is not bound directly to
5489 // an argument expression, the conversion sequence is the one
5490 // required to convert the argument expression to the
5491 // underlying type of the reference according to
5492 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5493 // to copy-initializing a temporary of the underlying type with
5494 // the argument expression. Any difference in top-level
5495 // cv-qualification is subsumed by the initialization itself
5496 // and does not constitute a conversion.
5497 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5498 AllowedExplicit::None,
5499 /*InOverloadResolution=*/false,
5500 /*CStyle=*/false,
5501 /*AllowObjCWritebackConversion=*/false,
5502 /*AllowObjCConversionOnExplicit=*/false);
5503
5504 // Of course, that's still a reference binding.
5505 if (ICS.isStandard()) {
5506 ICS.Standard.ReferenceBinding = true;
5507 ICS.Standard.IsLvalueReference = !isRValRef;
5508 ICS.Standard.BindsToFunctionLvalue = false;
5509 ICS.Standard.BindsToRvalue = true;
5512 } else if (ICS.isUserDefined()) {
5513 const ReferenceType *LValRefType =
5516
5517 // C++ [over.ics.ref]p3:
5518 // Except for an implicit object parameter, for which see 13.3.1, a
5519 // standard conversion sequence cannot be formed if it requires [...]
5520 // binding an rvalue reference to an lvalue other than a function
5521 // lvalue.
5522 // Note that the function case is not possible here.
5523 if (isRValRef && LValRefType) {
5525 return ICS;
5526 }
5527
5529 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5531 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5535 }
5536
5537 return ICS;
5538}
5539
5540static ImplicitConversionSequence
5541TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5542 bool SuppressUserConversions,
5543 bool InOverloadResolution,
5544 bool AllowObjCWritebackConversion,
5545 bool AllowExplicit = false);
5546
5547/// TryListConversion - Try to copy-initialize a value of type ToType from the
5548/// initializer list From.
5549static ImplicitConversionSequence
5551 bool SuppressUserConversions,
5552 bool InOverloadResolution,
5553 bool AllowObjCWritebackConversion) {
5554 // C++11 [over.ics.list]p1:
5555 // When an argument is an initializer list, it is not an expression and
5556 // special rules apply for converting it to a parameter type.
5557
5559 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5560
5561 // We need a complete type for what follows. With one C++20 exception,
5562 // incomplete types can never be initialized from init lists.
5563 QualType InitTy = ToType;
5564 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5565 if (AT && S.getLangOpts().CPlusPlus20)
5566 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5567 // C++20 allows list initialization of an incomplete array type.
5568 InitTy = IAT->getElementType();
5569 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5570 return Result;
5571
5572 // C++20 [over.ics.list]/2:
5573 // If the initializer list is a designated-initializer-list, a conversion
5574 // is only possible if the parameter has an aggregate type
5575 //
5576 // FIXME: The exception for reference initialization here is not part of the
5577 // language rules, but follow other compilers in adding it as a tentative DR
5578 // resolution.
5579 bool IsDesignatedInit = From->hasDesignatedInit();
5580 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5581 IsDesignatedInit)
5582 return Result;
5583
5584 // Per DR1467 and DR2137:
5585 // If the parameter type is an aggregate class X and the initializer list
5586 // has a single element of type cv U, where U is X or a class derived from
5587 // X, the implicit conversion sequence is the one required to convert the
5588 // element to the parameter type.
5589 //
5590 // Otherwise, if the parameter type is a character array [... ]
5591 // and the initializer list has a single element that is an
5592 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5593 // implicit conversion sequence is the identity conversion.
5594 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5595 if (ToType->isRecordType() && ToType->isAggregateType()) {
5596 QualType InitType = From->getInit(0)->getType();
5597 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5598 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5599 return TryCopyInitialization(S, From->getInit(0), ToType,
5600 SuppressUserConversions,
5601 InOverloadResolution,
5602 AllowObjCWritebackConversion);
5603 }
5604
5605 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5606 InitializedEntity Entity =
5608 /*Consumed=*/false);
5609 if (S.CanPerformCopyInitialization(Entity, From)) {
5610 Result.setStandard();
5611 Result.Standard.setAsIdentityConversion();
5612 Result.Standard.setFromType(ToType);
5613 Result.Standard.setAllToTypes(ToType);
5614 return Result;
5615 }
5616 }
5617 }
5618
5619 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5620 // C++11 [over.ics.list]p2:
5621 // If the parameter type is std::initializer_list<X> or "array of X" and
5622 // all the elements can be implicitly converted to X, the implicit
5623 // conversion sequence is the worst conversion necessary to convert an
5624 // element of the list to X.
5625 //
5626 // C++14 [over.ics.list]p3:
5627 // Otherwise, if the parameter type is "array of N X", if the initializer
5628 // list has exactly N elements or if it has fewer than N elements and X is
5629 // default-constructible, and if all the elements of the initializer list
5630 // can be implicitly converted to X, the implicit conversion sequence is
5631 // the worst conversion necessary to convert an element of the list to X.
5632 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5633 unsigned e = From->getNumInits();
5636 QualType());
5637 QualType ContTy = ToType;
5638 bool IsUnbounded = false;
5639 if (AT) {
5640 InitTy = AT->getElementType();
5641 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5642 if (CT->getSize().ult(e)) {
5643 // Too many inits, fatally bad
5645 ToType);
5646 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5647 return Result;
5648 }
5649 if (CT->getSize().ugt(e)) {
5650 // Need an init from empty {}, is there one?
5651 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5652 From->getEndLoc());
5653 EmptyList.setType(S.Context.VoidTy);
5654 DfltElt = TryListConversion(
5655 S, &EmptyList, InitTy, SuppressUserConversions,
5656 InOverloadResolution, AllowObjCWritebackConversion);
5657 if (DfltElt.isBad()) {
5658 // No {} init, fatally bad
5660 ToType);
5661 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5662 return Result;
5663 }
5664 }
5665 } else {
5666 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5667 IsUnbounded = true;
5668 if (!e) {
5669 // Cannot convert to zero-sized.
5671 ToType);
5672 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5673 return Result;
5674 }
5675 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5676 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5678 }
5679 }
5680
5681 Result.setStandard();
5682 Result.Standard.setAsIdentityConversion();
5683 Result.Standard.setFromType(InitTy);
5684 Result.Standard.setAllToTypes(InitTy);
5685 for (unsigned i = 0; i < e; ++i) {
5686 Expr *Init = From->getInit(i);
5688 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5689 AllowObjCWritebackConversion);
5690
5691 // Keep the worse conversion seen so far.
5692 // FIXME: Sequences are not totally ordered, so 'worse' can be
5693 // ambiguous. CWG has been informed.
5695 Result) ==
5697 Result = ICS;
5698 // Bail as soon as we find something unconvertible.
5699 if (Result.isBad()) {
5700 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5701 return Result;
5702 }
5703 }
5704 }
5705
5706 // If we needed any implicit {} initialization, compare that now.
5707 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5708 // has been informed that this might not be the best thing.
5709 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5710 S, From->getEndLoc(), DfltElt, Result) ==
5712 Result = DfltElt;
5713 // Record the type being initialized so that we may compare sequences
5714 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5715 return Result;
5716 }
5717
5718 // C++14 [over.ics.list]p4:
5719 // C++11 [over.ics.list]p3:
5720 // Otherwise, if the parameter is a non-aggregate class X and overload
5721 // resolution chooses a single best constructor [...] the implicit
5722 // conversion sequence is a user-defined conversion sequence. If multiple
5723 // constructors are viable but none is better than the others, the
5724 // implicit conversion sequence is a user-defined conversion sequence.
5725 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5726 // This function can deal with initializer lists.
5727 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5728 AllowedExplicit::None,
5729 InOverloadResolution, /*CStyle=*/false,
5730 AllowObjCWritebackConversion,
5731 /*AllowObjCConversionOnExplicit=*/false);
5732 }
5733
5734 // C++14 [over.ics.list]p5:
5735 // C++11 [over.ics.list]p4:
5736 // Otherwise, if the parameter has an aggregate type which can be
5737 // initialized from the initializer list [...] the implicit conversion
5738 // sequence is a user-defined conversion sequence.
5739 if (ToType->isAggregateType()) {
5740 // Type is an aggregate, argument is an init list. At this point it comes
5741 // down to checking whether the initialization works.
5742 // FIXME: Find out whether this parameter is consumed or not.
5743 InitializedEntity Entity =
5745 /*Consumed=*/false);
5747 From)) {
5748 Result.setUserDefined();
5749 Result.UserDefined.Before.setAsIdentityConversion();
5750 // Initializer lists don't have a type.
5751 Result.UserDefined.Before.setFromType(QualType());
5752 Result.UserDefined.Before.setAllToTypes(QualType());
5753
5754 Result.UserDefined.After.setAsIdentityConversion();
5755 Result.UserDefined.After.setFromType(ToType);
5756 Result.UserDefined.After.setAllToTypes(ToType);
5757 Result.UserDefined.ConversionFunction = nullptr;
5758 }
5759 return Result;
5760 }
5761
5762 // C++14 [over.ics.list]p6:
5763 // C++11 [over.ics.list]p5:
5764 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5765 if (ToType->isReferenceType()) {
5766 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5767 // mention initializer lists in any way. So we go by what list-
5768 // initialization would do and try to extrapolate from that.
5769
5770 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5771
5772 // If the initializer list has a single element that is reference-related
5773 // to the parameter type, we initialize the reference from that.
5774 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5775 Expr *Init = From->getInit(0);
5776
5777 QualType T2 = Init->getType();
5778
5779 // If the initializer is the address of an overloaded function, try
5780 // to resolve the overloaded function. If all goes well, T2 is the
5781 // type of the resulting function.
5782 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5785 Init, ToType, false, Found))
5786 T2 = Fn->getType();
5787 }
5788
5789 // Compute some basic properties of the types and the initializer.
5790 Sema::ReferenceCompareResult RefRelationship =
5791 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5792
5793 if (RefRelationship >= Sema::Ref_Related) {
5794 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5795 SuppressUserConversions,
5796 /*AllowExplicit=*/false);
5797 }
5798 }
5799
5800 // Otherwise, we bind the reference to a temporary created from the
5801 // initializer list.
5802 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5803 InOverloadResolution,
5804 AllowObjCWritebackConversion);
5805 if (Result.isFailure())
5806 return Result;
5807 assert(!Result.isEllipsis() &&
5808 "Sub-initialization cannot result in ellipsis conversion.");
5809
5810 // Can we even bind to a temporary?
5811 if (ToType->isRValueReferenceType() ||
5812 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5813 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5814 Result.UserDefined.After;
5815 SCS.ReferenceBinding = true;
5817 SCS.BindsToRvalue = true;
5818 SCS.BindsToFunctionLvalue = false;
5821 SCS.FromBracedInitList = false;
5822
5823 } else
5825 From, ToType);
5826 return Result;
5827 }
5828
5829 // C++14 [over.ics.list]p7:
5830 // C++11 [over.ics.list]p6:
5831 // Otherwise, if the parameter type is not a class:
5832 if (!ToType->isRecordType()) {
5833 // - if the initializer list has one element that is not itself an
5834 // initializer list, the implicit conversion sequence is the one
5835 // required to convert the element to the parameter type.
5836 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5837 // single integer.
5838 unsigned NumInits = From->getNumInits();
5839 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5840 !isa<EmbedExpr>(From->getInit(0))) {
5841 Result = TryCopyInitialization(
5842 S, From->getInit(0), ToType, SuppressUserConversions,
5843 InOverloadResolution, AllowObjCWritebackConversion);
5844 if (Result.isStandard())
5845 Result.Standard.FromBracedInitList = true;
5846 }
5847 // - if the initializer list has no elements, the implicit conversion
5848 // sequence is the identity conversion.
5849 else if (NumInits == 0) {
5850 Result.setStandard();
5851 Result.Standard.setAsIdentityConversion();
5852 Result.Standard.setFromType(ToType);
5853 Result.Standard.setAllToTypes(ToType);
5854 }
5855 return Result;
5856 }
5857
5858 // C++14 [over.ics.list]p8:
5859 // C++11 [over.ics.list]p7:
5860 // In all cases other than those enumerated above, no conversion is possible
5861 return Result;
5862}
5863
5864/// TryCopyInitialization - Try to copy-initialize a value of type
5865/// ToType from the expression From. Return the implicit conversion
5866/// sequence required to pass this argument, which may be a bad
5867/// conversion sequence (meaning that the argument cannot be passed to
5868/// a parameter of this type). If @p SuppressUserConversions, then we
5869/// do not permit any user-defined conversion sequences.
5870static ImplicitConversionSequence
5872 bool SuppressUserConversions,
5873 bool InOverloadResolution,
5874 bool AllowObjCWritebackConversion,
5875 bool AllowExplicit) {
5876 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5877 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5878 InOverloadResolution,AllowObjCWritebackConversion);
5879
5880 if (ToType->isReferenceType())
5881 return TryReferenceInit(S, From, ToType,
5882 /*FIXME:*/ From->getBeginLoc(),
5883 SuppressUserConversions, AllowExplicit);
5884
5885 return TryImplicitConversion(S, From, ToType,
5886 SuppressUserConversions,
5887 AllowedExplicit::None,
5888 InOverloadResolution,
5889 /*CStyle=*/false,
5890 AllowObjCWritebackConversion,
5891 /*AllowObjCConversionOnExplicit=*/false);
5892}
5893
5894static bool TryCopyInitialization(const CanQualType FromQTy,
5895 const CanQualType ToQTy,
5896 Sema &S,
5897 SourceLocation Loc,
5898 ExprValueKind FromVK) {
5899 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5901 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5902
5903 return !ICS.isBad();
5904}
5905
5906/// TryObjectArgumentInitialization - Try to initialize the object
5907/// parameter of the given member function (@c Method) from the
5908/// expression @p From.
5910 Sema &S, SourceLocation Loc, QualType FromType,
5911 Expr::Classification FromClassification, CXXMethodDecl *Method,
5912 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5913 QualType ExplicitParameterType = QualType(),
5914 bool SuppressUserConversion = false) {
5915
5916 // We need to have an object of class type.
5917 if (const auto *PT = FromType->getAs<PointerType>()) {
5918 FromType = PT->getPointeeType();
5919
5920 // When we had a pointer, it's implicitly dereferenced, so we
5921 // better have an lvalue.
5922 assert(FromClassification.isLValue());
5923 }
5924
5925 auto ValueKindFromClassification = [](Expr::Classification C) {
5926 if (C.isPRValue())
5927 return clang::VK_PRValue;
5928 if (C.isXValue())
5929 return VK_XValue;
5930 return clang::VK_LValue;
5931 };
5932
5933 if (Method->isExplicitObjectMemberFunction()) {
5934 if (ExplicitParameterType.isNull())
5935 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5936 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5937 ValueKindFromClassification(FromClassification));
5939 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5940 /*InOverloadResolution=*/true, false);
5941 if (ICS.isBad())
5942 ICS.Bad.FromExpr = nullptr;
5943 return ICS;
5944 }
5945
5946 assert(FromType->isRecordType());
5947
5948 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
5949 // C++98 [class.dtor]p2:
5950 // A destructor can be invoked for a const, volatile or const volatile
5951 // object.
5952 // C++98 [over.match.funcs]p4:
5953 // For static member functions, the implicit object parameter is considered
5954 // to match any object (since if the function is selected, the object is
5955 // discarded).
5956 Qualifiers Quals = Method->getMethodQualifiers();
5957 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5958 Quals.addConst();
5959 Quals.addVolatile();
5960 }
5961
5962 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5963
5964 // Set up the conversion sequence as a "bad" conversion, to allow us
5965 // to exit early.
5967
5968 // C++0x [over.match.funcs]p4:
5969 // For non-static member functions, the type of the implicit object
5970 // parameter is
5971 //
5972 // - "lvalue reference to cv X" for functions declared without a
5973 // ref-qualifier or with the & ref-qualifier
5974 // - "rvalue reference to cv X" for functions declared with the &&
5975 // ref-qualifier
5976 //
5977 // where X is the class of which the function is a member and cv is the
5978 // cv-qualification on the member function declaration.
5979 //
5980 // However, when finding an implicit conversion sequence for the argument, we
5981 // are not allowed to perform user-defined conversions
5982 // (C++ [over.match.funcs]p5). We perform a simplified version of
5983 // reference binding here, that allows class rvalues to bind to
5984 // non-constant references.
5985
5986 // First check the qualifiers.
5987 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5988 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5989 if (ImplicitParamType.getCVRQualifiers() !=
5990 FromTypeCanon.getLocalCVRQualifiers() &&
5991 !ImplicitParamType.isAtLeastAsQualifiedAs(
5992 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5994 FromType, ImplicitParamType);
5995 return ICS;
5996 }
5997
5998 if (FromTypeCanon.hasAddressSpace()) {
5999 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6000 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6001 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6002 S.getASTContext())) {
6004 FromType, ImplicitParamType);
6005 return ICS;
6006 }
6007 }
6008
6009 // Check that we have either the same type or a derived type. It
6010 // affects the conversion rank.
6011 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6012 ImplicitConversionKind SecondKind;
6013 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6014 SecondKind = ICK_Identity;
6015 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6016 SecondKind = ICK_Derived_To_Base;
6017 } else if (!Method->isExplicitObjectMemberFunction()) {
6019 FromType, ImplicitParamType);
6020 return ICS;
6021 }
6022
6023 // Check the ref-qualifier.
6024 switch (Method->getRefQualifier()) {
6025 case RQ_None:
6026 // Do nothing; we don't care about lvalueness or rvalueness.
6027 break;
6028
6029 case RQ_LValue:
6030 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6031 // non-const lvalue reference cannot bind to an rvalue
6033 ImplicitParamType);
6034 return ICS;
6035 }
6036 break;
6037
6038 case RQ_RValue:
6039 if (!FromClassification.isRValue()) {
6040 // rvalue reference cannot bind to an lvalue
6042 ImplicitParamType);
6043 return ICS;
6044 }
6045 break;
6046 }
6047
6048 // Success. Mark this as a reference binding.
6049 ICS.setStandard();
6051 ICS.Standard.Second = SecondKind;
6052 ICS.Standard.setFromType(FromType);
6053 ICS.Standard.setAllToTypes(ImplicitParamType);
6054 ICS.Standard.ReferenceBinding = true;
6055 ICS.Standard.DirectBinding = true;
6056 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6057 ICS.Standard.BindsToFunctionLvalue = false;
6058 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6059 ICS.Standard.FromBracedInitList = false;
6061 = (Method->getRefQualifier() == RQ_None);
6062 return ICS;
6063}
6064
6065/// PerformObjectArgumentInitialization - Perform initialization of
6066/// the implicit object parameter for the given Method with the given
6067/// expression.
6069 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6071 QualType FromRecordType, DestType;
6072 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6073
6074 Expr::Classification FromClassification;
6075 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6076 FromRecordType = PT->getPointeeType();
6077 DestType = Method->getThisType();
6078 FromClassification = Expr::Classification::makeSimpleLValue();
6079 } else {
6080 FromRecordType = From->getType();
6081 DestType = ImplicitParamRecordType;
6082 FromClassification = From->Classify(Context);
6083
6084 // CWG2813 [expr.call]p6:
6085 // If the function is an implicit object member function, the object
6086 // expression of the class member access shall be a glvalue [...]
6087 if (From->isPRValue()) {
6088 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6089 Method->getRefQualifier() !=
6091 }
6092 }
6093
6094 // Note that we always use the true parent context when performing
6095 // the actual argument initialization.
6097 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6098 Method->getParent());
6099 if (ICS.isBad()) {
6100 switch (ICS.Bad.Kind) {
6102 Qualifiers FromQs = FromRecordType.getQualifiers();
6103 Qualifiers ToQs = DestType.getQualifiers();
6104 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6105 if (CVR) {
6106 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6107 << Method->getDeclName() << FromRecordType << (CVR - 1)
6108 << From->getSourceRange();
6109 Diag(Method->getLocation(), diag::note_previous_decl)
6110 << Method->getDeclName();
6111 return ExprError();
6112 }
6113 break;
6114 }
6115
6118 bool IsRValueQualified =
6119 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6120 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6121 << Method->getDeclName() << FromClassification.isRValue()
6122 << IsRValueQualified;
6123 Diag(Method->getLocation(), diag::note_previous_decl)
6124 << Method->getDeclName();
6125 return ExprError();
6126 }
6127
6130 break;
6131
6134 llvm_unreachable("Lists are not objects");
6135 }
6136
6137 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6138 << ImplicitParamRecordType << FromRecordType
6139 << From->getSourceRange();
6140 }
6141
6142 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6143 ExprResult FromRes =
6144 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6145 if (FromRes.isInvalid())
6146 return ExprError();
6147 From = FromRes.get();
6148 }
6149
6150 if (!Context.hasSameType(From->getType(), DestType)) {
6151 CastKind CK;
6152 QualType PteeTy = DestType->getPointeeType();
6153 LangAS DestAS =
6154 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6155 if (FromRecordType.getAddressSpace() != DestAS)
6156 CK = CK_AddressSpaceConversion;
6157 else
6158 CK = CK_NoOp;
6159 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6160 }
6161 return From;
6162}
6163
6164/// TryContextuallyConvertToBool - Attempt to contextually convert the
6165/// expression From to bool (C++0x [conv]p3).
6168 // C++ [dcl.init]/17.8:
6169 // - Otherwise, if the initialization is direct-initialization, the source
6170 // type is std::nullptr_t, and the destination type is bool, the initial
6171 // value of the object being initialized is false.
6172 if (From->getType()->isNullPtrType())
6174 S.Context.BoolTy,
6175 From->isGLValue());
6176
6177 // All other direct-initialization of bool is equivalent to an implicit
6178 // conversion to bool in which explicit conversions are permitted.
6179 return TryImplicitConversion(S, From, S.Context.BoolTy,
6180 /*SuppressUserConversions=*/false,
6181 AllowedExplicit::Conversions,
6182 /*InOverloadResolution=*/false,
6183 /*CStyle=*/false,
6184 /*AllowObjCWritebackConversion=*/false,
6185 /*AllowObjCConversionOnExplicit=*/false);
6186}
6187
6189 if (checkPlaceholderForOverload(*this, From))
6190 return ExprError();
6191
6193 if (!ICS.isBad())
6194 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6196
6198 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6199 << From->getType() << From->getSourceRange();
6200 return ExprError();
6201}
6202
6203/// Check that the specified conversion is permitted in a converted constant
6204/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6205/// is acceptable.
6208 // Since we know that the target type is an integral or unscoped enumeration
6209 // type, most conversion kinds are impossible. All possible First and Third
6210 // conversions are fine.
6211 switch (SCS.Second) {
6212 case ICK_Identity:
6214 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6216 return true;
6217
6219 // Conversion from an integral or unscoped enumeration type to bool is
6220 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6221 // conversion, so we allow it in a converted constant expression.
6222 //
6223 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6224 // a lot of popular code. We should at least add a warning for this
6225 // (non-conforming) extension.
6227 SCS.getToType(2)->isBooleanType();
6228
6230 case ICK_Pointer_Member:
6231 // C++1z: null pointer conversions and null member pointer conversions are
6232 // only permitted if the source type is std::nullptr_t.
6233 return SCS.getFromType()->isNullPtrType();
6234
6246 case ICK_Vector_Splat:
6247 case ICK_Complex_Real:
6256 return false;
6257
6262 llvm_unreachable("found a first conversion kind in Second");
6263
6265 case ICK_Qualification:
6266 llvm_unreachable("found a third conversion kind in Second");
6267
6269 break;
6270 }
6271
6272 llvm_unreachable("unknown conversion kind");
6273}
6274
6275/// BuildConvertedConstantExpression - Check that the expression From is a
6276/// converted constant expression of type T, perform the conversion but
6277/// does not evaluate the expression
6279 QualType T, CCEKind CCE,
6280 NamedDecl *Dest,
6281 APValue &PreNarrowingValue) {
6282 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6284 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6285 "converted constant expression outside C++11 or TTP matching");
6286
6287 if (checkPlaceholderForOverload(S, From))
6288 return ExprError();
6289
6290 // C++1z [expr.const]p3:
6291 // A converted constant expression of type T is an expression,
6292 // implicitly converted to type T, where the converted
6293 // expression is a constant expression and the implicit conversion
6294 // sequence contains only [... list of conversions ...].
6296 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6298 : TryCopyInitialization(S, From, T,
6299 /*SuppressUserConversions=*/false,
6300 /*InOverloadResolution=*/false,
6301 /*AllowObjCWritebackConversion=*/false,
6302 /*AllowExplicit=*/false);
6303 StandardConversionSequence *SCS = nullptr;
6304 switch (ICS.getKind()) {
6306 SCS = &ICS.Standard;
6307 break;
6309 if (T->isRecordType())
6310 SCS = &ICS.UserDefined.Before;
6311 else
6312 SCS = &ICS.UserDefined.After;
6313 break;
6317 return S.Diag(From->getBeginLoc(),
6318 diag::err_typecheck_converted_constant_expression)
6319 << From->getType() << From->getSourceRange() << T;
6320 return ExprError();
6321
6324 llvm_unreachable("bad conversion in converted constant expression");
6325 }
6326
6327 // Check that we would only use permitted conversions.
6328 if (!CheckConvertedConstantConversions(S, *SCS)) {
6329 return S.Diag(From->getBeginLoc(),
6330 diag::err_typecheck_converted_constant_expression_disallowed)
6331 << From->getType() << From->getSourceRange() << T;
6332 }
6333 // [...] and where the reference binding (if any) binds directly.
6334 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6335 return S.Diag(From->getBeginLoc(),
6336 diag::err_typecheck_converted_constant_expression_indirect)
6337 << From->getType() << From->getSourceRange() << T;
6338 }
6339 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6340 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6341 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6342 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6343 // case explicitly.
6344 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6345 return S.Diag(From->getBeginLoc(),
6346 diag::err_reference_bind_to_bitfield_in_cce)
6347 << From->getSourceRange();
6348 }
6349
6350 // Usually we can simply apply the ImplicitConversionSequence we formed
6351 // earlier, but that's not guaranteed to work when initializing an object of
6352 // class type.
6353 ExprResult Result;
6354 bool IsTemplateArgument =
6356 if (T->isRecordType()) {
6357 assert(IsTemplateArgument &&
6358 "unexpected class type converted constant expr");
6359 Result = S.PerformCopyInitialization(
6362 SourceLocation(), From);
6363 } else {
6364 Result =
6366 }
6367 if (Result.isInvalid())
6368 return Result;
6369
6370 // C++2a [intro.execution]p5:
6371 // A full-expression is [...] a constant-expression [...]
6372 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6373 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6374 IsTemplateArgument);
6375 if (Result.isInvalid())
6376 return Result;
6377
6378 // Check for a narrowing implicit conversion.
6379 bool ReturnPreNarrowingValue = false;
6380 QualType PreNarrowingType;
6381 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6382 PreNarrowingType)) {
6384 // Implicit conversion to a narrower type, and the value is not a constant
6385 // expression. We'll diagnose this in a moment.
6386 case NK_Not_Narrowing:
6387 break;
6388
6390 if (CCE == CCEKind::ArrayBound &&
6391 PreNarrowingType->isIntegralOrEnumerationType() &&
6392 PreNarrowingValue.isInt()) {
6393 // Don't diagnose array bound narrowing here; we produce more precise
6394 // errors by allowing the un-narrowed value through.
6395 ReturnPreNarrowingValue = true;
6396 break;
6397 }
6398 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6399 << CCE << /*Constant*/ 1
6400 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6401 break;
6402
6404 // Implicit conversion to a narrower type, but the expression is
6405 // value-dependent so we can't tell whether it's actually narrowing.
6406 // For matching the parameters of a TTP, the conversion is ill-formed
6407 // if it may narrow.
6408 if (CCE != CCEKind::TempArgStrict)
6409 break;
6410 [[fallthrough]];
6411 case NK_Type_Narrowing:
6412 // FIXME: It would be better to diagnose that the expression is not a
6413 // constant expression.
6414 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6415 << CCE << /*Constant*/ 0 << From->getType() << T;
6416 break;
6417 }
6418 if (!ReturnPreNarrowingValue)
6419 PreNarrowingValue = {};
6420
6421 return Result;
6422}
6423
6424/// CheckConvertedConstantExpression - Check that the expression From is a
6425/// converted constant expression of type T, perform the conversion and produce
6426/// the converted expression, per C++11 [expr.const]p3.
6429 CCEKind CCE, bool RequireInt,
6430 NamedDecl *Dest) {
6431
6432 APValue PreNarrowingValue;
6433 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6434 PreNarrowingValue);
6435 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6436 Value = APValue();
6437 return Result;
6438 }
6439 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6440 RequireInt, PreNarrowingValue);
6441}
6442
6444 CCEKind CCE,
6445 NamedDecl *Dest) {
6446 APValue PreNarrowingValue;
6447 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6448 PreNarrowingValue);
6449}
6450
6452 APValue &Value, CCEKind CCE,
6453 NamedDecl *Dest) {
6454 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6455 Dest);
6456}
6457
6459 llvm::APSInt &Value,
6460 CCEKind CCE) {
6461 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6462
6463 APValue V;
6464 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6465 /*Dest=*/nullptr);
6466 if (!R.isInvalid() && !R.get()->isValueDependent())
6467 Value = V.getInt();
6468 return R;
6469}
6470
6473 CCEKind CCE, bool RequireInt,
6474 const APValue &PreNarrowingValue) {
6475
6476 ExprResult Result = E;
6477 // Check the expression is a constant expression.
6479 Expr::EvalResult Eval;
6480 Eval.Diag = &Notes;
6481
6482 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6483
6484 ConstantExprKind Kind;
6485 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6486 Kind = ConstantExprKind::ClassTemplateArgument;
6487 else if (CCE == CCEKind::TemplateArg)
6488 Kind = ConstantExprKind::NonClassTemplateArgument;
6489 else
6490 Kind = ConstantExprKind::Normal;
6491
6492 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6493 (RequireInt && !Eval.Val.isInt())) {
6494 // The expression can't be folded, so we can't keep it at this position in
6495 // the AST.
6496 Result = ExprError();
6497 } else {
6498 Value = Eval.Val;
6499
6500 if (Notes.empty()) {
6501 // It's a constant expression.
6502 Expr *E = Result.get();
6503 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6504 // We expect a ConstantExpr to have a value associated with it
6505 // by this point.
6506 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6507 "ConstantExpr has no value associated with it");
6508 (void)CE;
6509 } else {
6511 }
6512 if (!PreNarrowingValue.isAbsent())
6513 Value = std::move(PreNarrowingValue);
6514 return E;
6515 }
6516 }
6517
6518 // It's not a constant expression. Produce an appropriate diagnostic.
6519 if (Notes.size() == 1 &&
6520 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6521 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6522 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6523 diag::note_constexpr_invalid_template_arg) {
6524 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6525 for (unsigned I = 0; I < Notes.size(); ++I)
6526 Diag(Notes[I].first, Notes[I].second);
6527 } else {
6528 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6529 << CCE << E->getSourceRange();
6530 for (unsigned I = 0; I < Notes.size(); ++I)
6531 Diag(Notes[I].first, Notes[I].second);
6532 }
6533 return ExprError();
6534}
6535
6536/// dropPointerConversions - If the given standard conversion sequence
6537/// involves any pointer conversions, remove them. This may change
6538/// the result type of the conversion sequence.
6540 if (SCS.Second == ICK_Pointer_Conversion) {
6541 SCS.Second = ICK_Identity;
6542 SCS.Dimension = ICK_Identity;
6543 SCS.Third = ICK_Identity;
6544 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6545 }
6546}
6547
6548/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6549/// convert the expression From to an Objective-C pointer type.
6550static ImplicitConversionSequence
6552 // Do an implicit conversion to 'id'.
6555 = TryImplicitConversion(S, From, Ty,
6556 // FIXME: Are these flags correct?
6557 /*SuppressUserConversions=*/false,
6558 AllowedExplicit::Conversions,
6559 /*InOverloadResolution=*/false,
6560 /*CStyle=*/false,
6561 /*AllowObjCWritebackConversion=*/false,
6562 /*AllowObjCConversionOnExplicit=*/true);
6563
6564 // Strip off any final conversions to 'id'.
6565 switch (ICS.getKind()) {
6570 break;
6571
6574 break;
6575
6578 break;
6579 }
6580
6581 return ICS;
6582}
6583
6585 if (checkPlaceholderForOverload(*this, From))
6586 return ExprError();
6587
6588 QualType Ty = Context.getObjCIdType();
6591 if (!ICS.isBad())
6592 return PerformImplicitConversion(From, Ty, ICS,
6594 return ExprResult();
6595}
6596
6597static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6598 const Expr *Base = nullptr;
6599 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6600 "expected a member expression");
6601
6602 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6603 M && !M->isImplicitAccess())
6604 Base = M->getBase();
6605 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6606 M && !M->isImplicitAccess())
6607 Base = M->getBase();
6608
6609 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6610
6611 if (T->isPointerType())
6612 T = T->getPointeeType();
6613
6614 return T;
6615}
6616
6618 const FunctionDecl *Fun) {
6619 QualType ObjType = Obj->getType();
6620 if (ObjType->isPointerType()) {
6621 ObjType = ObjType->getPointeeType();
6622 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6624 /*CanOverflow=*/false, FPOptionsOverride());
6625 }
6626 return Obj;
6627}
6628
6636
6638 Expr *Object, MultiExprArg &Args,
6639 SmallVectorImpl<Expr *> &NewArgs) {
6640 assert(Method->isExplicitObjectMemberFunction() &&
6641 "Method is not an explicit member function");
6642 assert(NewArgs.empty() && "NewArgs should be empty");
6643
6644 NewArgs.reserve(Args.size() + 1);
6645 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6646 NewArgs.push_back(This);
6647 NewArgs.append(Args.begin(), Args.end());
6648 Args = NewArgs;
6650 Method, Object->getBeginLoc());
6651}
6652
6653/// Determine whether the provided type is an integral type, or an enumeration
6654/// type of a permitted flavor.
6656 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6657 : T->isIntegralOrUnscopedEnumerationType();
6658}
6659
6660static ExprResult
6663 QualType T, UnresolvedSetImpl &ViableConversions) {
6664
6665 if (Converter.Suppress)
6666 return ExprError();
6667
6668 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6669 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6670 CXXConversionDecl *Conv =
6671 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6673 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6674 }
6675 return From;
6676}
6677
6678static bool
6681 QualType T, bool HadMultipleCandidates,
6682 UnresolvedSetImpl &ExplicitConversions) {
6683 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6684 DeclAccessPair Found = ExplicitConversions[0];
6685 CXXConversionDecl *Conversion =
6686 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6687
6688 // The user probably meant to invoke the given explicit
6689 // conversion; use it.
6690 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6691 std::string TypeStr;
6692 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6693
6694 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6696 "static_cast<" + TypeStr + ">(")
6698 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6699 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6700
6701 // If we aren't in a SFINAE context, build a call to the
6702 // explicit conversion function.
6703 if (SemaRef.isSFINAEContext())
6704 return true;
6705
6706 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6707 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6708 HadMultipleCandidates);
6709 if (Result.isInvalid())
6710 return true;
6711
6712 // Replace the conversion with a RecoveryExpr, so we don't try to
6713 // instantiate it later, but can further diagnose here.
6714 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6715 From, Result.get()->getType());
6716 if (Result.isInvalid())
6717 return true;
6718 From = Result.get();
6719 }
6720 return false;
6721}
6722
6723static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6725 QualType T, bool HadMultipleCandidates,
6727 CXXConversionDecl *Conversion =
6728 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6729 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6730
6731 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6732 if (!Converter.SuppressConversion) {
6733 if (SemaRef.isSFINAEContext())
6734 return true;
6735
6736 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6737 << From->getSourceRange();
6738 }
6739
6740 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6741 HadMultipleCandidates);
6742 if (Result.isInvalid())
6743 return true;
6744 // Record usage of conversion in an implicit cast.
6745 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6746 CK_UserDefinedConversion, Result.get(),
6747 nullptr, Result.get()->getValueKind(),
6748 SemaRef.CurFPFeatureOverrides());
6749 return false;
6750}
6751
6753 Sema &SemaRef, SourceLocation Loc, Expr *From,
6755 if (!Converter.match(From->getType()) && !Converter.Suppress)
6756 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6757 << From->getSourceRange();
6758
6759 return SemaRef.DefaultLvalueConversion(From);
6760}
6761
6762static void
6764 UnresolvedSetImpl &ViableConversions,
6765 OverloadCandidateSet &CandidateSet) {
6766 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6767 NamedDecl *D = FoundDecl.getDecl();
6768 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6769 if (isa<UsingShadowDecl>(D))
6770 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6771
6772 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6774 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6775 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6776 continue;
6777 }
6779 SemaRef.AddConversionCandidate(
6780 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6781 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6782 }
6783}
6784
6785/// Attempt to convert the given expression to a type which is accepted
6786/// by the given converter.
6787///
6788/// This routine will attempt to convert an expression of class type to a
6789/// type accepted by the specified converter. In C++11 and before, the class
6790/// must have a single non-explicit conversion function converting to a matching
6791/// type. In C++1y, there can be multiple such conversion functions, but only
6792/// one target type.
6793///
6794/// \param Loc The source location of the construct that requires the
6795/// conversion.
6796///
6797/// \param From The expression we're converting from.
6798///
6799/// \param Converter Used to control and diagnose the conversion process.
6800///
6801/// \returns The expression, converted to an integral or enumeration type if
6802/// successful.
6804 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6805 // We can't perform any more checking for type-dependent expressions.
6806 if (From->isTypeDependent())
6807 return From;
6808
6809 // Process placeholders immediately.
6810 if (From->hasPlaceholderType()) {
6811 ExprResult result = CheckPlaceholderExpr(From);
6812 if (result.isInvalid())
6813 return result;
6814 From = result.get();
6815 }
6816
6817 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6818 ExprResult Converted = DefaultLvalueConversion(From);
6819 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6820 // If the expression already has a matching type, we're golden.
6821 if (Converter.match(T))
6822 return Converted;
6823
6824 // FIXME: Check for missing '()' if T is a function type?
6825
6826 // We can only perform contextual implicit conversions on objects of class
6827 // type.
6828 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6829 if (!RecordTy || !getLangOpts().CPlusPlus) {
6830 if (!Converter.Suppress)
6831 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6832 return From;
6833 }
6834
6835 // We must have a complete class type.
6836 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6837 ContextualImplicitConverter &Converter;
6838 Expr *From;
6839
6840 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6841 : Converter(Converter), From(From) {}
6842
6843 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6844 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6845 }
6846 } IncompleteDiagnoser(Converter, From);
6847
6848 if (Converter.Suppress ? !isCompleteType(Loc, T)
6849 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6850 return From;
6851
6852 // Look for a conversion to an integral or enumeration type.
6854 ViableConversions; // These are *potentially* viable in C++1y.
6855 UnresolvedSet<4> ExplicitConversions;
6856 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getOriginalDecl())
6857 ->getDefinitionOrSelf()
6858 ->getVisibleConversionFunctions();
6859
6860 bool HadMultipleCandidates =
6861 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6862
6863 // To check that there is only one target type, in C++1y:
6864 QualType ToType;
6865 bool HasUniqueTargetType = true;
6866
6867 // Collect explicit or viable (potentially in C++1y) conversions.
6868 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6869 NamedDecl *D = (*I)->getUnderlyingDecl();
6870 CXXConversionDecl *Conversion;
6871 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6872 if (ConvTemplate) {
6874 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6875 else
6876 continue; // C++11 does not consider conversion operator templates(?).
6877 } else
6878 Conversion = cast<CXXConversionDecl>(D);
6879
6880 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6881 "Conversion operator templates are considered potentially "
6882 "viable in C++1y");
6883
6884 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6885 if (Converter.match(CurToType) || ConvTemplate) {
6886
6887 if (Conversion->isExplicit()) {
6888 // FIXME: For C++1y, do we need this restriction?
6889 // cf. diagnoseNoViableConversion()
6890 if (!ConvTemplate)
6891 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6892 } else {
6893 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6894 if (ToType.isNull())
6895 ToType = CurToType.getUnqualifiedType();
6896 else if (HasUniqueTargetType &&
6897 (CurToType.getUnqualifiedType() != ToType))
6898 HasUniqueTargetType = false;
6899 }
6900 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6901 }
6902 }
6903 }
6904
6905 if (getLangOpts().CPlusPlus14) {
6906 // C++1y [conv]p6:
6907 // ... An expression e of class type E appearing in such a context
6908 // is said to be contextually implicitly converted to a specified
6909 // type T and is well-formed if and only if e can be implicitly
6910 // converted to a type T that is determined as follows: E is searched
6911 // for conversion functions whose return type is cv T or reference to
6912 // cv T such that T is allowed by the context. There shall be
6913 // exactly one such T.
6914
6915 // If no unique T is found:
6916 if (ToType.isNull()) {
6917 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6918 HadMultipleCandidates,
6919 ExplicitConversions))
6920 return ExprError();
6921 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6922 }
6923
6924 // If more than one unique Ts are found:
6925 if (!HasUniqueTargetType)
6926 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6927 ViableConversions);
6928
6929 // If one unique T is found:
6930 // First, build a candidate set from the previously recorded
6931 // potentially viable conversions.
6933 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6934 CandidateSet);
6935
6936 // Then, perform overload resolution over the candidate set.
6938 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6939 case OR_Success: {
6940 // Apply this conversion.
6942 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6943 if (recordConversion(*this, Loc, From, Converter, T,
6944 HadMultipleCandidates, Found))
6945 return ExprError();
6946 break;
6947 }
6948 case OR_Ambiguous:
6949 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6950 ViableConversions);
6952 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6953 HadMultipleCandidates,
6954 ExplicitConversions))
6955 return ExprError();
6956 [[fallthrough]];
6957 case OR_Deleted:
6958 // We'll complain below about a non-integral condition type.
6959 break;
6960 }
6961 } else {
6962 switch (ViableConversions.size()) {
6963 case 0: {
6964 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6965 HadMultipleCandidates,
6966 ExplicitConversions))
6967 return ExprError();
6968
6969 // We'll complain below about a non-integral condition type.
6970 break;
6971 }
6972 case 1: {
6973 // Apply this conversion.
6974 DeclAccessPair Found = ViableConversions[0];
6975 if (recordConversion(*this, Loc, From, Converter, T,
6976 HadMultipleCandidates, Found))
6977 return ExprError();
6978 break;
6979 }
6980 default:
6981 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6982 ViableConversions);
6983 }
6984 }
6985
6986 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6987}
6988
6989/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6990/// an acceptable non-member overloaded operator for a call whose
6991/// arguments have types T1 (and, if non-empty, T2). This routine
6992/// implements the check in C++ [over.match.oper]p3b2 concerning
6993/// enumeration types.
6995 FunctionDecl *Fn,
6996 ArrayRef<Expr *> Args) {
6997 QualType T1 = Args[0]->getType();
6998 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6999
7000 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7001 return true;
7002
7003 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7004 return true;
7005
7006 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7007 if (Proto->getNumParams() < 1)
7008 return false;
7009
7010 if (T1->isEnumeralType()) {
7011 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7012 if (Context.hasSameUnqualifiedType(T1, ArgType))
7013 return true;
7014 }
7015
7016 if (Proto->getNumParams() < 2)
7017 return false;
7018
7019 if (!T2.isNull() && T2->isEnumeralType()) {
7020 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7021 if (Context.hasSameUnqualifiedType(T2, ArgType))
7022 return true;
7023 }
7024
7025 return false;
7026}
7027
7030 return false;
7031
7032 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7033 return FD->isTargetMultiVersion();
7034
7035 if (!FD->isMultiVersion())
7036 return false;
7037
7038 // Among multiple target versions consider either the default,
7039 // or the first non-default in the absence of default version.
7040 unsigned SeenAt = 0;
7041 unsigned I = 0;
7042 bool HasDefault = false;
7044 FD, [&](const FunctionDecl *CurFD) {
7045 if (FD == CurFD)
7046 SeenAt = I;
7047 else if (CurFD->isTargetMultiVersionDefault())
7048 HasDefault = true;
7049 ++I;
7050 });
7051 return HasDefault || SeenAt != 0;
7052}
7053
7056 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7057 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7058 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7059 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7060 bool StrictPackMatch) {
7061 const FunctionProtoType *Proto
7062 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7063 assert(Proto && "Functions without a prototype cannot be overloaded");
7064 assert(!Function->getDescribedFunctionTemplate() &&
7065 "Use AddTemplateOverloadCandidate for function templates");
7066
7067 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7069 // If we get here, it's because we're calling a member function
7070 // that is named without a member access expression (e.g.,
7071 // "this->f") that was either written explicitly or created
7072 // implicitly. This can happen with a qualified call to a member
7073 // function, e.g., X::f(). We use an empty type for the implied
7074 // object argument (C++ [over.call.func]p3), and the acting context
7075 // is irrelevant.
7076 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7078 CandidateSet, SuppressUserConversions,
7079 PartialOverloading, EarlyConversions, PO,
7080 StrictPackMatch);
7081 return;
7082 }
7083 // We treat a constructor like a non-member function, since its object
7084 // argument doesn't participate in overload resolution.
7085 }
7086
7087 if (!CandidateSet.isNewCandidate(Function, PO))
7088 return;
7089
7090 // C++11 [class.copy]p11: [DR1402]
7091 // A defaulted move constructor that is defined as deleted is ignored by
7092 // overload resolution.
7093 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7094 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7095 Constructor->isMoveConstructor())
7096 return;
7097
7098 // Overload resolution is always an unevaluated context.
7101
7102 // C++ [over.match.oper]p3:
7103 // if no operand has a class type, only those non-member functions in the
7104 // lookup set that have a first parameter of type T1 or "reference to
7105 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7106 // is a right operand) a second parameter of type T2 or "reference to
7107 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7108 // candidate functions.
7109 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7111 return;
7112
7113 // Add this candidate
7114 OverloadCandidate &Candidate =
7115 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7116 Candidate.FoundDecl = FoundDecl;
7117 Candidate.Function = Function;
7118 Candidate.Viable = true;
7119 Candidate.RewriteKind =
7120 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7121 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7122 Candidate.ExplicitCallArguments = Args.size();
7123 Candidate.StrictPackMatch = StrictPackMatch;
7124
7125 // Explicit functions are not actually candidates at all if we're not
7126 // allowing them in this context, but keep them around so we can point
7127 // to them in diagnostics.
7128 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7129 Candidate.Viable = false;
7130 Candidate.FailureKind = ovl_fail_explicit;
7131 return;
7132 }
7133
7134 // Functions with internal linkage are only viable in the same module unit.
7135 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7136 /// FIXME: Currently, the semantics of linkage in clang is slightly
7137 /// different from the semantics in C++ spec. In C++ spec, only names
7138 /// have linkage. So that all entities of the same should share one
7139 /// linkage. But in clang, different entities of the same could have
7140 /// different linkage.
7141 const NamedDecl *ND = Function;
7142 bool IsImplicitlyInstantiated = false;
7143 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7144 ND = SpecInfo->getTemplate();
7145 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7147 }
7148
7149 /// Don't remove inline functions with internal linkage from the overload
7150 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7151 /// However:
7152 /// - Inline functions with internal linkage are a common pattern in
7153 /// headers to avoid ODR issues.
7154 /// - The global module is meant to be a transition mechanism for C and C++
7155 /// headers, and the current rules as written work against that goal.
7156 const bool IsInlineFunctionInGMF =
7157 Function->isFromGlobalModule() &&
7158 (IsImplicitlyInstantiated || Function->isInlined());
7159
7160 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7161 Candidate.Viable = false;
7163 return;
7164 }
7165 }
7166
7168 Candidate.Viable = false;
7170 return;
7171 }
7172
7173 if (Constructor) {
7174 // C++ [class.copy]p3:
7175 // A member function template is never instantiated to perform the copy
7176 // of a class object to an object of its class type.
7177 CanQualType ClassType =
7178 Context.getCanonicalTagType(Constructor->getParent());
7179 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7180 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7181 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7182 ClassType))) {
7183 Candidate.Viable = false;
7185 return;
7186 }
7187
7188 // C++ [over.match.funcs]p8: (proposed DR resolution)
7189 // A constructor inherited from class type C that has a first parameter
7190 // of type "reference to P" (including such a constructor instantiated
7191 // from a template) is excluded from the set of candidate functions when
7192 // constructing an object of type cv D if the argument list has exactly
7193 // one argument and D is reference-related to P and P is reference-related
7194 // to C.
7195 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7196 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7197 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7198 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7199 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7200 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7201 SourceLocation Loc = Args.front()->getExprLoc();
7202 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7203 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7204 Candidate.Viable = false;
7206 return;
7207 }
7208 }
7209
7210 // Check that the constructor is capable of constructing an object in the
7211 // destination address space.
7213 Constructor->getMethodQualifiers().getAddressSpace(),
7214 CandidateSet.getDestAS(), getASTContext())) {
7215 Candidate.Viable = false;
7217 }
7218 }
7219
7220 unsigned NumParams = Proto->getNumParams();
7221
7222 // (C++ 13.3.2p2): A candidate function having fewer than m
7223 // parameters is viable only if it has an ellipsis in its parameter
7224 // list (8.3.5).
7225 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7226 !Proto->isVariadic() &&
7227 shouldEnforceArgLimit(PartialOverloading, Function)) {
7228 Candidate.Viable = false;
7230 return;
7231 }
7232
7233 // (C++ 13.3.2p2): A candidate function having more than m parameters
7234 // is viable only if the (m+1)st parameter has a default argument
7235 // (8.3.6). For the purposes of overload resolution, the
7236 // parameter list is truncated on the right, so that there are
7237 // exactly m parameters.
7238 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7239 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7240 !PartialOverloading) {
7241 // Not enough arguments.
7242 Candidate.Viable = false;
7244 return;
7245 }
7246
7247 // (CUDA B.1): Check for invalid calls between targets.
7248 if (getLangOpts().CUDA) {
7249 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7250 // Skip the check for callers that are implicit members, because in this
7251 // case we may not yet know what the member's target is; the target is
7252 // inferred for the member automatically, based on the bases and fields of
7253 // the class.
7254 if (!(Caller && Caller->isImplicit()) &&
7255 !CUDA().IsAllowedCall(Caller, Function)) {
7256 Candidate.Viable = false;
7257 Candidate.FailureKind = ovl_fail_bad_target;
7258 return;
7259 }
7260 }
7261
7262 if (Function->getTrailingRequiresClause()) {
7263 ConstraintSatisfaction Satisfaction;
7264 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7265 /*ForOverloadResolution*/ true) ||
7266 !Satisfaction.IsSatisfied) {
7267 Candidate.Viable = false;
7269 return;
7270 }
7271 }
7272
7273 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7274 // Determine the implicit conversion sequences for each of the
7275 // arguments.
7276 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7277 unsigned ConvIdx =
7278 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7279 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7280 // We already formed a conversion sequence for this parameter during
7281 // template argument deduction.
7282 } else if (ArgIdx < NumParams) {
7283 // (C++ 13.3.2p3): for F to be a viable function, there shall
7284 // exist for each argument an implicit conversion sequence
7285 // (13.3.3.1) that converts that argument to the corresponding
7286 // parameter of F.
7287 QualType ParamType = Proto->getParamType(ArgIdx);
7288 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7289 if (ParamABI == ParameterABI::HLSLOut ||
7290 ParamABI == ParameterABI::HLSLInOut)
7291 ParamType = ParamType.getNonReferenceType();
7292 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7293 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7294 /*InOverloadResolution=*/true,
7295 /*AllowObjCWritebackConversion=*/
7296 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7297 if (Candidate.Conversions[ConvIdx].isBad()) {
7298 Candidate.Viable = false;
7300 return;
7301 }
7302 } else {
7303 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7304 // argument for which there is no corresponding parameter is
7305 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7306 Candidate.Conversions[ConvIdx].setEllipsis();
7307 }
7308 }
7309
7310 if (EnableIfAttr *FailedAttr =
7311 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7312 Candidate.Viable = false;
7313 Candidate.FailureKind = ovl_fail_enable_if;
7314 Candidate.DeductionFailure.Data = FailedAttr;
7315 return;
7316 }
7317}
7318
7322 if (Methods.size() <= 1)
7323 return nullptr;
7324
7325 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7326 bool Match = true;
7327 ObjCMethodDecl *Method = Methods[b];
7328 unsigned NumNamedArgs = Sel.getNumArgs();
7329 // Method might have more arguments than selector indicates. This is due
7330 // to addition of c-style arguments in method.
7331 if (Method->param_size() > NumNamedArgs)
7332 NumNamedArgs = Method->param_size();
7333 if (Args.size() < NumNamedArgs)
7334 continue;
7335
7336 for (unsigned i = 0; i < NumNamedArgs; i++) {
7337 // We can't do any type-checking on a type-dependent argument.
7338 if (Args[i]->isTypeDependent()) {
7339 Match = false;
7340 break;
7341 }
7342
7343 ParmVarDecl *param = Method->parameters()[i];
7344 Expr *argExpr = Args[i];
7345 assert(argExpr && "SelectBestMethod(): missing expression");
7346
7347 // Strip the unbridged-cast placeholder expression off unless it's
7348 // a consumed argument.
7349 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7350 !param->hasAttr<CFConsumedAttr>())
7351 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7352
7353 // If the parameter is __unknown_anytype, move on to the next method.
7354 if (param->getType() == Context.UnknownAnyTy) {
7355 Match = false;
7356 break;
7357 }
7358
7359 ImplicitConversionSequence ConversionState
7360 = TryCopyInitialization(*this, argExpr, param->getType(),
7361 /*SuppressUserConversions*/false,
7362 /*InOverloadResolution=*/true,
7363 /*AllowObjCWritebackConversion=*/
7364 getLangOpts().ObjCAutoRefCount,
7365 /*AllowExplicit*/false);
7366 // This function looks for a reasonably-exact match, so we consider
7367 // incompatible pointer conversions to be a failure here.
7368 if (ConversionState.isBad() ||
7369 (ConversionState.isStandard() &&
7370 ConversionState.Standard.Second ==
7372 Match = false;
7373 break;
7374 }
7375 }
7376 // Promote additional arguments to variadic methods.
7377 if (Match && Method->isVariadic()) {
7378 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7379 if (Args[i]->isTypeDependent()) {
7380 Match = false;
7381 break;
7382 }
7384 Args[i], VariadicCallType::Method, nullptr);
7385 if (Arg.isInvalid()) {
7386 Match = false;
7387 break;
7388 }
7389 }
7390 } else {
7391 // Check for extra arguments to non-variadic methods.
7392 if (Args.size() != NumNamedArgs)
7393 Match = false;
7394 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7395 // Special case when selectors have no argument. In this case, select
7396 // one with the most general result type of 'id'.
7397 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7398 QualType ReturnT = Methods[b]->getReturnType();
7399 if (ReturnT->isObjCIdType())
7400 return Methods[b];
7401 }
7402 }
7403 }
7404
7405 if (Match)
7406 return Method;
7407 }
7408 return nullptr;
7409}
7410
7412 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7413 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7414 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7415 if (ThisArg) {
7416 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7417 assert(!isa<CXXConstructorDecl>(Method) &&
7418 "Shouldn't have `this` for ctors!");
7419 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7421 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7422 if (R.isInvalid())
7423 return false;
7424 ConvertedThis = R.get();
7425 } else {
7426 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7427 (void)MD;
7428 assert((MissingImplicitThis || MD->isStatic() ||
7430 "Expected `this` for non-ctor instance methods");
7431 }
7432 ConvertedThis = nullptr;
7433 }
7434
7435 // Ignore any variadic arguments. Converting them is pointless, since the
7436 // user can't refer to them in the function condition.
7437 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7438
7439 // Convert the arguments.
7440 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7441 ExprResult R;
7443 S.Context, Function->getParamDecl(I)),
7444 SourceLocation(), Args[I]);
7445
7446 if (R.isInvalid())
7447 return false;
7448
7449 ConvertedArgs.push_back(R.get());
7450 }
7451
7452 if (Trap.hasErrorOccurred())
7453 return false;
7454
7455 // Push default arguments if needed.
7456 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7457 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7458 ParmVarDecl *P = Function->getParamDecl(i);
7459 if (!P->hasDefaultArg())
7460 return false;
7461 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7462 if (R.isInvalid())
7463 return false;
7464 ConvertedArgs.push_back(R.get());
7465 }
7466
7467 if (Trap.hasErrorOccurred())
7468 return false;
7469 }
7470 return true;
7471}
7472
7474 SourceLocation CallLoc,
7475 ArrayRef<Expr *> Args,
7476 bool MissingImplicitThis) {
7477 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7478 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7479 return nullptr;
7480
7481 SFINAETrap Trap(*this);
7482 SmallVector<Expr *, 16> ConvertedArgs;
7483 // FIXME: We should look into making enable_if late-parsed.
7484 Expr *DiscardedThis;
7486 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7487 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7488 return *EnableIfAttrs.begin();
7489
7490 for (auto *EIA : EnableIfAttrs) {
7492 // FIXME: This doesn't consider value-dependent cases, because doing so is
7493 // very difficult. Ideally, we should handle them more gracefully.
7494 if (EIA->getCond()->isValueDependent() ||
7495 !EIA->getCond()->EvaluateWithSubstitution(
7496 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7497 return EIA;
7498
7499 if (!Result.isInt() || !Result.getInt().getBoolValue())
7500 return EIA;
7501 }
7502 return nullptr;
7503}
7504
7505template <typename CheckFn>
7507 bool ArgDependent, SourceLocation Loc,
7508 CheckFn &&IsSuccessful) {
7510 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7511 if (ArgDependent == DIA->getArgDependent())
7512 Attrs.push_back(DIA);
7513 }
7514
7515 // Common case: No diagnose_if attributes, so we can quit early.
7516 if (Attrs.empty())
7517 return false;
7518
7519 auto WarningBegin = std::stable_partition(
7520 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7521 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7522 DIA->getWarningGroup().empty();
7523 });
7524
7525 // Note that diagnose_if attributes are late-parsed, so they appear in the
7526 // correct order (unlike enable_if attributes).
7527 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7528 IsSuccessful);
7529 if (ErrAttr != WarningBegin) {
7530 const DiagnoseIfAttr *DIA = *ErrAttr;
7531 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7532 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7533 << DIA->getParent() << DIA->getCond()->getSourceRange();
7534 return true;
7535 }
7536
7537 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7538 switch (Sev) {
7539 case DiagnoseIfAttr::DS_warning:
7541 case DiagnoseIfAttr::DS_error:
7542 return diag::Severity::Error;
7543 }
7544 llvm_unreachable("Fully covered switch above!");
7545 };
7546
7547 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7548 if (IsSuccessful(DIA)) {
7549 if (DIA->getWarningGroup().empty() &&
7550 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7551 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7552 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7553 << DIA->getParent() << DIA->getCond()->getSourceRange();
7554 } else {
7555 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7556 DIA->getWarningGroup());
7557 assert(DiagGroup);
7558 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7559 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7560 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7561 S.Diag(Loc, DiagID) << DIA->getMessage();
7562 }
7563 }
7564
7565 return false;
7566}
7567
7569 const Expr *ThisArg,
7571 SourceLocation Loc) {
7573 *this, Function, /*ArgDependent=*/true, Loc,
7574 [&](const DiagnoseIfAttr *DIA) {
7576 // It's sane to use the same Args for any redecl of this function, since
7577 // EvaluateWithSubstitution only cares about the position of each
7578 // argument in the arg list, not the ParmVarDecl* it maps to.
7579 if (!DIA->getCond()->EvaluateWithSubstitution(
7580 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7581 return false;
7582 return Result.isInt() && Result.getInt().getBoolValue();
7583 });
7584}
7585
7587 SourceLocation Loc) {
7589 *this, ND, /*ArgDependent=*/false, Loc,
7590 [&](const DiagnoseIfAttr *DIA) {
7591 bool Result;
7592 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7593 Result;
7594 });
7595}
7596
7598 ArrayRef<Expr *> Args,
7599 OverloadCandidateSet &CandidateSet,
7600 TemplateArgumentListInfo *ExplicitTemplateArgs,
7601 bool SuppressUserConversions,
7602 bool PartialOverloading,
7603 bool FirstArgumentIsBase) {
7604 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7605 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7606 ArrayRef<Expr *> FunctionArgs = Args;
7607
7608 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7609 FunctionDecl *FD =
7610 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7611
7612 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7613 QualType ObjectType;
7614 Expr::Classification ObjectClassification;
7615 if (Args.size() > 0) {
7616 if (Expr *E = Args[0]) {
7617 // Use the explicit base to restrict the lookup:
7618 ObjectType = E->getType();
7619 // Pointers in the object arguments are implicitly dereferenced, so we
7620 // always classify them as l-values.
7621 if (!ObjectType.isNull() && ObjectType->isPointerType())
7622 ObjectClassification = Expr::Classification::makeSimpleLValue();
7623 else
7624 ObjectClassification = E->Classify(Context);
7625 } // .. else there is an implicit base.
7626 FunctionArgs = Args.slice(1);
7627 }
7628 if (FunTmpl) {
7630 FunTmpl, F.getPair(),
7632 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7633 FunctionArgs, CandidateSet, SuppressUserConversions,
7634 PartialOverloading);
7635 } else {
7636 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7637 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7638 ObjectClassification, FunctionArgs, CandidateSet,
7639 SuppressUserConversions, PartialOverloading);
7640 }
7641 } else {
7642 // This branch handles both standalone functions and static methods.
7643
7644 // Slice the first argument (which is the base) when we access
7645 // static method as non-static.
7646 if (Args.size() > 0 &&
7647 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7648 !isa<CXXConstructorDecl>(FD)))) {
7649 assert(cast<CXXMethodDecl>(FD)->isStatic());
7650 FunctionArgs = Args.slice(1);
7651 }
7652 if (FunTmpl) {
7653 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7654 ExplicitTemplateArgs, FunctionArgs,
7655 CandidateSet, SuppressUserConversions,
7656 PartialOverloading);
7657 } else {
7658 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7659 SuppressUserConversions, PartialOverloading);
7660 }
7661 }
7662 }
7663}
7664
7666 Expr::Classification ObjectClassification,
7667 ArrayRef<Expr *> Args,
7668 OverloadCandidateSet &CandidateSet,
7669 bool SuppressUserConversions,
7671 NamedDecl *Decl = FoundDecl.getDecl();
7673
7675 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7676
7677 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7678 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7679 "Expected a member function template");
7680 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7681 /*ExplicitArgs*/ nullptr, ObjectType,
7682 ObjectClassification, Args, CandidateSet,
7683 SuppressUserConversions, false, PO);
7684 } else {
7685 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7686 ObjectType, ObjectClassification, Args, CandidateSet,
7687 SuppressUserConversions, false, {}, PO);
7688 }
7689}
7690
7693 CXXRecordDecl *ActingContext, QualType ObjectType,
7694 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7695 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7696 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7697 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7698 const FunctionProtoType *Proto
7699 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7700 assert(Proto && "Methods without a prototype cannot be overloaded");
7702 "Use AddOverloadCandidate for constructors");
7703
7704 if (!CandidateSet.isNewCandidate(Method, PO))
7705 return;
7706
7707 // C++11 [class.copy]p23: [DR1402]
7708 // A defaulted move assignment operator that is defined as deleted is
7709 // ignored by overload resolution.
7710 if (Method->isDefaulted() && Method->isDeleted() &&
7711 Method->isMoveAssignmentOperator())
7712 return;
7713
7714 // Overload resolution is always an unevaluated context.
7717
7718 bool IgnoreExplicitObject =
7719 (Method->isExplicitObjectMemberFunction() &&
7720 CandidateSet.getKind() ==
7722 bool ImplicitObjectMethodTreatedAsStatic =
7723 CandidateSet.getKind() ==
7725 Method->isImplicitObjectMemberFunction();
7726
7727 unsigned ExplicitOffset =
7728 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7729
7730 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7731 int(ImplicitObjectMethodTreatedAsStatic);
7732
7733 unsigned ExtraArgs =
7735 ? 0
7736 : 1;
7737
7738 // Add this candidate
7739 OverloadCandidate &Candidate =
7740 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7741 Candidate.FoundDecl = FoundDecl;
7742 Candidate.Function = Method;
7743 Candidate.RewriteKind =
7744 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7745 Candidate.TookAddressOfOverload =
7747 Candidate.ExplicitCallArguments = Args.size();
7748 Candidate.StrictPackMatch = StrictPackMatch;
7749
7750 // (C++ 13.3.2p2): A candidate function having fewer than m
7751 // parameters is viable only if it has an ellipsis in its parameter
7752 // list (8.3.5).
7753 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7754 !Proto->isVariadic() &&
7755 shouldEnforceArgLimit(PartialOverloading, Method)) {
7756 Candidate.Viable = false;
7758 return;
7759 }
7760
7761 // (C++ 13.3.2p2): A candidate function having more than m parameters
7762 // is viable only if the (m+1)st parameter has a default argument
7763 // (8.3.6). For the purposes of overload resolution, the
7764 // parameter list is truncated on the right, so that there are
7765 // exactly m parameters.
7766 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7767 ExplicitOffset +
7768 int(ImplicitObjectMethodTreatedAsStatic);
7769
7770 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7771 // Not enough arguments.
7772 Candidate.Viable = false;
7774 return;
7775 }
7776
7777 Candidate.Viable = true;
7778
7779 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7780 if (!IgnoreExplicitObject) {
7781 if (ObjectType.isNull())
7782 Candidate.IgnoreObjectArgument = true;
7783 else if (Method->isStatic()) {
7784 // [over.best.ics.general]p8
7785 // When the parameter is the implicit object parameter of a static member
7786 // function, the implicit conversion sequence is a standard conversion
7787 // sequence that is neither better nor worse than any other standard
7788 // conversion sequence.
7789 //
7790 // This is a rule that was introduced in C++23 to support static lambdas.
7791 // We apply it retroactively because we want to support static lambdas as
7792 // an extension and it doesn't hurt previous code.
7793 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7794 } else {
7795 // Determine the implicit conversion sequence for the object
7796 // parameter.
7797 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7798 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7799 Method, ActingContext, /*InOverloadResolution=*/true);
7800 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7801 Candidate.Viable = false;
7803 return;
7804 }
7805 }
7806 }
7807
7808 // (CUDA B.1): Check for invalid calls between targets.
7809 if (getLangOpts().CUDA)
7810 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7811 Method)) {
7812 Candidate.Viable = false;
7813 Candidate.FailureKind = ovl_fail_bad_target;
7814 return;
7815 }
7816
7817 if (Method->getTrailingRequiresClause()) {
7818 ConstraintSatisfaction Satisfaction;
7819 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7820 /*ForOverloadResolution*/ true) ||
7821 !Satisfaction.IsSatisfied) {
7822 Candidate.Viable = false;
7824 return;
7825 }
7826 }
7827
7828 // Determine the implicit conversion sequences for each of the
7829 // arguments.
7830 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7831 unsigned ConvIdx =
7832 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7833 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7834 // We already formed a conversion sequence for this parameter during
7835 // template argument deduction.
7836 } else if (ArgIdx < NumParams) {
7837 // (C++ 13.3.2p3): for F to be a viable function, there shall
7838 // exist for each argument an implicit conversion sequence
7839 // (13.3.3.1) that converts that argument to the corresponding
7840 // parameter of F.
7841 QualType ParamType;
7842 if (ImplicitObjectMethodTreatedAsStatic) {
7843 ParamType = ArgIdx == 0
7844 ? Method->getFunctionObjectParameterReferenceType()
7845 : Proto->getParamType(ArgIdx - 1);
7846 } else {
7847 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7848 }
7849 Candidate.Conversions[ConvIdx]
7850 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7851 SuppressUserConversions,
7852 /*InOverloadResolution=*/true,
7853 /*AllowObjCWritebackConversion=*/
7854 getLangOpts().ObjCAutoRefCount);
7855 if (Candidate.Conversions[ConvIdx].isBad()) {
7856 Candidate.Viable = false;
7858 return;
7859 }
7860 } else {
7861 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7862 // argument for which there is no corresponding parameter is
7863 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7864 Candidate.Conversions[ConvIdx].setEllipsis();
7865 }
7866 }
7867
7868 if (EnableIfAttr *FailedAttr =
7869 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7870 Candidate.Viable = false;
7871 Candidate.FailureKind = ovl_fail_enable_if;
7872 Candidate.DeductionFailure.Data = FailedAttr;
7873 return;
7874 }
7875
7877 Candidate.Viable = false;
7879 }
7880}
7881
7883 Sema &S, OverloadCandidateSet &CandidateSet,
7884 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7885 CXXRecordDecl *ActingContext,
7886 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7887 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7888 bool SuppressUserConversions, bool PartialOverloading,
7890
7891 // C++ [over.match.funcs]p7:
7892 // In each case where a candidate is a function template, candidate
7893 // function template specializations are generated using template argument
7894 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7895 // candidate functions in the usual way.113) A given name can refer to one
7896 // or more function templates and also to a set of overloaded non-template
7897 // functions. In such a case, the candidate functions generated from each
7898 // function template are combined with the set of non-template candidate
7899 // functions.
7900 TemplateDeductionInfo Info(CandidateSet.getLocation());
7901 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7902 FunctionDecl *Specialization = nullptr;
7903 ConversionSequenceList Conversions;
7905 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7906 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7907 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7908 CandidateSet.getKind() ==
7910 [&](ArrayRef<QualType> ParamTypes,
7911 bool OnlyInitializeNonUserDefinedConversions) {
7912 return S.CheckNonDependentConversions(
7913 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7914 Sema::CheckNonDependentConversionsFlag(
7915 SuppressUserConversions,
7916 OnlyInitializeNonUserDefinedConversions),
7917 ActingContext, ObjectType, ObjectClassification, PO);
7918 });
7920 OverloadCandidate &Candidate =
7921 CandidateSet.addCandidate(Conversions.size(), Conversions);
7922 Candidate.FoundDecl = FoundDecl;
7923 Candidate.Function = Method;
7924 Candidate.Viable = false;
7925 Candidate.RewriteKind =
7926 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7927 Candidate.IsSurrogate = false;
7928 Candidate.TookAddressOfOverload =
7929 CandidateSet.getKind() ==
7931
7932 Candidate.IgnoreObjectArgument =
7933 Method->isStatic() ||
7934 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7935 Candidate.ExplicitCallArguments = Args.size();
7938 else {
7940 Candidate.DeductionFailure =
7941 MakeDeductionFailureInfo(S.Context, Result, Info);
7942 }
7943 return;
7944 }
7945
7946 // Add the function template specialization produced by template argument
7947 // deduction as a candidate.
7948 assert(Specialization && "Missing member function template specialization?");
7950 "Specialization is not a member function?");
7952 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7953 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7954 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7955}
7956
7958 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7959 CXXRecordDecl *ActingContext,
7960 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7961 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7962 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7963 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7964 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7965 return;
7966
7967 if (ExplicitTemplateArgs ||
7970 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7971 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7972 SuppressUserConversions, PartialOverloading, PO);
7973 return;
7974 }
7975
7977 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7978 Args, SuppressUserConversions, PartialOverloading, PO);
7979}
7980
7981/// Determine whether a given function template has a simple explicit specifier
7982/// or a non-value-dependent explicit-specification that evaluates to true.
7986
7991
7993 Sema &S, OverloadCandidateSet &CandidateSet,
7995 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7996 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7998 bool AggregateCandidateDeduction) {
7999
8000 // If the function template has a non-dependent explicit specification,
8001 // exclude it now if appropriate; we are not permitted to perform deduction
8002 // and substitution in this case.
8003 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8004 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8005 Candidate.FoundDecl = FoundDecl;
8006 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8007 Candidate.Viable = false;
8008 Candidate.FailureKind = ovl_fail_explicit;
8009 return;
8010 }
8011
8012 // C++ [over.match.funcs]p7:
8013 // In each case where a candidate is a function template, candidate
8014 // function template specializations are generated using template argument
8015 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8016 // candidate functions in the usual way.113) A given name can refer to one
8017 // or more function templates and also to a set of overloaded non-template
8018 // functions. In such a case, the candidate functions generated from each
8019 // function template are combined with the set of non-template candidate
8020 // functions.
8021 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8022 FunctionTemplate->getTemplateDepth());
8023 FunctionDecl *Specialization = nullptr;
8024 ConversionSequenceList Conversions;
8026 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8027 PartialOverloading, AggregateCandidateDeduction,
8028 /*PartialOrdering=*/false,
8029 /*ObjectType=*/QualType(),
8030 /*ObjectClassification=*/Expr::Classification(),
8031 CandidateSet.getKind() ==
8033 [&](ArrayRef<QualType> ParamTypes,
8034 bool OnlyInitializeNonUserDefinedConversions) {
8035 return S.CheckNonDependentConversions(
8036 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8037 Sema::CheckNonDependentConversionsFlag(
8038 SuppressUserConversions,
8039 OnlyInitializeNonUserDefinedConversions),
8040 nullptr, QualType(), {}, PO);
8041 });
8043 OverloadCandidate &Candidate =
8044 CandidateSet.addCandidate(Conversions.size(), Conversions);
8045 Candidate.FoundDecl = FoundDecl;
8046 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8047 Candidate.Viable = false;
8048 Candidate.RewriteKind =
8049 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8050 Candidate.IsSurrogate = false;
8051 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8052 // Ignore the object argument if there is one, since we don't have an object
8053 // type.
8054 Candidate.TookAddressOfOverload =
8055 CandidateSet.getKind() ==
8057
8058 Candidate.IgnoreObjectArgument =
8059 isa<CXXMethodDecl>(Candidate.Function) &&
8060 !cast<CXXMethodDecl>(Candidate.Function)
8061 ->isExplicitObjectMemberFunction() &&
8063
8064 Candidate.ExplicitCallArguments = Args.size();
8067 else {
8069 Candidate.DeductionFailure =
8071 }
8072 return;
8073 }
8074
8075 // Add the function template specialization produced by template argument
8076 // deduction as a candidate.
8077 assert(Specialization && "Missing function template specialization?");
8079 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8080 PartialOverloading, AllowExplicit,
8081 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8082 Info.AggregateDeductionCandidateHasMismatchedArity,
8083 Info.hasStrictPackMatch());
8084}
8085
8088 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8089 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8090 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8091 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8092 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8093 return;
8094
8095 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8096
8097 if (ExplicitTemplateArgs ||
8099 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8100 DependentExplicitSpecifier)) {
8101
8103 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8104 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8105 IsADLCandidate, PO, AggregateCandidateDeduction);
8106
8107 if (DependentExplicitSpecifier)
8109 return;
8110 }
8111
8112 CandidateSet.AddDeferredTemplateCandidate(
8113 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8114 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8115 AggregateCandidateDeduction);
8116}
8117
8120 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8122 CheckNonDependentConversionsFlag UserConversionFlag,
8123 CXXRecordDecl *ActingContext, QualType ObjectType,
8124 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8125 // FIXME: The cases in which we allow explicit conversions for constructor
8126 // arguments never consider calling a constructor template. It's not clear
8127 // that is correct.
8128 const bool AllowExplicit = false;
8129
8130 bool ForOverloadSetAddressResolution =
8132 auto *FD = FunctionTemplate->getTemplatedDecl();
8133 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8134 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8136 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8137
8138 if (Conversions.empty())
8139 Conversions =
8140 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8141
8142 // Overload resolution is always an unevaluated context.
8145
8146 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8147 // require that, but this check should never result in a hard error, and
8148 // overload resolution is permitted to sidestep instantiations.
8149 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8150 !ObjectType.isNull()) {
8151 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8152 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8153 !ParamTypes[0]->isDependentType()) {
8155 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8156 Method, ActingContext, /*InOverloadResolution=*/true,
8157 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8158 : QualType());
8159 if (Conversions[ConvIdx].isBad())
8160 return true;
8161 }
8162 }
8163
8164 // A speculative workaround for self-dependent constraint bugs that manifest
8165 // after CWG2369.
8166 // FIXME: Add references to the standard once P3606 is adopted.
8167 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8168 QualType ArgType) {
8169 ParamType = ParamType.getNonReferenceType();
8170 ArgType = ArgType.getNonReferenceType();
8171 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8172 if (PointerConv) {
8173 ParamType = ParamType->getPointeeType();
8174 ArgType = ArgType->getPointeeType();
8175 }
8176
8177 if (auto *RD = ParamType->getAsCXXRecordDecl();
8178 RD && RD->hasDefinition() &&
8179 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8180 auto Info = getConstructorInfo(ND);
8181 if (!Info)
8182 return false;
8183 CXXConstructorDecl *Ctor = Info.Constructor;
8184 /// isConvertingConstructor takes copy/move constructors into
8185 /// account!
8186 return !Ctor->isCopyOrMoveConstructor() &&
8188 /*AllowExplicit=*/true);
8189 }))
8190 return true;
8191 if (auto *RD = ArgType->getAsCXXRecordDecl();
8192 RD && RD->hasDefinition() &&
8193 !RD->getVisibleConversionFunctions().empty())
8194 return true;
8195
8196 return false;
8197 };
8198
8199 unsigned Offset =
8200 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8201 : 0;
8202
8203 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8204 I != N; ++I) {
8205 QualType ParamType = ParamTypes[I + Offset];
8206 if (!ParamType->isDependentType()) {
8207 unsigned ConvIdx;
8209 ConvIdx = Args.size() - 1 - I;
8210 assert(Args.size() + ThisConversions == 2 &&
8211 "number of args (including 'this') must be exactly 2 for "
8212 "reversed order");
8213 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8214 // would also be 0. 'this' got ConvIdx = 1 previously.
8215 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8216 } else {
8217 // For members, 'this' got ConvIdx = 0 previously.
8218 ConvIdx = ThisConversions + I;
8219 }
8220 if (Conversions[ConvIdx].isInitialized())
8221 continue;
8222 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8223 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8224 continue;
8226 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8227 /*InOverloadResolution=*/true,
8228 /*AllowObjCWritebackConversion=*/
8229 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8230 if (Conversions[ConvIdx].isBad())
8231 return true;
8232 }
8233 }
8234
8235 return false;
8236}
8237
8238/// Determine whether this is an allowable conversion from the result
8239/// of an explicit conversion operator to the expected type, per C++
8240/// [over.match.conv]p1 and [over.match.ref]p1.
8241///
8242/// \param ConvType The return type of the conversion function.
8243///
8244/// \param ToType The type we are converting to.
8245///
8246/// \param AllowObjCPointerConversion Allow a conversion from one
8247/// Objective-C pointer to another.
8248///
8249/// \returns true if the conversion is allowable, false otherwise.
8251 QualType ConvType, QualType ToType,
8252 bool AllowObjCPointerConversion) {
8253 QualType ToNonRefType = ToType.getNonReferenceType();
8254
8255 // Easy case: the types are the same.
8256 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8257 return true;
8258
8259 // Allow qualification conversions.
8260 bool ObjCLifetimeConversion;
8261 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8262 ObjCLifetimeConversion))
8263 return true;
8264
8265 // If we're not allowed to consider Objective-C pointer conversions,
8266 // we're done.
8267 if (!AllowObjCPointerConversion)
8268 return false;
8269
8270 // Is this an Objective-C pointer conversion?
8271 bool IncompatibleObjC = false;
8272 QualType ConvertedType;
8273 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8274 IncompatibleObjC);
8275}
8276
8278 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8279 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8280 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8281 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8282 assert(!Conversion->getDescribedFunctionTemplate() &&
8283 "Conversion function templates use AddTemplateConversionCandidate");
8284 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8285 if (!CandidateSet.isNewCandidate(Conversion))
8286 return;
8287
8288 // If the conversion function has an undeduced return type, trigger its
8289 // deduction now.
8290 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8291 if (DeduceReturnType(Conversion, From->getExprLoc()))
8292 return;
8293 ConvType = Conversion->getConversionType().getNonReferenceType();
8294 }
8295
8296 // If we don't allow any conversion of the result type, ignore conversion
8297 // functions that don't convert to exactly (possibly cv-qualified) T.
8298 if (!AllowResultConversion &&
8299 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8300 return;
8301
8302 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8303 // operator is only a candidate if its return type is the target type or
8304 // can be converted to the target type with a qualification conversion.
8305 //
8306 // FIXME: Include such functions in the candidate list and explain why we
8307 // can't select them.
8308 if (Conversion->isExplicit() &&
8309 !isAllowableExplicitConversion(*this, ConvType, ToType,
8310 AllowObjCConversionOnExplicit))
8311 return;
8312
8313 // Overload resolution is always an unevaluated context.
8316
8317 // Add this candidate
8318 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8319 Candidate.FoundDecl = FoundDecl;
8320 Candidate.Function = Conversion;
8322 Candidate.FinalConversion.setFromType(ConvType);
8323 Candidate.FinalConversion.setAllToTypes(ToType);
8324 Candidate.HasFinalConversion = true;
8325 Candidate.Viable = true;
8326 Candidate.ExplicitCallArguments = 1;
8327 Candidate.StrictPackMatch = StrictPackMatch;
8328
8329 // Explicit functions are not actually candidates at all if we're not
8330 // allowing them in this context, but keep them around so we can point
8331 // to them in diagnostics.
8332 if (!AllowExplicit && Conversion->isExplicit()) {
8333 Candidate.Viable = false;
8334 Candidate.FailureKind = ovl_fail_explicit;
8335 return;
8336 }
8337
8338 // C++ [over.match.funcs]p4:
8339 // For conversion functions, the function is considered to be a member of
8340 // the class of the implicit implied object argument for the purpose of
8341 // defining the type of the implicit object parameter.
8342 //
8343 // Determine the implicit conversion sequence for the implicit
8344 // object parameter.
8345 QualType ObjectType = From->getType();
8346 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8347 ObjectType = FromPtrType->getPointeeType();
8348 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8349 // C++23 [over.best.ics.general]
8350 // However, if the target is [...]
8351 // - the object parameter of a user-defined conversion function
8352 // [...] user-defined conversion sequences are not considered.
8354 *this, CandidateSet.getLocation(), From->getType(),
8355 From->Classify(Context), Conversion, ConversionContext,
8356 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8357 /*SuppressUserConversion*/ true);
8358
8359 if (Candidate.Conversions[0].isBad()) {
8360 Candidate.Viable = false;
8362 return;
8363 }
8364
8365 if (Conversion->getTrailingRequiresClause()) {
8366 ConstraintSatisfaction Satisfaction;
8367 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8368 !Satisfaction.IsSatisfied) {
8369 Candidate.Viable = false;
8371 return;
8372 }
8373 }
8374
8375 // We won't go through a user-defined type conversion function to convert a
8376 // derived to base as such conversions are given Conversion Rank. They only
8377 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8378 QualType FromCanon
8379 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8380 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8381 if (FromCanon == ToCanon ||
8382 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8383 Candidate.Viable = false;
8385 return;
8386 }
8387
8388 // To determine what the conversion from the result of calling the
8389 // conversion function to the type we're eventually trying to
8390 // convert to (ToType), we need to synthesize a call to the
8391 // conversion function and attempt copy initialization from it. This
8392 // makes sure that we get the right semantics with respect to
8393 // lvalues/rvalues and the type. Fortunately, we can allocate this
8394 // call on the stack and we don't need its arguments to be
8395 // well-formed.
8396 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8397 VK_LValue, From->getBeginLoc());
8399 Context.getPointerType(Conversion->getType()),
8400 CK_FunctionToPointerDecay, &ConversionRef,
8402
8403 QualType ConversionType = Conversion->getConversionType();
8404 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8405 Candidate.Viable = false;
8407 return;
8408 }
8409
8410 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8411
8412 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8413
8414 // Introduce a temporary expression with the right type and value category
8415 // that we can use for deduction purposes.
8416 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8417
8419 TryCopyInitialization(*this, &FakeCall, ToType,
8420 /*SuppressUserConversions=*/true,
8421 /*InOverloadResolution=*/false,
8422 /*AllowObjCWritebackConversion=*/false);
8423
8424 switch (ICS.getKind()) {
8426 Candidate.FinalConversion = ICS.Standard;
8427 Candidate.HasFinalConversion = true;
8428
8429 // C++ [over.ics.user]p3:
8430 // If the user-defined conversion is specified by a specialization of a
8431 // conversion function template, the second standard conversion sequence
8432 // shall have exact match rank.
8433 if (Conversion->getPrimaryTemplate() &&
8435 Candidate.Viable = false;
8437 return;
8438 }
8439
8440 // C++0x [dcl.init.ref]p5:
8441 // In the second case, if the reference is an rvalue reference and
8442 // the second standard conversion sequence of the user-defined
8443 // conversion sequence includes an lvalue-to-rvalue conversion, the
8444 // program is ill-formed.
8445 if (ToType->isRValueReferenceType() &&
8447 Candidate.Viable = false;
8449 return;
8450 }
8451 break;
8452
8454 Candidate.Viable = false;
8456 return;
8457
8458 default:
8459 llvm_unreachable(
8460 "Can only end up with a standard conversion sequence or failure");
8461 }
8462
8463 if (EnableIfAttr *FailedAttr =
8464 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8465 Candidate.Viable = false;
8466 Candidate.FailureKind = ovl_fail_enable_if;
8467 Candidate.DeductionFailure.Data = FailedAttr;
8468 return;
8469 }
8470
8471 if (isNonViableMultiVersionOverload(Conversion)) {
8472 Candidate.Viable = false;
8474 }
8475}
8476
8478 Sema &S, OverloadCandidateSet &CandidateSet,
8480 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8481 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8482 bool AllowResultConversion) {
8483
8484 // If the function template has a non-dependent explicit specification,
8485 // exclude it now if appropriate; we are not permitted to perform deduction
8486 // and substitution in this case.
8487 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8488 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8489 Candidate.FoundDecl = FoundDecl;
8490 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8491 Candidate.Viable = false;
8492 Candidate.FailureKind = ovl_fail_explicit;
8493 return;
8494 }
8495
8496 QualType ObjectType = From->getType();
8497 Expr::Classification ObjectClassification = From->Classify(S.Context);
8498
8499 TemplateDeductionInfo Info(CandidateSet.getLocation());
8502 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8503 Specialization, Info);
8505 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8506 Candidate.FoundDecl = FoundDecl;
8507 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8508 Candidate.Viable = false;
8510 Candidate.ExplicitCallArguments = 1;
8511 Candidate.DeductionFailure =
8512 MakeDeductionFailureInfo(S.Context, Result, Info);
8513 return;
8514 }
8515
8516 // Add the conversion function template specialization produced by
8517 // template argument deduction as a candidate.
8518 assert(Specialization && "Missing function template specialization?");
8519 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8520 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8521 AllowExplicit, AllowResultConversion,
8522 Info.hasStrictPackMatch());
8523}
8524
8527 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8528 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8529 bool AllowExplicit, bool AllowResultConversion) {
8530 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8531 "Only conversion function templates permitted here");
8532
8533 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8534 return;
8535
8537 CandidateSet.getKind() ==
8541 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8542 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8543 AllowResultConversion);
8544
8546 return;
8547 }
8548
8550 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8551 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8552}
8553
8555 DeclAccessPair FoundDecl,
8556 CXXRecordDecl *ActingContext,
8557 const FunctionProtoType *Proto,
8558 Expr *Object,
8559 ArrayRef<Expr *> Args,
8560 OverloadCandidateSet& CandidateSet) {
8561 if (!CandidateSet.isNewCandidate(Conversion))
8562 return;
8563
8564 // Overload resolution is always an unevaluated context.
8567
8568 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8569 Candidate.FoundDecl = FoundDecl;
8570 Candidate.Function = nullptr;
8571 Candidate.Surrogate = Conversion;
8572 Candidate.IsSurrogate = true;
8573 Candidate.Viable = true;
8574 Candidate.ExplicitCallArguments = Args.size();
8575
8576 // Determine the implicit conversion sequence for the implicit
8577 // object parameter.
8578 ImplicitConversionSequence ObjectInit;
8579 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8580 ObjectInit = TryCopyInitialization(*this, Object,
8581 Conversion->getParamDecl(0)->getType(),
8582 /*SuppressUserConversions=*/false,
8583 /*InOverloadResolution=*/true, false);
8584 } else {
8586 *this, CandidateSet.getLocation(), Object->getType(),
8587 Object->Classify(Context), Conversion, ActingContext);
8588 }
8589
8590 if (ObjectInit.isBad()) {
8591 Candidate.Viable = false;
8593 Candidate.Conversions[0] = ObjectInit;
8594 return;
8595 }
8596
8597 // The first conversion is actually a user-defined conversion whose
8598 // first conversion is ObjectInit's standard conversion (which is
8599 // effectively a reference binding). Record it as such.
8600 Candidate.Conversions[0].setUserDefined();
8601 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8602 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8603 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8604 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8605 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8606 Candidate.Conversions[0].UserDefined.After
8607 = Candidate.Conversions[0].UserDefined.Before;
8608 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8609
8610 // Find the
8611 unsigned NumParams = Proto->getNumParams();
8612
8613 // (C++ 13.3.2p2): A candidate function having fewer than m
8614 // parameters is viable only if it has an ellipsis in its parameter
8615 // list (8.3.5).
8616 if (Args.size() > NumParams && !Proto->isVariadic()) {
8617 Candidate.Viable = false;
8619 return;
8620 }
8621
8622 // Function types don't have any default arguments, so just check if
8623 // we have enough arguments.
8624 if (Args.size() < NumParams) {
8625 // Not enough arguments.
8626 Candidate.Viable = false;
8628 return;
8629 }
8630
8631 // Determine the implicit conversion sequences for each of the
8632 // arguments.
8633 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8634 if (ArgIdx < NumParams) {
8635 // (C++ 13.3.2p3): for F to be a viable function, there shall
8636 // exist for each argument an implicit conversion sequence
8637 // (13.3.3.1) that converts that argument to the corresponding
8638 // parameter of F.
8639 QualType ParamType = Proto->getParamType(ArgIdx);
8640 Candidate.Conversions[ArgIdx + 1]
8641 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8642 /*SuppressUserConversions=*/false,
8643 /*InOverloadResolution=*/false,
8644 /*AllowObjCWritebackConversion=*/
8645 getLangOpts().ObjCAutoRefCount);
8646 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8647 Candidate.Viable = false;
8649 return;
8650 }
8651 } else {
8652 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8653 // argument for which there is no corresponding parameter is
8654 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8655 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8656 }
8657 }
8658
8659 if (Conversion->getTrailingRequiresClause()) {
8660 ConstraintSatisfaction Satisfaction;
8661 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8662 /*ForOverloadResolution*/ true) ||
8663 !Satisfaction.IsSatisfied) {
8664 Candidate.Viable = false;
8666 return;
8667 }
8668 }
8669
8670 if (EnableIfAttr *FailedAttr =
8671 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8672 Candidate.Viable = false;
8673 Candidate.FailureKind = ovl_fail_enable_if;
8674 Candidate.DeductionFailure.Data = FailedAttr;
8675 return;
8676 }
8677}
8678
8680 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8681 OverloadCandidateSet &CandidateSet,
8682 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8683 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8684 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8685 ArrayRef<Expr *> FunctionArgs = Args;
8686
8687 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8688 FunctionDecl *FD =
8689 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8690
8691 // Don't consider rewritten functions if we're not rewriting.
8692 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8693 continue;
8694
8695 assert(!isa<CXXMethodDecl>(FD) &&
8696 "unqualified operator lookup found a member function");
8697
8698 if (FunTmpl) {
8699 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8700 FunctionArgs, CandidateSet);
8701 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8702
8703 // As template candidates are not deduced immediately,
8704 // persist the array in the overload set.
8706 FunctionArgs[1], FunctionArgs[0]);
8707 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8708 Reversed, CandidateSet, false, false, true,
8709 ADLCallKind::NotADL,
8711 }
8712 } else {
8713 if (ExplicitTemplateArgs)
8714 continue;
8715 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8716 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8717 AddOverloadCandidate(FD, F.getPair(),
8718 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8719 false, false, true, false, ADLCallKind::NotADL, {},
8721 }
8722 }
8723}
8724
8726 SourceLocation OpLoc,
8727 ArrayRef<Expr *> Args,
8728 OverloadCandidateSet &CandidateSet,
8730 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8731
8732 // C++ [over.match.oper]p3:
8733 // For a unary operator @ with an operand of a type whose
8734 // cv-unqualified version is T1, and for a binary operator @ with
8735 // a left operand of a type whose cv-unqualified version is T1 and
8736 // a right operand of a type whose cv-unqualified version is T2,
8737 // three sets of candidate functions, designated member
8738 // candidates, non-member candidates and built-in candidates, are
8739 // constructed as follows:
8740 QualType T1 = Args[0]->getType();
8741
8742 // -- If T1 is a complete class type or a class currently being
8743 // defined, the set of member candidates is the result of the
8744 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8745 // the set of member candidates is empty.
8746 if (T1->isRecordType()) {
8747 bool IsComplete = isCompleteType(OpLoc, T1);
8748 auto *T1RD = T1->getAsCXXRecordDecl();
8749 // Complete the type if it can be completed.
8750 // If the type is neither complete nor being defined, bail out now.
8751 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8752 return;
8753
8754 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8755 LookupQualifiedName(Operators, T1RD);
8756 Operators.suppressAccessDiagnostics();
8757
8758 for (LookupResult::iterator Oper = Operators.begin(),
8759 OperEnd = Operators.end();
8760 Oper != OperEnd; ++Oper) {
8761 if (Oper->getAsFunction() &&
8763 !CandidateSet.getRewriteInfo().shouldAddReversed(
8764 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8765 continue;
8766 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8767 Args[0]->Classify(Context), Args.slice(1),
8768 CandidateSet, /*SuppressUserConversion=*/false, PO);
8769 }
8770 }
8771}
8772
8774 OverloadCandidateSet& CandidateSet,
8775 bool IsAssignmentOperator,
8776 unsigned NumContextualBoolArguments) {
8777 // Overload resolution is always an unevaluated context.
8780
8781 // Add this candidate
8782 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8783 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8784 Candidate.Function = nullptr;
8785 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8786
8787 // Determine the implicit conversion sequences for each of the
8788 // arguments.
8789 Candidate.Viable = true;
8790 Candidate.ExplicitCallArguments = Args.size();
8791 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8792 // C++ [over.match.oper]p4:
8793 // For the built-in assignment operators, conversions of the
8794 // left operand are restricted as follows:
8795 // -- no temporaries are introduced to hold the left operand, and
8796 // -- no user-defined conversions are applied to the left
8797 // operand to achieve a type match with the left-most
8798 // parameter of a built-in candidate.
8799 //
8800 // We block these conversions by turning off user-defined
8801 // conversions, since that is the only way that initialization of
8802 // a reference to a non-class type can occur from something that
8803 // is not of the same type.
8804 if (ArgIdx < NumContextualBoolArguments) {
8805 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8806 "Contextual conversion to bool requires bool type");
8807 Candidate.Conversions[ArgIdx]
8808 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8809 } else {
8810 Candidate.Conversions[ArgIdx]
8811 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8812 ArgIdx == 0 && IsAssignmentOperator,
8813 /*InOverloadResolution=*/false,
8814 /*AllowObjCWritebackConversion=*/
8815 getLangOpts().ObjCAutoRefCount);
8816 }
8817 if (Candidate.Conversions[ArgIdx].isBad()) {
8818 Candidate.Viable = false;
8820 break;
8821 }
8822 }
8823}
8824
8825namespace {
8826
8827/// BuiltinCandidateTypeSet - A set of types that will be used for the
8828/// candidate operator functions for built-in operators (C++
8829/// [over.built]). The types are separated into pointer types and
8830/// enumeration types.
8831class BuiltinCandidateTypeSet {
8832 /// TypeSet - A set of types.
8833 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8834
8835 /// PointerTypes - The set of pointer types that will be used in the
8836 /// built-in candidates.
8837 TypeSet PointerTypes;
8838
8839 /// MemberPointerTypes - The set of member pointer types that will be
8840 /// used in the built-in candidates.
8841 TypeSet MemberPointerTypes;
8842
8843 /// EnumerationTypes - The set of enumeration types that will be
8844 /// used in the built-in candidates.
8845 TypeSet EnumerationTypes;
8846
8847 /// The set of vector types that will be used in the built-in
8848 /// candidates.
8849 TypeSet VectorTypes;
8850
8851 /// The set of matrix types that will be used in the built-in
8852 /// candidates.
8853 TypeSet MatrixTypes;
8854
8855 /// The set of _BitInt types that will be used in the built-in candidates.
8856 TypeSet BitIntTypes;
8857
8858 /// A flag indicating non-record types are viable candidates
8859 bool HasNonRecordTypes;
8860
8861 /// A flag indicating whether either arithmetic or enumeration types
8862 /// were present in the candidate set.
8863 bool HasArithmeticOrEnumeralTypes;
8864
8865 /// A flag indicating whether the nullptr type was present in the
8866 /// candidate set.
8867 bool HasNullPtrType;
8868
8869 /// Sema - The semantic analysis instance where we are building the
8870 /// candidate type set.
8871 Sema &SemaRef;
8872
8873 /// Context - The AST context in which we will build the type sets.
8874 ASTContext &Context;
8875
8876 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8877 const Qualifiers &VisibleQuals);
8878 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8879
8880public:
8881 /// iterator - Iterates through the types that are part of the set.
8882 typedef TypeSet::iterator iterator;
8883
8884 BuiltinCandidateTypeSet(Sema &SemaRef)
8885 : HasNonRecordTypes(false),
8886 HasArithmeticOrEnumeralTypes(false),
8887 HasNullPtrType(false),
8888 SemaRef(SemaRef),
8889 Context(SemaRef.Context) { }
8890
8891 void AddTypesConvertedFrom(QualType Ty,
8892 SourceLocation Loc,
8893 bool AllowUserConversions,
8894 bool AllowExplicitConversions,
8895 const Qualifiers &VisibleTypeConversionsQuals);
8896
8897 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8898 llvm::iterator_range<iterator> member_pointer_types() {
8899 return MemberPointerTypes;
8900 }
8901 llvm::iterator_range<iterator> enumeration_types() {
8902 return EnumerationTypes;
8903 }
8904 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8905 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8906 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8907
8908 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8909 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8910 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8911 bool hasNullPtrType() const { return HasNullPtrType; }
8912};
8913
8914} // end anonymous namespace
8915
8916/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8917/// the set of pointer types along with any more-qualified variants of
8918/// that type. For example, if @p Ty is "int const *", this routine
8919/// will add "int const *", "int const volatile *", "int const
8920/// restrict *", and "int const volatile restrict *" to the set of
8921/// pointer types. Returns true if the add of @p Ty itself succeeded,
8922/// false otherwise.
8923///
8924/// FIXME: what to do about extended qualifiers?
8925bool
8926BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8927 const Qualifiers &VisibleQuals) {
8928
8929 // Insert this type.
8930 if (!PointerTypes.insert(Ty))
8931 return false;
8932
8933 QualType PointeeTy;
8934 const PointerType *PointerTy = Ty->getAs<PointerType>();
8935 bool buildObjCPtr = false;
8936 if (!PointerTy) {
8937 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8938 PointeeTy = PTy->getPointeeType();
8939 buildObjCPtr = true;
8940 } else {
8941 PointeeTy = PointerTy->getPointeeType();
8942 }
8943
8944 // Don't add qualified variants of arrays. For one, they're not allowed
8945 // (the qualifier would sink to the element type), and for another, the
8946 // only overload situation where it matters is subscript or pointer +- int,
8947 // and those shouldn't have qualifier variants anyway.
8948 if (PointeeTy->isArrayType())
8949 return true;
8950
8951 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8952 bool hasVolatile = VisibleQuals.hasVolatile();
8953 bool hasRestrict = VisibleQuals.hasRestrict();
8954
8955 // Iterate through all strict supersets of BaseCVR.
8956 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8957 if ((CVR | BaseCVR) != CVR) continue;
8958 // Skip over volatile if no volatile found anywhere in the types.
8959 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8960
8961 // Skip over restrict if no restrict found anywhere in the types, or if
8962 // the type cannot be restrict-qualified.
8963 if ((CVR & Qualifiers::Restrict) &&
8964 (!hasRestrict ||
8965 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8966 continue;
8967
8968 // Build qualified pointee type.
8969 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8970
8971 // Build qualified pointer type.
8972 QualType QPointerTy;
8973 if (!buildObjCPtr)
8974 QPointerTy = Context.getPointerType(QPointeeTy);
8975 else
8976 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8977
8978 // Insert qualified pointer type.
8979 PointerTypes.insert(QPointerTy);
8980 }
8981
8982 return true;
8983}
8984
8985/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8986/// to the set of pointer types along with any more-qualified variants of
8987/// that type. For example, if @p Ty is "int const *", this routine
8988/// will add "int const *", "int const volatile *", "int const
8989/// restrict *", and "int const volatile restrict *" to the set of
8990/// pointer types. Returns true if the add of @p Ty itself succeeded,
8991/// false otherwise.
8992///
8993/// FIXME: what to do about extended qualifiers?
8994bool
8995BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8996 QualType Ty) {
8997 // Insert this type.
8998 if (!MemberPointerTypes.insert(Ty))
8999 return false;
9000
9001 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9002 assert(PointerTy && "type was not a member pointer type!");
9003
9004 QualType PointeeTy = PointerTy->getPointeeType();
9005 // Don't add qualified variants of arrays. For one, they're not allowed
9006 // (the qualifier would sink to the element type), and for another, the
9007 // only overload situation where it matters is subscript or pointer +- int,
9008 // and those shouldn't have qualifier variants anyway.
9009 if (PointeeTy->isArrayType())
9010 return true;
9011 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9012
9013 // Iterate through all strict supersets of the pointee type's CVR
9014 // qualifiers.
9015 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9016 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9017 if ((CVR | BaseCVR) != CVR) continue;
9018
9019 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9020 MemberPointerTypes.insert(Context.getMemberPointerType(
9021 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9022 }
9023
9024 return true;
9025}
9026
9027/// AddTypesConvertedFrom - Add each of the types to which the type @p
9028/// Ty can be implicit converted to the given set of @p Types. We're
9029/// primarily interested in pointer types and enumeration types. We also
9030/// take member pointer types, for the conditional operator.
9031/// AllowUserConversions is true if we should look at the conversion
9032/// functions of a class type, and AllowExplicitConversions if we
9033/// should also include the explicit conversion functions of a class
9034/// type.
9035void
9036BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9037 SourceLocation Loc,
9038 bool AllowUserConversions,
9039 bool AllowExplicitConversions,
9040 const Qualifiers &VisibleQuals) {
9041 // Only deal with canonical types.
9042 Ty = Context.getCanonicalType(Ty);
9043
9044 // Look through reference types; they aren't part of the type of an
9045 // expression for the purposes of conversions.
9046 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9047 Ty = RefTy->getPointeeType();
9048
9049 // If we're dealing with an array type, decay to the pointer.
9050 if (Ty->isArrayType())
9051 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9052
9053 // Otherwise, we don't care about qualifiers on the type.
9054 Ty = Ty.getLocalUnqualifiedType();
9055
9056 // Flag if we ever add a non-record type.
9057 bool TyIsRec = Ty->isRecordType();
9058 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9059
9060 // Flag if we encounter an arithmetic type.
9061 HasArithmeticOrEnumeralTypes =
9062 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9063
9064 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9065 PointerTypes.insert(Ty);
9066 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9067 // Insert our type, and its more-qualified variants, into the set
9068 // of types.
9069 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9070 return;
9071 } else if (Ty->isMemberPointerType()) {
9072 // Member pointers are far easier, since the pointee can't be converted.
9073 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9074 return;
9075 } else if (Ty->isEnumeralType()) {
9076 HasArithmeticOrEnumeralTypes = true;
9077 EnumerationTypes.insert(Ty);
9078 } else if (Ty->isBitIntType()) {
9079 HasArithmeticOrEnumeralTypes = true;
9080 BitIntTypes.insert(Ty);
9081 } else if (Ty->isVectorType()) {
9082 // We treat vector types as arithmetic types in many contexts as an
9083 // extension.
9084 HasArithmeticOrEnumeralTypes = true;
9085 VectorTypes.insert(Ty);
9086 } else if (Ty->isMatrixType()) {
9087 // Similar to vector types, we treat vector types as arithmetic types in
9088 // many contexts as an extension.
9089 HasArithmeticOrEnumeralTypes = true;
9090 MatrixTypes.insert(Ty);
9091 } else if (Ty->isNullPtrType()) {
9092 HasNullPtrType = true;
9093 } else if (AllowUserConversions && TyIsRec) {
9094 // No conversion functions in incomplete types.
9095 if (!SemaRef.isCompleteType(Loc, Ty))
9096 return;
9097
9098 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9099 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9100 if (isa<UsingShadowDecl>(D))
9101 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9102
9103 // Skip conversion function templates; they don't tell us anything
9104 // about which builtin types we can convert to.
9106 continue;
9107
9108 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9109 if (AllowExplicitConversions || !Conv->isExplicit()) {
9110 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9111 VisibleQuals);
9112 }
9113 }
9114 }
9115}
9116/// Helper function for adjusting address spaces for the pointer or reference
9117/// operands of builtin operators depending on the argument.
9122
9123/// Helper function for AddBuiltinOperatorCandidates() that adds
9124/// the volatile- and non-volatile-qualified assignment operators for the
9125/// given type to the candidate set.
9127 QualType T,
9128 ArrayRef<Expr *> Args,
9129 OverloadCandidateSet &CandidateSet) {
9130 QualType ParamTypes[2];
9131
9132 // T& operator=(T&, T)
9133 ParamTypes[0] = S.Context.getLValueReferenceType(
9135 ParamTypes[1] = T;
9136 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9137 /*IsAssignmentOperator=*/true);
9138
9140 // volatile T& operator=(volatile T&, T)
9141 ParamTypes[0] = S.Context.getLValueReferenceType(
9143 Args[0]));
9144 ParamTypes[1] = T;
9145 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9146 /*IsAssignmentOperator=*/true);
9147 }
9148}
9149
9150/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9151/// if any, found in visible type conversion functions found in ArgExpr's type.
9152static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9153 Qualifiers VRQuals;
9154 CXXRecordDecl *ClassDecl;
9155 if (const MemberPointerType *RHSMPType =
9156 ArgExpr->getType()->getAs<MemberPointerType>())
9157 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9158 else
9159 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9160 if (!ClassDecl) {
9161 // Just to be safe, assume the worst case.
9162 VRQuals.addVolatile();
9163 VRQuals.addRestrict();
9164 return VRQuals;
9165 }
9166 if (!ClassDecl->hasDefinition())
9167 return VRQuals;
9168
9169 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9170 if (isa<UsingShadowDecl>(D))
9171 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9172 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9173 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9174 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9175 CanTy = ResTypeRef->getPointeeType();
9176 // Need to go down the pointer/mempointer chain and add qualifiers
9177 // as see them.
9178 bool done = false;
9179 while (!done) {
9180 if (CanTy.isRestrictQualified())
9181 VRQuals.addRestrict();
9182 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9183 CanTy = ResTypePtr->getPointeeType();
9184 else if (const MemberPointerType *ResTypeMPtr =
9185 CanTy->getAs<MemberPointerType>())
9186 CanTy = ResTypeMPtr->getPointeeType();
9187 else
9188 done = true;
9189 if (CanTy.isVolatileQualified())
9190 VRQuals.addVolatile();
9191 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9192 return VRQuals;
9193 }
9194 }
9195 }
9196 return VRQuals;
9197}
9198
9199// Note: We're currently only handling qualifiers that are meaningful for the
9200// LHS of compound assignment overloading.
9202 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9203 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9204 // _Atomic
9205 if (Available.hasAtomic()) {
9206 Available.removeAtomic();
9207 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9208 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9209 return;
9210 }
9211
9212 // volatile
9213 if (Available.hasVolatile()) {
9214 Available.removeVolatile();
9215 assert(!Applied.hasVolatile());
9216 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9217 Callback);
9218 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9219 return;
9220 }
9221
9222 Callback(Applied);
9223}
9224
9226 QualifiersAndAtomic Quals,
9227 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9229 Callback);
9230}
9231
9233 QualifiersAndAtomic Quals,
9234 Sema &S) {
9235 if (Quals.hasAtomic())
9237 if (Quals.hasVolatile())
9240}
9241
9242namespace {
9243
9244/// Helper class to manage the addition of builtin operator overload
9245/// candidates. It provides shared state and utility methods used throughout
9246/// the process, as well as a helper method to add each group of builtin
9247/// operator overloads from the standard to a candidate set.
9248class BuiltinOperatorOverloadBuilder {
9249 // Common instance state available to all overload candidate addition methods.
9250 Sema &S;
9251 ArrayRef<Expr *> Args;
9252 QualifiersAndAtomic VisibleTypeConversionsQuals;
9253 bool HasArithmeticOrEnumeralCandidateType;
9254 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9255 OverloadCandidateSet &CandidateSet;
9256
9257 static constexpr int ArithmeticTypesCap = 26;
9258 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9259
9260 // Define some indices used to iterate over the arithmetic types in
9261 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9262 // types are that preserved by promotion (C++ [over.built]p2).
9263 unsigned FirstIntegralType,
9264 LastIntegralType;
9265 unsigned FirstPromotedIntegralType,
9266 LastPromotedIntegralType;
9267 unsigned FirstPromotedArithmeticType,
9268 LastPromotedArithmeticType;
9269 unsigned NumArithmeticTypes;
9270
9271 void InitArithmeticTypes() {
9272 // Start of promoted types.
9273 FirstPromotedArithmeticType = 0;
9274 ArithmeticTypes.push_back(S.Context.FloatTy);
9275 ArithmeticTypes.push_back(S.Context.DoubleTy);
9276 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9278 ArithmeticTypes.push_back(S.Context.Float128Ty);
9280 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9281
9282 // Start of integral types.
9283 FirstIntegralType = ArithmeticTypes.size();
9284 FirstPromotedIntegralType = ArithmeticTypes.size();
9285 ArithmeticTypes.push_back(S.Context.IntTy);
9286 ArithmeticTypes.push_back(S.Context.LongTy);
9287 ArithmeticTypes.push_back(S.Context.LongLongTy);
9291 ArithmeticTypes.push_back(S.Context.Int128Ty);
9292 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9293 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9294 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9298 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9299
9300 /// We add candidates for the unique, unqualified _BitInt types present in
9301 /// the candidate type set. The candidate set already handled ensuring the
9302 /// type is unqualified and canonical, but because we're adding from N
9303 /// different sets, we need to do some extra work to unique things. Insert
9304 /// the candidates into a unique set, then move from that set into the list
9305 /// of arithmetic types.
9306 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9307 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9308 for (QualType BitTy : Candidate.bitint_types())
9309 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9310 }
9311 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9312 LastPromotedIntegralType = ArithmeticTypes.size();
9313 LastPromotedArithmeticType = ArithmeticTypes.size();
9314 // End of promoted types.
9315
9316 ArithmeticTypes.push_back(S.Context.BoolTy);
9317 ArithmeticTypes.push_back(S.Context.CharTy);
9318 ArithmeticTypes.push_back(S.Context.WCharTy);
9319 if (S.Context.getLangOpts().Char8)
9320 ArithmeticTypes.push_back(S.Context.Char8Ty);
9321 ArithmeticTypes.push_back(S.Context.Char16Ty);
9322 ArithmeticTypes.push_back(S.Context.Char32Ty);
9323 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9324 ArithmeticTypes.push_back(S.Context.ShortTy);
9325 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9326 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9327 LastIntegralType = ArithmeticTypes.size();
9328 NumArithmeticTypes = ArithmeticTypes.size();
9329 // End of integral types.
9330 // FIXME: What about complex? What about half?
9331
9332 // We don't know for sure how many bit-precise candidates were involved, so
9333 // we subtract those from the total when testing whether we're under the
9334 // cap or not.
9335 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9336 ArithmeticTypesCap &&
9337 "Enough inline storage for all arithmetic types.");
9338 }
9339
9340 /// Helper method to factor out the common pattern of adding overloads
9341 /// for '++' and '--' builtin operators.
9342 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9343 bool HasVolatile,
9344 bool HasRestrict) {
9345 QualType ParamTypes[2] = {
9346 S.Context.getLValueReferenceType(CandidateTy),
9347 S.Context.IntTy
9348 };
9349
9350 // Non-volatile version.
9351 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9352
9353 // Use a heuristic to reduce number of builtin candidates in the set:
9354 // add volatile version only if there are conversions to a volatile type.
9355 if (HasVolatile) {
9356 ParamTypes[0] =
9358 S.Context.getVolatileType(CandidateTy));
9359 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9360 }
9361
9362 // Add restrict version only if there are conversions to a restrict type
9363 // and our candidate type is a non-restrict-qualified pointer.
9364 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9365 !CandidateTy.isRestrictQualified()) {
9366 ParamTypes[0]
9369 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9370
9371 if (HasVolatile) {
9372 ParamTypes[0]
9374 S.Context.getCVRQualifiedType(CandidateTy,
9377 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9378 }
9379 }
9380
9381 }
9382
9383 /// Helper to add an overload candidate for a binary builtin with types \p L
9384 /// and \p R.
9385 void AddCandidate(QualType L, QualType R) {
9386 QualType LandR[2] = {L, R};
9387 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9388 }
9389
9390public:
9391 BuiltinOperatorOverloadBuilder(
9392 Sema &S, ArrayRef<Expr *> Args,
9393 QualifiersAndAtomic VisibleTypeConversionsQuals,
9394 bool HasArithmeticOrEnumeralCandidateType,
9395 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9396 OverloadCandidateSet &CandidateSet)
9397 : S(S), Args(Args),
9398 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9399 HasArithmeticOrEnumeralCandidateType(
9400 HasArithmeticOrEnumeralCandidateType),
9401 CandidateTypes(CandidateTypes),
9402 CandidateSet(CandidateSet) {
9403
9404 InitArithmeticTypes();
9405 }
9406
9407 // Increment is deprecated for bool since C++17.
9408 //
9409 // C++ [over.built]p3:
9410 //
9411 // For every pair (T, VQ), where T is an arithmetic type other
9412 // than bool, and VQ is either volatile or empty, there exist
9413 // candidate operator functions of the form
9414 //
9415 // VQ T& operator++(VQ T&);
9416 // T operator++(VQ T&, int);
9417 //
9418 // C++ [over.built]p4:
9419 //
9420 // For every pair (T, VQ), where T is an arithmetic type other
9421 // than bool, and VQ is either volatile or empty, there exist
9422 // candidate operator functions of the form
9423 //
9424 // VQ T& operator--(VQ T&);
9425 // T operator--(VQ T&, int);
9426 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9427 if (!HasArithmeticOrEnumeralCandidateType)
9428 return;
9429
9430 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9431 const auto TypeOfT = ArithmeticTypes[Arith];
9432 if (TypeOfT == S.Context.BoolTy) {
9433 if (Op == OO_MinusMinus)
9434 continue;
9435 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9436 continue;
9437 }
9438 addPlusPlusMinusMinusStyleOverloads(
9439 TypeOfT,
9440 VisibleTypeConversionsQuals.hasVolatile(),
9441 VisibleTypeConversionsQuals.hasRestrict());
9442 }
9443 }
9444
9445 // C++ [over.built]p5:
9446 //
9447 // For every pair (T, VQ), where T is a cv-qualified or
9448 // cv-unqualified object type, and VQ is either volatile or
9449 // empty, there exist candidate operator functions of the form
9450 //
9451 // T*VQ& operator++(T*VQ&);
9452 // T*VQ& operator--(T*VQ&);
9453 // T* operator++(T*VQ&, int);
9454 // T* operator--(T*VQ&, int);
9455 void addPlusPlusMinusMinusPointerOverloads() {
9456 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9457 // Skip pointer types that aren't pointers to object types.
9458 if (!PtrTy->getPointeeType()->isObjectType())
9459 continue;
9460
9461 addPlusPlusMinusMinusStyleOverloads(
9462 PtrTy,
9463 (!PtrTy.isVolatileQualified() &&
9464 VisibleTypeConversionsQuals.hasVolatile()),
9465 (!PtrTy.isRestrictQualified() &&
9466 VisibleTypeConversionsQuals.hasRestrict()));
9467 }
9468 }
9469
9470 // C++ [over.built]p6:
9471 // For every cv-qualified or cv-unqualified object type T, there
9472 // exist candidate operator functions of the form
9473 //
9474 // T& operator*(T*);
9475 //
9476 // C++ [over.built]p7:
9477 // For every function type T that does not have cv-qualifiers or a
9478 // ref-qualifier, there exist candidate operator functions of the form
9479 // T& operator*(T*);
9480 void addUnaryStarPointerOverloads() {
9481 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9482 QualType PointeeTy = ParamTy->getPointeeType();
9483 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9484 continue;
9485
9486 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9487 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9488 continue;
9489
9490 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9491 }
9492 }
9493
9494 // C++ [over.built]p9:
9495 // For every promoted arithmetic type T, there exist candidate
9496 // operator functions of the form
9497 //
9498 // T operator+(T);
9499 // T operator-(T);
9500 void addUnaryPlusOrMinusArithmeticOverloads() {
9501 if (!HasArithmeticOrEnumeralCandidateType)
9502 return;
9503
9504 for (unsigned Arith = FirstPromotedArithmeticType;
9505 Arith < LastPromotedArithmeticType; ++Arith) {
9506 QualType ArithTy = ArithmeticTypes[Arith];
9507 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9508 }
9509
9510 // Extension: We also add these operators for vector types.
9511 for (QualType VecTy : CandidateTypes[0].vector_types())
9512 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9513 }
9514
9515 // C++ [over.built]p8:
9516 // For every type T, there exist candidate operator functions of
9517 // the form
9518 //
9519 // T* operator+(T*);
9520 void addUnaryPlusPointerOverloads() {
9521 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9522 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9523 }
9524
9525 // C++ [over.built]p10:
9526 // For every promoted integral type T, there exist candidate
9527 // operator functions of the form
9528 //
9529 // T operator~(T);
9530 void addUnaryTildePromotedIntegralOverloads() {
9531 if (!HasArithmeticOrEnumeralCandidateType)
9532 return;
9533
9534 for (unsigned Int = FirstPromotedIntegralType;
9535 Int < LastPromotedIntegralType; ++Int) {
9536 QualType IntTy = ArithmeticTypes[Int];
9537 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9538 }
9539
9540 // Extension: We also add this operator for vector types.
9541 for (QualType VecTy : CandidateTypes[0].vector_types())
9542 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9543 }
9544
9545 // C++ [over.match.oper]p16:
9546 // For every pointer to member type T or type std::nullptr_t, there
9547 // exist candidate operator functions of the form
9548 //
9549 // bool operator==(T,T);
9550 // bool operator!=(T,T);
9551 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9552 /// Set of (canonical) types that we've already handled.
9553 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9554
9555 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9556 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9557 // Don't add the same builtin candidate twice.
9558 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9559 continue;
9560
9561 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9562 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9563 }
9564
9565 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9567 if (AddedTypes.insert(NullPtrTy).second) {
9568 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9569 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9570 }
9571 }
9572 }
9573 }
9574
9575 // C++ [over.built]p15:
9576 //
9577 // For every T, where T is an enumeration type or a pointer type,
9578 // there exist candidate operator functions of the form
9579 //
9580 // bool operator<(T, T);
9581 // bool operator>(T, T);
9582 // bool operator<=(T, T);
9583 // bool operator>=(T, T);
9584 // bool operator==(T, T);
9585 // bool operator!=(T, T);
9586 // R operator<=>(T, T)
9587 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9588 // C++ [over.match.oper]p3:
9589 // [...]the built-in candidates include all of the candidate operator
9590 // functions defined in 13.6 that, compared to the given operator, [...]
9591 // do not have the same parameter-type-list as any non-template non-member
9592 // candidate.
9593 //
9594 // Note that in practice, this only affects enumeration types because there
9595 // aren't any built-in candidates of record type, and a user-defined operator
9596 // must have an operand of record or enumeration type. Also, the only other
9597 // overloaded operator with enumeration arguments, operator=,
9598 // cannot be overloaded for enumeration types, so this is the only place
9599 // where we must suppress candidates like this.
9600 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9601 UserDefinedBinaryOperators;
9602
9603 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9604 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9605 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9606 CEnd = CandidateSet.end();
9607 C != CEnd; ++C) {
9608 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9609 continue;
9610
9611 if (C->Function->isFunctionTemplateSpecialization())
9612 continue;
9613
9614 // We interpret "same parameter-type-list" as applying to the
9615 // "synthesized candidate, with the order of the two parameters
9616 // reversed", not to the original function.
9617 bool Reversed = C->isReversed();
9618 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9619 ->getType()
9620 .getUnqualifiedType();
9621 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9622 ->getType()
9623 .getUnqualifiedType();
9624
9625 // Skip if either parameter isn't of enumeral type.
9626 if (!FirstParamType->isEnumeralType() ||
9627 !SecondParamType->isEnumeralType())
9628 continue;
9629
9630 // Add this operator to the set of known user-defined operators.
9631 UserDefinedBinaryOperators.insert(
9632 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9633 S.Context.getCanonicalType(SecondParamType)));
9634 }
9635 }
9636 }
9637
9638 /// Set of (canonical) types that we've already handled.
9639 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9640
9641 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9642 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9643 // Don't add the same builtin candidate twice.
9644 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9645 continue;
9646 if (IsSpaceship && PtrTy->isFunctionPointerType())
9647 continue;
9648
9649 QualType ParamTypes[2] = {PtrTy, PtrTy};
9650 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9651 }
9652 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9653 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9654
9655 // Don't add the same builtin candidate twice, or if a user defined
9656 // candidate exists.
9657 if (!AddedTypes.insert(CanonType).second ||
9658 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9659 CanonType)))
9660 continue;
9661 QualType ParamTypes[2] = {EnumTy, EnumTy};
9662 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9663 }
9664 }
9665 }
9666
9667 // C++ [over.built]p13:
9668 //
9669 // For every cv-qualified or cv-unqualified object type T
9670 // there exist candidate operator functions of the form
9671 //
9672 // T* operator+(T*, ptrdiff_t);
9673 // T& operator[](T*, ptrdiff_t); [BELOW]
9674 // T* operator-(T*, ptrdiff_t);
9675 // T* operator+(ptrdiff_t, T*);
9676 // T& operator[](ptrdiff_t, T*); [BELOW]
9677 //
9678 // C++ [over.built]p14:
9679 //
9680 // For every T, where T is a pointer to object type, there
9681 // exist candidate operator functions of the form
9682 //
9683 // ptrdiff_t operator-(T, T);
9684 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9685 /// Set of (canonical) types that we've already handled.
9686 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9687
9688 for (int Arg = 0; Arg < 2; ++Arg) {
9689 QualType AsymmetricParamTypes[2] = {
9692 };
9693 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9694 QualType PointeeTy = PtrTy->getPointeeType();
9695 if (!PointeeTy->isObjectType())
9696 continue;
9697
9698 AsymmetricParamTypes[Arg] = PtrTy;
9699 if (Arg == 0 || Op == OO_Plus) {
9700 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9701 // T* operator+(ptrdiff_t, T*);
9702 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9703 }
9704 if (Op == OO_Minus) {
9705 // ptrdiff_t operator-(T, T);
9706 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9707 continue;
9708
9709 QualType ParamTypes[2] = {PtrTy, PtrTy};
9710 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9711 }
9712 }
9713 }
9714 }
9715
9716 // C++ [over.built]p12:
9717 //
9718 // For every pair of promoted arithmetic types L and R, there
9719 // exist candidate operator functions of the form
9720 //
9721 // LR operator*(L, R);
9722 // LR operator/(L, R);
9723 // LR operator+(L, R);
9724 // LR operator-(L, R);
9725 // bool operator<(L, R);
9726 // bool operator>(L, R);
9727 // bool operator<=(L, R);
9728 // bool operator>=(L, R);
9729 // bool operator==(L, R);
9730 // bool operator!=(L, R);
9731 //
9732 // where LR is the result of the usual arithmetic conversions
9733 // between types L and R.
9734 //
9735 // C++ [over.built]p24:
9736 //
9737 // For every pair of promoted arithmetic types L and R, there exist
9738 // candidate operator functions of the form
9739 //
9740 // LR operator?(bool, L, R);
9741 //
9742 // where LR is the result of the usual arithmetic conversions
9743 // between types L and R.
9744 // Our candidates ignore the first parameter.
9745 void addGenericBinaryArithmeticOverloads() {
9746 if (!HasArithmeticOrEnumeralCandidateType)
9747 return;
9748
9749 for (unsigned Left = FirstPromotedArithmeticType;
9750 Left < LastPromotedArithmeticType; ++Left) {
9751 for (unsigned Right = FirstPromotedArithmeticType;
9752 Right < LastPromotedArithmeticType; ++Right) {
9753 QualType LandR[2] = { ArithmeticTypes[Left],
9754 ArithmeticTypes[Right] };
9755 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9756 }
9757 }
9758
9759 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9760 // conditional operator for vector types.
9761 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9762 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9763 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9764 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9765 }
9766 }
9767
9768 /// Add binary operator overloads for each candidate matrix type M1, M2:
9769 /// * (M1, M1) -> M1
9770 /// * (M1, M1.getElementType()) -> M1
9771 /// * (M2.getElementType(), M2) -> M2
9772 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9773 void addMatrixBinaryArithmeticOverloads() {
9774 if (!HasArithmeticOrEnumeralCandidateType)
9775 return;
9776
9777 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9778 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9779 AddCandidate(M1, M1);
9780 }
9781
9782 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9783 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9784 if (!CandidateTypes[0].containsMatrixType(M2))
9785 AddCandidate(M2, M2);
9786 }
9787 }
9788
9789 // C++2a [over.built]p14:
9790 //
9791 // For every integral type T there exists a candidate operator function
9792 // of the form
9793 //
9794 // std::strong_ordering operator<=>(T, T)
9795 //
9796 // C++2a [over.built]p15:
9797 //
9798 // For every pair of floating-point types L and R, there exists a candidate
9799 // operator function of the form
9800 //
9801 // std::partial_ordering operator<=>(L, R);
9802 //
9803 // FIXME: The current specification for integral types doesn't play nice with
9804 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9805 // comparisons. Under the current spec this can lead to ambiguity during
9806 // overload resolution. For example:
9807 //
9808 // enum A : int {a};
9809 // auto x = (a <=> (long)42);
9810 //
9811 // error: call is ambiguous for arguments 'A' and 'long'.
9812 // note: candidate operator<=>(int, int)
9813 // note: candidate operator<=>(long, long)
9814 //
9815 // To avoid this error, this function deviates from the specification and adds
9816 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9817 // arithmetic types (the same as the generic relational overloads).
9818 //
9819 // For now this function acts as a placeholder.
9820 void addThreeWayArithmeticOverloads() {
9821 addGenericBinaryArithmeticOverloads();
9822 }
9823
9824 // C++ [over.built]p17:
9825 //
9826 // For every pair of promoted integral types L and R, there
9827 // exist candidate operator functions of the form
9828 //
9829 // LR operator%(L, R);
9830 // LR operator&(L, R);
9831 // LR operator^(L, R);
9832 // LR operator|(L, R);
9833 // L operator<<(L, R);
9834 // L operator>>(L, R);
9835 //
9836 // where LR is the result of the usual arithmetic conversions
9837 // between types L and R.
9838 void addBinaryBitwiseArithmeticOverloads() {
9839 if (!HasArithmeticOrEnumeralCandidateType)
9840 return;
9841
9842 for (unsigned Left = FirstPromotedIntegralType;
9843 Left < LastPromotedIntegralType; ++Left) {
9844 for (unsigned Right = FirstPromotedIntegralType;
9845 Right < LastPromotedIntegralType; ++Right) {
9846 QualType LandR[2] = { ArithmeticTypes[Left],
9847 ArithmeticTypes[Right] };
9848 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9849 }
9850 }
9851 }
9852
9853 // C++ [over.built]p20:
9854 //
9855 // For every pair (T, VQ), where T is an enumeration or
9856 // pointer to member type and VQ is either volatile or
9857 // empty, there exist candidate operator functions of the form
9858 //
9859 // VQ T& operator=(VQ T&, T);
9860 void addAssignmentMemberPointerOrEnumeralOverloads() {
9861 /// Set of (canonical) types that we've already handled.
9862 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9863
9864 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9865 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9866 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9867 continue;
9868
9869 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9870 }
9871
9872 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9873 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9874 continue;
9875
9876 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9877 }
9878 }
9879 }
9880
9881 // C++ [over.built]p19:
9882 //
9883 // For every pair (T, VQ), where T is any type and VQ is either
9884 // volatile or empty, there exist candidate operator functions
9885 // of the form
9886 //
9887 // T*VQ& operator=(T*VQ&, T*);
9888 //
9889 // C++ [over.built]p21:
9890 //
9891 // For every pair (T, VQ), where T is a cv-qualified or
9892 // cv-unqualified object type and VQ is either volatile or
9893 // empty, there exist candidate operator functions of the form
9894 //
9895 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9896 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9897 void addAssignmentPointerOverloads(bool isEqualOp) {
9898 /// Set of (canonical) types that we've already handled.
9899 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9900
9901 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9902 // If this is operator=, keep track of the builtin candidates we added.
9903 if (isEqualOp)
9904 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9905 else if (!PtrTy->getPointeeType()->isObjectType())
9906 continue;
9907
9908 // non-volatile version
9909 QualType ParamTypes[2] = {
9911 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9912 };
9913 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9914 /*IsAssignmentOperator=*/ isEqualOp);
9915
9916 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9917 VisibleTypeConversionsQuals.hasVolatile();
9918 if (NeedVolatile) {
9919 // volatile version
9920 ParamTypes[0] =
9922 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9923 /*IsAssignmentOperator=*/isEqualOp);
9924 }
9925
9926 if (!PtrTy.isRestrictQualified() &&
9927 VisibleTypeConversionsQuals.hasRestrict()) {
9928 // restrict version
9929 ParamTypes[0] =
9931 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9932 /*IsAssignmentOperator=*/isEqualOp);
9933
9934 if (NeedVolatile) {
9935 // volatile restrict version
9936 ParamTypes[0] =
9939 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9940 /*IsAssignmentOperator=*/isEqualOp);
9941 }
9942 }
9943 }
9944
9945 if (isEqualOp) {
9946 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9947 // Make sure we don't add the same candidate twice.
9948 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9949 continue;
9950
9951 QualType ParamTypes[2] = {
9953 PtrTy,
9954 };
9955
9956 // non-volatile version
9957 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9958 /*IsAssignmentOperator=*/true);
9959
9960 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9961 VisibleTypeConversionsQuals.hasVolatile();
9962 if (NeedVolatile) {
9963 // volatile version
9964 ParamTypes[0] = S.Context.getLValueReferenceType(
9965 S.Context.getVolatileType(PtrTy));
9966 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9967 /*IsAssignmentOperator=*/true);
9968 }
9969
9970 if (!PtrTy.isRestrictQualified() &&
9971 VisibleTypeConversionsQuals.hasRestrict()) {
9972 // restrict version
9973 ParamTypes[0] = S.Context.getLValueReferenceType(
9974 S.Context.getRestrictType(PtrTy));
9975 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9976 /*IsAssignmentOperator=*/true);
9977
9978 if (NeedVolatile) {
9979 // volatile restrict version
9980 ParamTypes[0] =
9983 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9984 /*IsAssignmentOperator=*/true);
9985 }
9986 }
9987 }
9988 }
9989 }
9990
9991 // C++ [over.built]p18:
9992 //
9993 // For every triple (L, VQ, R), where L is an arithmetic type,
9994 // VQ is either volatile or empty, and R is a promoted
9995 // arithmetic type, there exist candidate operator functions of
9996 // the form
9997 //
9998 // VQ L& operator=(VQ L&, R);
9999 // VQ L& operator*=(VQ L&, R);
10000 // VQ L& operator/=(VQ L&, R);
10001 // VQ L& operator+=(VQ L&, R);
10002 // VQ L& operator-=(VQ L&, R);
10003 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10004 if (!HasArithmeticOrEnumeralCandidateType)
10005 return;
10006
10007 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10008 for (unsigned Right = FirstPromotedArithmeticType;
10009 Right < LastPromotedArithmeticType; ++Right) {
10010 QualType ParamTypes[2];
10011 ParamTypes[1] = ArithmeticTypes[Right];
10013 S, ArithmeticTypes[Left], Args[0]);
10014
10016 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10017 ParamTypes[0] =
10018 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10020 /*IsAssignmentOperator=*/isEqualOp);
10021 });
10022 }
10023 }
10024
10025 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10026 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10027 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10028 QualType ParamTypes[2];
10029 ParamTypes[1] = Vec2Ty;
10030 // Add this built-in operator as a candidate (VQ is empty).
10031 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10032 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10033 /*IsAssignmentOperator=*/isEqualOp);
10034
10035 // Add this built-in operator as a candidate (VQ is 'volatile').
10036 if (VisibleTypeConversionsQuals.hasVolatile()) {
10037 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10038 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10039 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10040 /*IsAssignmentOperator=*/isEqualOp);
10041 }
10042 }
10043 }
10044
10045 // C++ [over.built]p22:
10046 //
10047 // For every triple (L, VQ, R), where L is an integral type, VQ
10048 // is either volatile or empty, and R is a promoted integral
10049 // type, there exist candidate operator functions of the form
10050 //
10051 // VQ L& operator%=(VQ L&, R);
10052 // VQ L& operator<<=(VQ L&, R);
10053 // VQ L& operator>>=(VQ L&, R);
10054 // VQ L& operator&=(VQ L&, R);
10055 // VQ L& operator^=(VQ L&, R);
10056 // VQ L& operator|=(VQ L&, R);
10057 void addAssignmentIntegralOverloads() {
10058 if (!HasArithmeticOrEnumeralCandidateType)
10059 return;
10060
10061 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10062 for (unsigned Right = FirstPromotedIntegralType;
10063 Right < LastPromotedIntegralType; ++Right) {
10064 QualType ParamTypes[2];
10065 ParamTypes[1] = ArithmeticTypes[Right];
10067 S, ArithmeticTypes[Left], Args[0]);
10068
10070 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10071 ParamTypes[0] =
10072 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10073 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10074 });
10075 }
10076 }
10077 }
10078
10079 // C++ [over.operator]p23:
10080 //
10081 // There also exist candidate operator functions of the form
10082 //
10083 // bool operator!(bool);
10084 // bool operator&&(bool, bool);
10085 // bool operator||(bool, bool);
10086 void addExclaimOverload() {
10087 QualType ParamTy = S.Context.BoolTy;
10088 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10089 /*IsAssignmentOperator=*/false,
10090 /*NumContextualBoolArguments=*/1);
10091 }
10092 void addAmpAmpOrPipePipeOverload() {
10093 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10094 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10095 /*IsAssignmentOperator=*/false,
10096 /*NumContextualBoolArguments=*/2);
10097 }
10098
10099 // C++ [over.built]p13:
10100 //
10101 // For every cv-qualified or cv-unqualified object type T there
10102 // exist candidate operator functions of the form
10103 //
10104 // T* operator+(T*, ptrdiff_t); [ABOVE]
10105 // T& operator[](T*, ptrdiff_t);
10106 // T* operator-(T*, ptrdiff_t); [ABOVE]
10107 // T* operator+(ptrdiff_t, T*); [ABOVE]
10108 // T& operator[](ptrdiff_t, T*);
10109 void addSubscriptOverloads() {
10110 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10111 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10112 QualType PointeeType = PtrTy->getPointeeType();
10113 if (!PointeeType->isObjectType())
10114 continue;
10115
10116 // T& operator[](T*, ptrdiff_t)
10117 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10118 }
10119
10120 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10121 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10122 QualType PointeeType = PtrTy->getPointeeType();
10123 if (!PointeeType->isObjectType())
10124 continue;
10125
10126 // T& operator[](ptrdiff_t, T*)
10127 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10128 }
10129 }
10130
10131 // C++ [over.built]p11:
10132 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10133 // C1 is the same type as C2 or is a derived class of C2, T is an object
10134 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10135 // there exist candidate operator functions of the form
10136 //
10137 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10138 //
10139 // where CV12 is the union of CV1 and CV2.
10140 void addArrowStarOverloads() {
10141 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10142 QualType C1Ty = PtrTy;
10143 QualType C1;
10144 QualifierCollector Q1;
10145 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10146 if (!isa<RecordType>(C1))
10147 continue;
10148 // heuristic to reduce number of builtin candidates in the set.
10149 // Add volatile/restrict version only if there are conversions to a
10150 // volatile/restrict type.
10151 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10152 continue;
10153 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10154 continue;
10155 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10156 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10157 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10158 *D2 = mptr->getMostRecentCXXRecordDecl();
10159 if (!declaresSameEntity(D1, D2) &&
10160 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10161 break;
10162 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10163 // build CV12 T&
10164 QualType T = mptr->getPointeeType();
10165 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10166 T.isVolatileQualified())
10167 continue;
10168 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10169 T.isRestrictQualified())
10170 continue;
10171 T = Q1.apply(S.Context, T);
10172 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10173 }
10174 }
10175 }
10176
10177 // Note that we don't consider the first argument, since it has been
10178 // contextually converted to bool long ago. The candidates below are
10179 // therefore added as binary.
10180 //
10181 // C++ [over.built]p25:
10182 // For every type T, where T is a pointer, pointer-to-member, or scoped
10183 // enumeration type, there exist candidate operator functions of the form
10184 //
10185 // T operator?(bool, T, T);
10186 //
10187 void addConditionalOperatorOverloads() {
10188 /// Set of (canonical) types that we've already handled.
10189 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10190
10191 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10192 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10193 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10194 continue;
10195
10196 QualType ParamTypes[2] = {PtrTy, PtrTy};
10197 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10198 }
10199
10200 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10201 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10202 continue;
10203
10204 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10205 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10206 }
10207
10208 if (S.getLangOpts().CPlusPlus11) {
10209 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10210 if (!EnumTy->castAsCanonical<EnumType>()
10211 ->getOriginalDecl()
10212 ->isScoped())
10213 continue;
10214
10215 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10216 continue;
10217
10218 QualType ParamTypes[2] = {EnumTy, EnumTy};
10219 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10220 }
10221 }
10222 }
10223 }
10224};
10225
10226} // end anonymous namespace
10227
10229 SourceLocation OpLoc,
10230 ArrayRef<Expr *> Args,
10231 OverloadCandidateSet &CandidateSet) {
10232 // Find all of the types that the arguments can convert to, but only
10233 // if the operator we're looking at has built-in operator candidates
10234 // that make use of these types. Also record whether we encounter non-record
10235 // candidate types or either arithmetic or enumeral candidate types.
10236 QualifiersAndAtomic VisibleTypeConversionsQuals;
10237 VisibleTypeConversionsQuals.addConst();
10238 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10239 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10240 if (Args[ArgIdx]->getType()->isAtomicType())
10241 VisibleTypeConversionsQuals.addAtomic();
10242 }
10243
10244 bool HasNonRecordCandidateType = false;
10245 bool HasArithmeticOrEnumeralCandidateType = false;
10247 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10248 CandidateTypes.emplace_back(*this);
10249 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10250 OpLoc,
10251 true,
10252 (Op == OO_Exclaim ||
10253 Op == OO_AmpAmp ||
10254 Op == OO_PipePipe),
10255 VisibleTypeConversionsQuals);
10256 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10257 CandidateTypes[ArgIdx].hasNonRecordTypes();
10258 HasArithmeticOrEnumeralCandidateType =
10259 HasArithmeticOrEnumeralCandidateType ||
10260 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10261 }
10262
10263 // Exit early when no non-record types have been added to the candidate set
10264 // for any of the arguments to the operator.
10265 //
10266 // We can't exit early for !, ||, or &&, since there we have always have
10267 // 'bool' overloads.
10268 if (!HasNonRecordCandidateType &&
10269 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10270 return;
10271
10272 // Setup an object to manage the common state for building overloads.
10273 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10274 VisibleTypeConversionsQuals,
10275 HasArithmeticOrEnumeralCandidateType,
10276 CandidateTypes, CandidateSet);
10277
10278 // Dispatch over the operation to add in only those overloads which apply.
10279 switch (Op) {
10280 case OO_None:
10282 llvm_unreachable("Expected an overloaded operator");
10283
10284 case OO_New:
10285 case OO_Delete:
10286 case OO_Array_New:
10287 case OO_Array_Delete:
10288 case OO_Call:
10289 llvm_unreachable(
10290 "Special operators don't use AddBuiltinOperatorCandidates");
10291
10292 case OO_Comma:
10293 case OO_Arrow:
10294 case OO_Coawait:
10295 // C++ [over.match.oper]p3:
10296 // -- For the operator ',', the unary operator '&', the
10297 // operator '->', or the operator 'co_await', the
10298 // built-in candidates set is empty.
10299 break;
10300
10301 case OO_Plus: // '+' is either unary or binary
10302 if (Args.size() == 1)
10303 OpBuilder.addUnaryPlusPointerOverloads();
10304 [[fallthrough]];
10305
10306 case OO_Minus: // '-' is either unary or binary
10307 if (Args.size() == 1) {
10308 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10309 } else {
10310 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10311 OpBuilder.addGenericBinaryArithmeticOverloads();
10312 OpBuilder.addMatrixBinaryArithmeticOverloads();
10313 }
10314 break;
10315
10316 case OO_Star: // '*' is either unary or binary
10317 if (Args.size() == 1)
10318 OpBuilder.addUnaryStarPointerOverloads();
10319 else {
10320 OpBuilder.addGenericBinaryArithmeticOverloads();
10321 OpBuilder.addMatrixBinaryArithmeticOverloads();
10322 }
10323 break;
10324
10325 case OO_Slash:
10326 OpBuilder.addGenericBinaryArithmeticOverloads();
10327 break;
10328
10329 case OO_PlusPlus:
10330 case OO_MinusMinus:
10331 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10332 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10333 break;
10334
10335 case OO_EqualEqual:
10336 case OO_ExclaimEqual:
10337 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10338 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10339 OpBuilder.addGenericBinaryArithmeticOverloads();
10340 break;
10341
10342 case OO_Less:
10343 case OO_Greater:
10344 case OO_LessEqual:
10345 case OO_GreaterEqual:
10346 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10347 OpBuilder.addGenericBinaryArithmeticOverloads();
10348 break;
10349
10350 case OO_Spaceship:
10351 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10352 OpBuilder.addThreeWayArithmeticOverloads();
10353 break;
10354
10355 case OO_Percent:
10356 case OO_Caret:
10357 case OO_Pipe:
10358 case OO_LessLess:
10359 case OO_GreaterGreater:
10360 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10361 break;
10362
10363 case OO_Amp: // '&' is either unary or binary
10364 if (Args.size() == 1)
10365 // C++ [over.match.oper]p3:
10366 // -- For the operator ',', the unary operator '&', or the
10367 // operator '->', the built-in candidates set is empty.
10368 break;
10369
10370 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10371 break;
10372
10373 case OO_Tilde:
10374 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10375 break;
10376
10377 case OO_Equal:
10378 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10379 [[fallthrough]];
10380
10381 case OO_PlusEqual:
10382 case OO_MinusEqual:
10383 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10384 [[fallthrough]];
10385
10386 case OO_StarEqual:
10387 case OO_SlashEqual:
10388 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10389 break;
10390
10391 case OO_PercentEqual:
10392 case OO_LessLessEqual:
10393 case OO_GreaterGreaterEqual:
10394 case OO_AmpEqual:
10395 case OO_CaretEqual:
10396 case OO_PipeEqual:
10397 OpBuilder.addAssignmentIntegralOverloads();
10398 break;
10399
10400 case OO_Exclaim:
10401 OpBuilder.addExclaimOverload();
10402 break;
10403
10404 case OO_AmpAmp:
10405 case OO_PipePipe:
10406 OpBuilder.addAmpAmpOrPipePipeOverload();
10407 break;
10408
10409 case OO_Subscript:
10410 if (Args.size() == 2)
10411 OpBuilder.addSubscriptOverloads();
10412 break;
10413
10414 case OO_ArrowStar:
10415 OpBuilder.addArrowStarOverloads();
10416 break;
10417
10418 case OO_Conditional:
10419 OpBuilder.addConditionalOperatorOverloads();
10420 OpBuilder.addGenericBinaryArithmeticOverloads();
10421 break;
10422 }
10423}
10424
10425void
10427 SourceLocation Loc,
10428 ArrayRef<Expr *> Args,
10429 TemplateArgumentListInfo *ExplicitTemplateArgs,
10430 OverloadCandidateSet& CandidateSet,
10431 bool PartialOverloading) {
10432 ADLResult Fns;
10433
10434 // FIXME: This approach for uniquing ADL results (and removing
10435 // redundant candidates from the set) relies on pointer-equality,
10436 // which means we need to key off the canonical decl. However,
10437 // always going back to the canonical decl might not get us the
10438 // right set of default arguments. What default arguments are
10439 // we supposed to consider on ADL candidates, anyway?
10440
10441 // FIXME: Pass in the explicit template arguments?
10442 ArgumentDependentLookup(Name, Loc, Args, Fns);
10443
10444 ArrayRef<Expr *> ReversedArgs;
10445
10446 // Erase all of the candidates we already knew about.
10447 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10448 CandEnd = CandidateSet.end();
10449 Cand != CandEnd; ++Cand)
10450 if (Cand->Function) {
10451 FunctionDecl *Fn = Cand->Function;
10452 Fns.erase(Fn);
10453 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10454 Fns.erase(FunTmpl);
10455 }
10456
10457 // For each of the ADL candidates we found, add it to the overload
10458 // set.
10459 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10461
10462 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10463 if (ExplicitTemplateArgs)
10464 continue;
10465
10467 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10468 PartialOverloading, /*AllowExplicit=*/true,
10469 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10470 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10472 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10473 /*SuppressUserConversions=*/false, PartialOverloading,
10474 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10475 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10476 }
10477 } else {
10478 auto *FTD = cast<FunctionTemplateDecl>(*I);
10480 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10481 /*SuppressUserConversions=*/false, PartialOverloading,
10482 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10483 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10484 *this, Args, FTD->getTemplatedDecl())) {
10485
10486 // As template candidates are not deduced immediately,
10487 // persist the array in the overload set.
10488 if (ReversedArgs.empty())
10489 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10490
10492 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10493 /*SuppressUserConversions=*/false, PartialOverloading,
10494 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10496 }
10497 }
10498 }
10499}
10500
10501namespace {
10502enum class Comparison { Equal, Better, Worse };
10503}
10504
10505/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10506/// overload resolution.
10507///
10508/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10509/// Cand1's first N enable_if attributes have precisely the same conditions as
10510/// Cand2's first N enable_if attributes (where N = the number of enable_if
10511/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10512///
10513/// Note that you can have a pair of candidates such that Cand1's enable_if
10514/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10515/// worse than Cand1's.
10516static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10517 const FunctionDecl *Cand2) {
10518 // Common case: One (or both) decls don't have enable_if attrs.
10519 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10520 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10521 if (!Cand1Attr || !Cand2Attr) {
10522 if (Cand1Attr == Cand2Attr)
10523 return Comparison::Equal;
10524 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10525 }
10526
10527 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10528 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10529
10530 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10531 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10532 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10533 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10534
10535 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10536 // has fewer enable_if attributes than Cand2, and vice versa.
10537 if (!Cand1A)
10538 return Comparison::Worse;
10539 if (!Cand2A)
10540 return Comparison::Better;
10541
10542 Cand1ID.clear();
10543 Cand2ID.clear();
10544
10545 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10546 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10547 if (Cand1ID != Cand2ID)
10548 return Comparison::Worse;
10549 }
10550
10551 return Comparison::Equal;
10552}
10553
10554static Comparison
10556 const OverloadCandidate &Cand2) {
10557 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10558 !Cand2.Function->isMultiVersion())
10559 return Comparison::Equal;
10560
10561 // If both are invalid, they are equal. If one of them is invalid, the other
10562 // is better.
10563 if (Cand1.Function->isInvalidDecl()) {
10564 if (Cand2.Function->isInvalidDecl())
10565 return Comparison::Equal;
10566 return Comparison::Worse;
10567 }
10568 if (Cand2.Function->isInvalidDecl())
10569 return Comparison::Better;
10570
10571 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10572 // cpu_dispatch, else arbitrarily based on the identifiers.
10573 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10574 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10575 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10576 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10577
10578 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10579 return Comparison::Equal;
10580
10581 if (Cand1CPUDisp && !Cand2CPUDisp)
10582 return Comparison::Better;
10583 if (Cand2CPUDisp && !Cand1CPUDisp)
10584 return Comparison::Worse;
10585
10586 if (Cand1CPUSpec && Cand2CPUSpec) {
10587 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10588 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10589 ? Comparison::Better
10590 : Comparison::Worse;
10591
10592 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10593 FirstDiff = std::mismatch(
10594 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10595 Cand2CPUSpec->cpus_begin(),
10596 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10597 return LHS->getName() == RHS->getName();
10598 });
10599
10600 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10601 "Two different cpu-specific versions should not have the same "
10602 "identifier list, otherwise they'd be the same decl!");
10603 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10604 ? Comparison::Better
10605 : Comparison::Worse;
10606 }
10607 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10608}
10609
10610/// Compute the type of the implicit object parameter for the given function,
10611/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10612/// null QualType if there is a 'matches anything' implicit object parameter.
10613static std::optional<QualType>
10616 return std::nullopt;
10617
10618 auto *M = cast<CXXMethodDecl>(F);
10619 // Static member functions' object parameters match all types.
10620 if (M->isStatic())
10621 return QualType();
10622 return M->getFunctionObjectParameterReferenceType();
10623}
10624
10625// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10626// represent the same entity.
10627static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10628 const FunctionDecl *F2) {
10629 if (declaresSameEntity(F1, F2))
10630 return true;
10631 auto PT1 = F1->getPrimaryTemplate();
10632 auto PT2 = F2->getPrimaryTemplate();
10633 if (PT1 && PT2) {
10634 if (declaresSameEntity(PT1, PT2) ||
10635 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10636 PT2->getInstantiatedFromMemberTemplate()))
10637 return true;
10638 }
10639 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10640 // different functions with same params). Consider removing this (as no test
10641 // fail w/o it).
10642 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10643 if (First) {
10644 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10645 return *T;
10646 }
10647 assert(I < F->getNumParams());
10648 return F->getParamDecl(I++)->getType();
10649 };
10650
10651 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10652 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10653
10654 if (F1NumParams != F2NumParams)
10655 return false;
10656
10657 unsigned I1 = 0, I2 = 0;
10658 for (unsigned I = 0; I != F1NumParams; ++I) {
10659 QualType T1 = NextParam(F1, I1, I == 0);
10660 QualType T2 = NextParam(F2, I2, I == 0);
10661 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10662 if (!Context.hasSameUnqualifiedType(T1, T2))
10663 return false;
10664 }
10665 return true;
10666}
10667
10668/// We're allowed to use constraints partial ordering only if the candidates
10669/// have the same parameter types:
10670/// [over.match.best.general]p2.6
10671/// F1 and F2 are non-template functions with the same
10672/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10674 FunctionDecl *Fn2,
10675 bool IsFn1Reversed,
10676 bool IsFn2Reversed) {
10677 assert(Fn1 && Fn2);
10678 if (Fn1->isVariadic() != Fn2->isVariadic())
10679 return false;
10680
10681 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10682 IsFn1Reversed ^ IsFn2Reversed))
10683 return false;
10684
10685 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10686 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10687 if (Mem1 && Mem2) {
10688 // if they are member functions, both are direct members of the same class,
10689 // and
10690 if (Mem1->getParent() != Mem2->getParent())
10691 return false;
10692 // if both are non-static member functions, they have the same types for
10693 // their object parameters
10694 if (Mem1->isInstance() && Mem2->isInstance() &&
10696 Mem1->getFunctionObjectParameterReferenceType(),
10697 Mem1->getFunctionObjectParameterReferenceType()))
10698 return false;
10699 }
10700 return true;
10701}
10702
10703static FunctionDecl *
10705 bool IsFn1Reversed, bool IsFn2Reversed) {
10706 if (!Fn1 || !Fn2)
10707 return nullptr;
10708
10709 // C++ [temp.constr.order]:
10710 // A non-template function F1 is more partial-ordering-constrained than a
10711 // non-template function F2 if:
10712 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10713 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10714
10715 if (Cand1IsSpecialization || Cand2IsSpecialization)
10716 return nullptr;
10717
10718 // - they have the same non-object-parameter-type-lists, and [...]
10719 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10720 IsFn2Reversed))
10721 return nullptr;
10722
10723 // - the declaration of F1 is more constrained than the declaration of F2.
10724 return S.getMoreConstrainedFunction(Fn1, Fn2);
10725}
10726
10727/// isBetterOverloadCandidate - Determines whether the first overload
10728/// candidate is a better candidate than the second (C++ 13.3.3p1).
10730 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10732 bool PartialOverloading) {
10733 // Define viable functions to be better candidates than non-viable
10734 // functions.
10735 if (!Cand2.Viable)
10736 return Cand1.Viable;
10737 else if (!Cand1.Viable)
10738 return false;
10739
10740 // [CUDA] A function with 'never' preference is marked not viable, therefore
10741 // is never shown up here. The worst preference shown up here is 'wrong side',
10742 // e.g. an H function called by a HD function in device compilation. This is
10743 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10744 // function which is called only by an H function. A deferred diagnostic will
10745 // be triggered if it is emitted. However a wrong-sided function is still
10746 // a viable candidate here.
10747 //
10748 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10749 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10750 // can be emitted, Cand1 is not better than Cand2. This rule should have
10751 // precedence over other rules.
10752 //
10753 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10754 // other rules should be used to determine which is better. This is because
10755 // host/device based overloading resolution is mostly for determining
10756 // viability of a function. If two functions are both viable, other factors
10757 // should take precedence in preference, e.g. the standard-defined preferences
10758 // like argument conversion ranks or enable_if partial-ordering. The
10759 // preference for pass-object-size parameters is probably most similar to a
10760 // type-based-overloading decision and so should take priority.
10761 //
10762 // If other rules cannot determine which is better, CUDA preference will be
10763 // used again to determine which is better.
10764 //
10765 // TODO: Currently IdentifyPreference does not return correct values
10766 // for functions called in global variable initializers due to missing
10767 // correct context about device/host. Therefore we can only enforce this
10768 // rule when there is a caller. We should enforce this rule for functions
10769 // in global variable initializers once proper context is added.
10770 //
10771 // TODO: We can only enable the hostness based overloading resolution when
10772 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10773 // overloading resolution diagnostics.
10774 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10775 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10776 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10777 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10778 bool IsCand1ImplicitHD =
10780 bool IsCand2ImplicitHD =
10782 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10783 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10784 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10785 // The implicit HD function may be a function in a system header which
10786 // is forced by pragma. In device compilation, if we prefer HD candidates
10787 // over wrong-sided candidates, overloading resolution may change, which
10788 // may result in non-deferrable diagnostics. As a workaround, we let
10789 // implicit HD candidates take equal preference as wrong-sided candidates.
10790 // This will preserve the overloading resolution.
10791 // TODO: We still need special handling of implicit HD functions since
10792 // they may incur other diagnostics to be deferred. We should make all
10793 // host/device related diagnostics deferrable and remove special handling
10794 // of implicit HD functions.
10795 auto EmitThreshold =
10796 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10797 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10800 auto Cand1Emittable = P1 > EmitThreshold;
10801 auto Cand2Emittable = P2 > EmitThreshold;
10802 if (Cand1Emittable && !Cand2Emittable)
10803 return true;
10804 if (!Cand1Emittable && Cand2Emittable)
10805 return false;
10806 }
10807 }
10808
10809 // C++ [over.match.best]p1: (Changed in C++23)
10810 //
10811 // -- if F is a static member function, ICS1(F) is defined such
10812 // that ICS1(F) is neither better nor worse than ICS1(G) for
10813 // any function G, and, symmetrically, ICS1(G) is neither
10814 // better nor worse than ICS1(F).
10815 unsigned StartArg = 0;
10816 if (!Cand1.TookAddressOfOverload &&
10818 StartArg = 1;
10819
10820 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10821 // We don't allow incompatible pointer conversions in C++.
10822 if (!S.getLangOpts().CPlusPlus)
10823 return ICS.isStandard() &&
10824 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10825
10826 // The only ill-formed conversion we allow in C++ is the string literal to
10827 // char* conversion, which is only considered ill-formed after C++11.
10828 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10830 };
10831
10832 // Define functions that don't require ill-formed conversions for a given
10833 // argument to be better candidates than functions that do.
10834 unsigned NumArgs = Cand1.Conversions.size();
10835 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10836 bool HasBetterConversion = false;
10837 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10838 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10839 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10840 if (Cand1Bad != Cand2Bad) {
10841 if (Cand1Bad)
10842 return false;
10843 HasBetterConversion = true;
10844 }
10845 }
10846
10847 if (HasBetterConversion)
10848 return true;
10849
10850 // C++ [over.match.best]p1:
10851 // A viable function F1 is defined to be a better function than another
10852 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10853 // conversion sequence than ICSi(F2), and then...
10854 bool HasWorseConversion = false;
10855 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10857 Cand1.Conversions[ArgIdx],
10858 Cand2.Conversions[ArgIdx])) {
10860 // Cand1 has a better conversion sequence.
10861 HasBetterConversion = true;
10862 break;
10863
10865 if (Cand1.Function && Cand2.Function &&
10866 Cand1.isReversed() != Cand2.isReversed() &&
10867 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10868 // Work around large-scale breakage caused by considering reversed
10869 // forms of operator== in C++20:
10870 //
10871 // When comparing a function against a reversed function, if we have a
10872 // better conversion for one argument and a worse conversion for the
10873 // other, the implicit conversion sequences are treated as being equally
10874 // good.
10875 //
10876 // This prevents a comparison function from being considered ambiguous
10877 // with a reversed form that is written in the same way.
10878 //
10879 // We diagnose this as an extension from CreateOverloadedBinOp.
10880 HasWorseConversion = true;
10881 break;
10882 }
10883
10884 // Cand1 can't be better than Cand2.
10885 return false;
10886
10888 // Do nothing.
10889 break;
10890 }
10891 }
10892
10893 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10894 // ICSj(F2), or, if not that,
10895 if (HasBetterConversion && !HasWorseConversion)
10896 return true;
10897
10898 // -- the context is an initialization by user-defined conversion
10899 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10900 // from the return type of F1 to the destination type (i.e.,
10901 // the type of the entity being initialized) is a better
10902 // conversion sequence than the standard conversion sequence
10903 // from the return type of F2 to the destination type.
10905 Cand1.Function && Cand2.Function &&
10908
10909 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10910 // First check whether we prefer one of the conversion functions over the
10911 // other. This only distinguishes the results in non-standard, extension
10912 // cases such as the conversion from a lambda closure type to a function
10913 // pointer or block.
10918 Cand1.FinalConversion,
10919 Cand2.FinalConversion);
10920
10923
10924 // FIXME: Compare kind of reference binding if conversion functions
10925 // convert to a reference type used in direct reference binding, per
10926 // C++14 [over.match.best]p1 section 2 bullet 3.
10927 }
10928
10929 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10930 // as combined with the resolution to CWG issue 243.
10931 //
10932 // When the context is initialization by constructor ([over.match.ctor] or
10933 // either phase of [over.match.list]), a constructor is preferred over
10934 // a conversion function.
10935 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10936 Cand1.Function && Cand2.Function &&
10939 return isa<CXXConstructorDecl>(Cand1.Function);
10940
10941 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10942 return Cand2.StrictPackMatch;
10943
10944 // -- F1 is a non-template function and F2 is a function template
10945 // specialization, or, if not that,
10946 bool Cand1IsSpecialization = Cand1.Function &&
10948 bool Cand2IsSpecialization = Cand2.Function &&
10950 if (Cand1IsSpecialization != Cand2IsSpecialization)
10951 return Cand2IsSpecialization;
10952
10953 // -- F1 and F2 are function template specializations, and the function
10954 // template for F1 is more specialized than the template for F2
10955 // according to the partial ordering rules described in 14.5.5.2, or,
10956 // if not that,
10957 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10958 const auto *Obj1Context =
10959 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10960 const auto *Obj2Context =
10961 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10962 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10964 Cand2.Function->getPrimaryTemplate(), Loc,
10966 : TPOC_Call,
10968 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
10969 : QualType{},
10970 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
10971 : QualType{},
10972 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10973 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10974 }
10975 }
10976
10977 // -— F1 and F2 are non-template functions and F1 is more
10978 // partial-ordering-constrained than F2 [...],
10980 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10981 Cand2.isReversed());
10982 F && F == Cand1.Function)
10983 return true;
10984
10985 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10986 // class B of D, and for all arguments the corresponding parameters of
10987 // F1 and F2 have the same type.
10988 // FIXME: Implement the "all parameters have the same type" check.
10989 bool Cand1IsInherited =
10990 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10991 bool Cand2IsInherited =
10992 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10993 if (Cand1IsInherited != Cand2IsInherited)
10994 return Cand2IsInherited;
10995 else if (Cand1IsInherited) {
10996 assert(Cand2IsInherited);
10997 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10998 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10999 if (Cand1Class->isDerivedFrom(Cand2Class))
11000 return true;
11001 if (Cand2Class->isDerivedFrom(Cand1Class))
11002 return false;
11003 // Inherited from sibling base classes: still ambiguous.
11004 }
11005
11006 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11007 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11008 // with reversed order of parameters and F1 is not
11009 //
11010 // We rank reversed + different operator as worse than just reversed, but
11011 // that comparison can never happen, because we only consider reversing for
11012 // the maximally-rewritten operator (== or <=>).
11013 if (Cand1.RewriteKind != Cand2.RewriteKind)
11014 return Cand1.RewriteKind < Cand2.RewriteKind;
11015
11016 // Check C++17 tie-breakers for deduction guides.
11017 {
11018 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11019 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11020 if (Guide1 && Guide2) {
11021 // -- F1 is generated from a deduction-guide and F2 is not
11022 if (Guide1->isImplicit() != Guide2->isImplicit())
11023 return Guide2->isImplicit();
11024
11025 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11026 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11027 return true;
11028 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11029 return false;
11030
11031 // --F1 is generated from a non-template constructor and F2 is generated
11032 // from a constructor template
11033 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11034 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11035 if (Constructor1 && Constructor2) {
11036 bool isC1Templated = Constructor1->getTemplatedKind() !=
11038 bool isC2Templated = Constructor2->getTemplatedKind() !=
11040 if (isC1Templated != isC2Templated)
11041 return isC2Templated;
11042 }
11043 }
11044 }
11045
11046 // Check for enable_if value-based overload resolution.
11047 if (Cand1.Function && Cand2.Function) {
11048 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11049 if (Cmp != Comparison::Equal)
11050 return Cmp == Comparison::Better;
11051 }
11052
11053 bool HasPS1 = Cand1.Function != nullptr &&
11055 bool HasPS2 = Cand2.Function != nullptr &&
11057 if (HasPS1 != HasPS2 && HasPS1)
11058 return true;
11059
11060 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11061 if (MV == Comparison::Better)
11062 return true;
11063 if (MV == Comparison::Worse)
11064 return false;
11065
11066 // If other rules cannot determine which is better, CUDA preference is used
11067 // to determine which is better.
11068 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11069 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11070 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11071 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11072 }
11073
11074 // General member function overloading is handled above, so this only handles
11075 // constructors with address spaces.
11076 // This only handles address spaces since C++ has no other
11077 // qualifier that can be used with constructors.
11078 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11079 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11080 if (CD1 && CD2) {
11081 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11082 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11083 if (AS1 != AS2) {
11085 return true;
11087 return false;
11088 }
11089 }
11090
11091 return false;
11092}
11093
11094/// Determine whether two declarations are "equivalent" for the purposes of
11095/// name lookup and overload resolution. This applies when the same internal/no
11096/// linkage entity is defined by two modules (probably by textually including
11097/// the same header). In such a case, we don't consider the declarations to
11098/// declare the same entity, but we also don't want lookups with both
11099/// declarations visible to be ambiguous in some cases (this happens when using
11100/// a modularized libstdc++).
11102 const NamedDecl *B) {
11103 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11104 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11105 if (!VA || !VB)
11106 return false;
11107
11108 // The declarations must be declaring the same name as an internal linkage
11109 // entity in different modules.
11110 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11111 VB->getDeclContext()->getRedeclContext()) ||
11112 getOwningModule(VA) == getOwningModule(VB) ||
11113 VA->isExternallyVisible() || VB->isExternallyVisible())
11114 return false;
11115
11116 // Check that the declarations appear to be equivalent.
11117 //
11118 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11119 // For constants and functions, we should check the initializer or body is
11120 // the same. For non-constant variables, we shouldn't allow it at all.
11121 if (Context.hasSameType(VA->getType(), VB->getType()))
11122 return true;
11123
11124 // Enum constants within unnamed enumerations will have different types, but
11125 // may still be similar enough to be interchangeable for our purposes.
11126 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11127 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11128 // Only handle anonymous enums. If the enumerations were named and
11129 // equivalent, they would have been merged to the same type.
11130 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11131 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11132 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11133 !Context.hasSameType(EnumA->getIntegerType(),
11134 EnumB->getIntegerType()))
11135 return false;
11136 // Allow this only if the value is the same for both enumerators.
11137 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11138 }
11139 }
11140
11141 // Nothing else is sufficiently similar.
11142 return false;
11143}
11144
11147 assert(D && "Unknown declaration");
11148 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11149
11150 Module *M = getOwningModule(D);
11151 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11152 << !M << (M ? M->getFullModuleName() : "");
11153
11154 for (auto *E : Equiv) {
11155 Module *M = getOwningModule(E);
11156 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11157 << !M << (M ? M->getFullModuleName() : "");
11158 }
11159}
11160
11163 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11165 static_cast<CNSInfo *>(DeductionFailure.Data)
11166 ->Satisfaction.ContainsErrors;
11167}
11168
11171 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11172 bool PartialOverloading, bool AllowExplicit,
11174 bool AggregateCandidateDeduction) {
11175
11176 auto *C =
11177 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11178
11181 /*AllowObjCConversionOnExplicit=*/false,
11182 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11183 PartialOverloading, AggregateCandidateDeduction},
11185 FoundDecl,
11186 Args,
11187 IsADLCandidate,
11188 PO};
11189
11190 HasDeferredTemplateConstructors |=
11191 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11192}
11193
11195 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11196 CXXRecordDecl *ActingContext, QualType ObjectType,
11197 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11198 bool SuppressUserConversions, bool PartialOverloading,
11200
11201 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11202
11203 auto *C =
11204 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11205
11208 /*AllowObjCConversionOnExplicit=*/false,
11209 /*AllowResultConversion=*/false,
11210 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11211 /*AggregateCandidateDeduction=*/false},
11212 MethodTmpl,
11213 FoundDecl,
11214 Args,
11215 ActingContext,
11216 ObjectClassification,
11217 ObjectType,
11218 PO};
11219}
11220
11223 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11224 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11225 bool AllowResultConversion) {
11226
11227 auto *C =
11228 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11229
11232 AllowObjCConversionOnExplicit, AllowResultConversion,
11233 /*AllowExplicit=*/false,
11234 /*SuppressUserConversions=*/false,
11235 /*PartialOverloading*/ false,
11236 /*AggregateCandidateDeduction=*/false},
11238 FoundDecl,
11239 ActingContext,
11240 From,
11241 ToType};
11242}
11243
11244static void
11247
11249 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11250 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11251 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11252}
11253
11254static void
11258 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11259 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11260 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11261 C.AggregateCandidateDeduction);
11262}
11263
11264static void
11268 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11269 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11270 C.AllowResultConversion);
11271}
11272
11274 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11275 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11276 while (Cand) {
11277 switch (Cand->Kind) {
11280 S, *this,
11281 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11282 break;
11285 S, *this,
11286 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11287 break;
11290 S, *this,
11291 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11292 break;
11293 }
11294 Cand = Cand->Next;
11295 }
11296 FirstDeferredCandidate = nullptr;
11297 DeferredCandidatesCount = 0;
11298}
11299
11301OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11302 Best->Best = true;
11303 if (Best->Function && Best->Function->isDeleted())
11304 return OR_Deleted;
11305 return OR_Success;
11306}
11307
11308void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11310 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11311 // are accepted by both clang and NVCC. However, during a particular
11312 // compilation mode only one call variant is viable. We need to
11313 // exclude non-viable overload candidates from consideration based
11314 // only on their host/device attributes. Specifically, if one
11315 // candidate call is WrongSide and the other is SameSide, we ignore
11316 // the WrongSide candidate.
11317 // We only need to remove wrong-sided candidates here if
11318 // -fgpu-exclude-wrong-side-overloads is off. When
11319 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11320 // uniformly in isBetterOverloadCandidate.
11321 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11322 return;
11323 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11324
11325 bool ContainsSameSideCandidate =
11326 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11327 // Check viable function only.
11328 return Cand->Viable && Cand->Function &&
11329 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11331 });
11332
11333 if (!ContainsSameSideCandidate)
11334 return;
11335
11336 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11337 // Check viable function only to avoid unnecessary data copying/moving.
11338 return Cand->Viable && Cand->Function &&
11339 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11341 };
11342 llvm::erase_if(Candidates, IsWrongSideCandidate);
11343}
11344
11345/// Computes the best viable function (C++ 13.3.3)
11346/// within an overload candidate set.
11347///
11348/// \param Loc The location of the function name (or operator symbol) for
11349/// which overload resolution occurs.
11350///
11351/// \param Best If overload resolution was successful or found a deleted
11352/// function, \p Best points to the candidate function found.
11353///
11354/// \returns The result of overload resolution.
11356 SourceLocation Loc,
11357 iterator &Best) {
11358
11360 DeferredCandidatesCount == 0) &&
11361 "Unexpected deferred template candidates");
11362
11363 bool TwoPhaseResolution =
11364 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11365
11366 if (TwoPhaseResolution) {
11367 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11368 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11369 if (!(HasDeferredTemplateConstructors &&
11370 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11371 return Res;
11372 }
11373 }
11374
11376 return BestViableFunctionImpl(S, Loc, Best);
11377}
11378
11379OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11381
11383 Candidates.reserve(this->Candidates.size());
11384 std::transform(this->Candidates.begin(), this->Candidates.end(),
11385 std::back_inserter(Candidates),
11386 [](OverloadCandidate &Cand) { return &Cand; });
11387
11388 if (S.getLangOpts().CUDA)
11389 CudaExcludeWrongSideCandidates(S, Candidates);
11390
11391 Best = end();
11392 for (auto *Cand : Candidates) {
11393 Cand->Best = false;
11394 if (Cand->Viable) {
11395 if (Best == end() ||
11396 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11397 Best = Cand;
11398 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11399 // This candidate has constraint that we were unable to evaluate because
11400 // it referenced an expression that contained an error. Rather than fall
11401 // back onto a potentially unintended candidate (made worse by
11402 // subsuming constraints), treat this as 'no viable candidate'.
11403 Best = end();
11404 return OR_No_Viable_Function;
11405 }
11406 }
11407
11408 // If we didn't find any viable functions, abort.
11409 if (Best == end())
11410 return OR_No_Viable_Function;
11411
11412 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11413 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11414 PendingBest.push_back(&*Best);
11415 Best->Best = true;
11416
11417 // Make sure that this function is better than every other viable
11418 // function. If not, we have an ambiguity.
11419 while (!PendingBest.empty()) {
11420 auto *Curr = PendingBest.pop_back_val();
11421 for (auto *Cand : Candidates) {
11422 if (Cand->Viable && !Cand->Best &&
11423 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11424 PendingBest.push_back(Cand);
11425 Cand->Best = true;
11426
11428 Curr->Function))
11429 EquivalentCands.push_back(Cand->Function);
11430 else
11431 Best = end();
11432 }
11433 }
11434 }
11435
11436 if (Best == end())
11437 return OR_Ambiguous;
11438
11439 OverloadingResult R = ResultForBestCandidate(Best);
11440
11441 if (!EquivalentCands.empty())
11443 EquivalentCands);
11444 return R;
11445}
11446
11447namespace {
11448
11449enum OverloadCandidateKind {
11450 oc_function,
11451 oc_method,
11452 oc_reversed_binary_operator,
11453 oc_constructor,
11454 oc_implicit_default_constructor,
11455 oc_implicit_copy_constructor,
11456 oc_implicit_move_constructor,
11457 oc_implicit_copy_assignment,
11458 oc_implicit_move_assignment,
11459 oc_implicit_equality_comparison,
11460 oc_inherited_constructor
11461};
11462
11463enum OverloadCandidateSelect {
11464 ocs_non_template,
11465 ocs_template,
11466 ocs_described_template,
11467};
11468
11469static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11470ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11471 const FunctionDecl *Fn,
11473 std::string &Description) {
11474
11475 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11476 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11477 isTemplate = true;
11478 Description = S.getTemplateArgumentBindingsText(
11479 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11480 }
11481
11482 OverloadCandidateSelect Select = [&]() {
11483 if (!Description.empty())
11484 return ocs_described_template;
11485 return isTemplate ? ocs_template : ocs_non_template;
11486 }();
11487
11488 OverloadCandidateKind Kind = [&]() {
11489 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11490 return oc_implicit_equality_comparison;
11491
11492 if (CRK & CRK_Reversed)
11493 return oc_reversed_binary_operator;
11494
11495 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11496 if (!Ctor->isImplicit()) {
11498 return oc_inherited_constructor;
11499 else
11500 return oc_constructor;
11501 }
11502
11503 if (Ctor->isDefaultConstructor())
11504 return oc_implicit_default_constructor;
11505
11506 if (Ctor->isMoveConstructor())
11507 return oc_implicit_move_constructor;
11508
11509 assert(Ctor->isCopyConstructor() &&
11510 "unexpected sort of implicit constructor");
11511 return oc_implicit_copy_constructor;
11512 }
11513
11514 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11515 // This actually gets spelled 'candidate function' for now, but
11516 // it doesn't hurt to split it out.
11517 if (!Meth->isImplicit())
11518 return oc_method;
11519
11520 if (Meth->isMoveAssignmentOperator())
11521 return oc_implicit_move_assignment;
11522
11523 if (Meth->isCopyAssignmentOperator())
11524 return oc_implicit_copy_assignment;
11525
11526 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11527 return oc_method;
11528 }
11529
11530 return oc_function;
11531 }();
11532
11533 return std::make_pair(Kind, Select);
11534}
11535
11536void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11537 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11538 // set.
11539 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11540 S.Diag(FoundDecl->getLocation(),
11541 diag::note_ovl_candidate_inherited_constructor)
11542 << Shadow->getNominatedBaseClass();
11543}
11544
11545} // end anonymous namespace
11546
11548 const FunctionDecl *FD) {
11549 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11550 bool AlwaysTrue;
11551 if (EnableIf->getCond()->isValueDependent() ||
11552 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11553 return false;
11554 if (!AlwaysTrue)
11555 return false;
11556 }
11557 return true;
11558}
11559
11560/// Returns true if we can take the address of the function.
11561///
11562/// \param Complain - If true, we'll emit a diagnostic
11563/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11564/// we in overload resolution?
11565/// \param Loc - The location of the statement we're complaining about. Ignored
11566/// if we're not complaining, or if we're in overload resolution.
11568 bool Complain,
11569 bool InOverloadResolution,
11570 SourceLocation Loc) {
11571 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11572 if (Complain) {
11573 if (InOverloadResolution)
11574 S.Diag(FD->getBeginLoc(),
11575 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11576 else
11577 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11578 }
11579 return false;
11580 }
11581
11582 if (FD->getTrailingRequiresClause()) {
11583 ConstraintSatisfaction Satisfaction;
11584 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11585 return false;
11586 if (!Satisfaction.IsSatisfied) {
11587 if (Complain) {
11588 if (InOverloadResolution) {
11589 SmallString<128> TemplateArgString;
11590 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11591 TemplateArgString += " ";
11592 TemplateArgString += S.getTemplateArgumentBindingsText(
11593 FunTmpl->getTemplateParameters(),
11595 }
11596
11597 S.Diag(FD->getBeginLoc(),
11598 diag::note_ovl_candidate_unsatisfied_constraints)
11599 << TemplateArgString;
11600 } else
11601 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11602 << FD;
11603 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11604 }
11605 return false;
11606 }
11607 }
11608
11609 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11610 return P->hasAttr<PassObjectSizeAttr>();
11611 });
11612 if (I == FD->param_end())
11613 return true;
11614
11615 if (Complain) {
11616 // Add one to ParamNo because it's user-facing
11617 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11618 if (InOverloadResolution)
11619 S.Diag(FD->getLocation(),
11620 diag::note_ovl_candidate_has_pass_object_size_params)
11621 << ParamNo;
11622 else
11623 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11624 << FD << ParamNo;
11625 }
11626 return false;
11627}
11628
11630 const FunctionDecl *FD) {
11631 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11632 /*InOverloadResolution=*/true,
11633 /*Loc=*/SourceLocation());
11634}
11635
11637 bool Complain,
11638 SourceLocation Loc) {
11639 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11640 /*InOverloadResolution=*/false,
11641 Loc);
11642}
11643
11644// Don't print candidates other than the one that matches the calling
11645// convention of the call operator, since that is guaranteed to exist.
11647 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11648
11649 if (!ConvD)
11650 return false;
11651 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11652 if (!RD->isLambda())
11653 return false;
11654
11655 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11656 CallingConv CallOpCC =
11657 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11658 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11659 CallingConv ConvToCC =
11660 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11661
11662 return ConvToCC != CallOpCC;
11663}
11664
11665// Notes the location of an overload candidate.
11667 OverloadCandidateRewriteKind RewriteKind,
11668 QualType DestType, bool TakingAddress) {
11669 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11670 return;
11671 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11672 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11673 return;
11674 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11675 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11676 return;
11678 return;
11679
11680 std::string FnDesc;
11681 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11682 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11683 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11684 << (unsigned)KSPair.first << (unsigned)KSPair.second
11685 << Fn << FnDesc;
11686
11687 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11688 Diag(Fn->getLocation(), PD);
11689 MaybeEmitInheritedConstructorNote(*this, Found);
11690}
11691
11692static void
11694 // Perhaps the ambiguity was caused by two atomic constraints that are
11695 // 'identical' but not equivalent:
11696 //
11697 // void foo() requires (sizeof(T) > 4) { } // #1
11698 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11699 //
11700 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11701 // #2 to subsume #1, but these constraint are not considered equivalent
11702 // according to the subsumption rules because they are not the same
11703 // source-level construct. This behavior is quite confusing and we should try
11704 // to help the user figure out what happened.
11705
11706 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11707 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11708 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11709 if (!I->Function)
11710 continue;
11712 if (auto *Template = I->Function->getPrimaryTemplate())
11713 Template->getAssociatedConstraints(AC);
11714 else
11715 I->Function->getAssociatedConstraints(AC);
11716 if (AC.empty())
11717 continue;
11718 if (FirstCand == nullptr) {
11719 FirstCand = I->Function;
11720 FirstAC = AC;
11721 } else if (SecondCand == nullptr) {
11722 SecondCand = I->Function;
11723 SecondAC = AC;
11724 } else {
11725 // We have more than one pair of constrained functions - this check is
11726 // expensive and we'd rather not try to diagnose it.
11727 return;
11728 }
11729 }
11730 if (!SecondCand)
11731 return;
11732 // The diagnostic can only happen if there are associated constraints on
11733 // both sides (there needs to be some identical atomic constraint).
11734 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11735 SecondCand, SecondAC))
11736 // Just show the user one diagnostic, they'll probably figure it out
11737 // from here.
11738 return;
11739}
11740
11741// Notes the location of all overload candidates designated through
11742// OverloadedExpr
11743void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11744 bool TakingAddress) {
11745 assert(OverloadedExpr->getType() == Context.OverloadTy);
11746
11747 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11748 OverloadExpr *OvlExpr = Ovl.Expression;
11749
11750 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11751 IEnd = OvlExpr->decls_end();
11752 I != IEnd; ++I) {
11753 if (FunctionTemplateDecl *FunTmpl =
11754 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11755 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11756 TakingAddress);
11757 } else if (FunctionDecl *Fun
11758 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11759 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11760 }
11761 }
11762}
11763
11764/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11765/// "lead" diagnostic; it will be given two arguments, the source and
11766/// target types of the conversion.
11768 Sema &S,
11769 SourceLocation CaretLoc,
11770 const PartialDiagnostic &PDiag) const {
11771 S.Diag(CaretLoc, PDiag)
11772 << Ambiguous.getFromType() << Ambiguous.getToType();
11773 unsigned CandsShown = 0;
11775 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11776 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11777 break;
11778 ++CandsShown;
11779 S.NoteOverloadCandidate(I->first, I->second);
11780 }
11781 S.Diags.overloadCandidatesShown(CandsShown);
11782 if (I != E)
11783 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11784}
11785
11787 unsigned I, bool TakingCandidateAddress) {
11788 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11789 assert(Conv.isBad());
11790 assert(Cand->Function && "for now, candidate must be a function");
11791 FunctionDecl *Fn = Cand->Function;
11792
11793 // There's a conversion slot for the object argument if this is a
11794 // non-constructor method. Note that 'I' corresponds the
11795 // conversion-slot index.
11796 bool isObjectArgument = false;
11797 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11799 if (I == 0)
11800 isObjectArgument = true;
11801 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11802 I--;
11803 }
11804
11805 std::string FnDesc;
11806 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11807 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11808 FnDesc);
11809
11810 Expr *FromExpr = Conv.Bad.FromExpr;
11811 QualType FromTy = Conv.Bad.getFromType();
11812 QualType ToTy = Conv.Bad.getToType();
11813 SourceRange ToParamRange;
11814
11815 // FIXME: In presence of parameter packs we can't determine parameter range
11816 // reliably, as we don't have access to instantiation.
11817 bool HasParamPack =
11818 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11819 return Parm->isParameterPack();
11820 });
11821 if (!isObjectArgument && !HasParamPack)
11822 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11823
11824 if (FromTy == S.Context.OverloadTy) {
11825 assert(FromExpr && "overload set argument came from implicit argument?");
11826 Expr *E = FromExpr->IgnoreParens();
11827 if (isa<UnaryOperator>(E))
11828 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11829 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11830
11831 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11832 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11833 << ToParamRange << ToTy << Name << I + 1;
11834 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11835 return;
11836 }
11837
11838 // Do some hand-waving analysis to see if the non-viability is due
11839 // to a qualifier mismatch.
11840 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11841 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11842 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11843 CToTy = RT->getPointeeType();
11844 else {
11845 // TODO: detect and diagnose the full richness of const mismatches.
11846 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11847 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11848 CFromTy = FromPT->getPointeeType();
11849 CToTy = ToPT->getPointeeType();
11850 }
11851 }
11852
11853 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11854 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11855 Qualifiers FromQs = CFromTy.getQualifiers();
11856 Qualifiers ToQs = CToTy.getQualifiers();
11857
11858 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11859 if (isObjectArgument)
11860 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11861 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11862 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11863 else
11864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11865 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11866 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11867 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11868 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11869 return;
11870 }
11871
11872 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11873 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11874 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11875 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11876 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11877 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11878 return;
11879 }
11880
11881 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11882 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11883 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11884 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11885 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11886 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11887 return;
11888 }
11889
11890 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11891 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11892 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11893 << FromTy << !!FromQs.getPointerAuth()
11894 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11895 << ToQs.getPointerAuth().getAsString() << I + 1
11896 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11897 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11898 return;
11899 }
11900
11901 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11902 assert(CVR && "expected qualifiers mismatch");
11903
11904 if (isObjectArgument) {
11905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11906 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11907 << FromTy << (CVR - 1);
11908 } else {
11909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11910 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11911 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11912 }
11913 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11914 return;
11915 }
11916
11919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11920 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11921 << (unsigned)isObjectArgument << I + 1
11923 << ToParamRange;
11924 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11925 return;
11926 }
11927
11928 // Special diagnostic for failure to convert an initializer list, since
11929 // telling the user that it has type void is not useful.
11930 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11931 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11932 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11933 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11936 ? 2
11937 : 0);
11938 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11939 return;
11940 }
11941
11942 // Diagnose references or pointers to incomplete types differently,
11943 // since it's far from impossible that the incompleteness triggered
11944 // the failure.
11945 QualType TempFromTy = FromTy.getNonReferenceType();
11946 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11947 TempFromTy = PTy->getPointeeType();
11948 if (TempFromTy->isIncompleteType()) {
11949 // Emit the generic diagnostic and, optionally, add the hints to it.
11950 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11951 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11952 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11953 << (unsigned)(Cand->Fix.Kind);
11954
11955 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11956 return;
11957 }
11958
11959 // Diagnose base -> derived pointer conversions.
11960 unsigned BaseToDerivedConversion = 0;
11961 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11962 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11963 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11964 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11965 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11966 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11967 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11968 FromPtrTy->getPointeeType()))
11969 BaseToDerivedConversion = 1;
11970 }
11971 } else if (const ObjCObjectPointerType *FromPtrTy
11972 = FromTy->getAs<ObjCObjectPointerType>()) {
11973 if (const ObjCObjectPointerType *ToPtrTy
11974 = ToTy->getAs<ObjCObjectPointerType>())
11975 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11976 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11977 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11978 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11979 FromIface->isSuperClassOf(ToIface))
11980 BaseToDerivedConversion = 2;
11981 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11982 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11983 S.getASTContext()) &&
11984 !FromTy->isIncompleteType() &&
11985 !ToRefTy->getPointeeType()->isIncompleteType() &&
11986 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11987 BaseToDerivedConversion = 3;
11988 }
11989 }
11990
11991 if (BaseToDerivedConversion) {
11992 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11993 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11994 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11995 << I + 1;
11996 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11997 return;
11998 }
11999
12000 if (isa<ObjCObjectPointerType>(CFromTy) &&
12001 isa<PointerType>(CToTy)) {
12002 Qualifiers FromQs = CFromTy.getQualifiers();
12003 Qualifiers ToQs = CToTy.getQualifiers();
12004 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12005 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12006 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12007 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12008 << I + 1;
12009 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12010 return;
12011 }
12012 }
12013
12014 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12015 return;
12016
12017 // Emit the generic diagnostic and, optionally, add the hints to it.
12018 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12019 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12020 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12021 << (unsigned)(Cand->Fix.Kind);
12022
12023 // Check that location of Fn is not in system header.
12024 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12025 // If we can fix the conversion, suggest the FixIts.
12026 for (const FixItHint &HI : Cand->Fix.Hints)
12027 FDiag << HI;
12028 }
12029
12030 S.Diag(Fn->getLocation(), FDiag);
12031
12032 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12033}
12034
12035/// Additional arity mismatch diagnosis specific to a function overload
12036/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12037/// over a candidate in any candidate set.
12039 unsigned NumArgs, bool IsAddressOf = false) {
12040 assert(Cand->Function && "Candidate is required to be a function.");
12041 FunctionDecl *Fn = Cand->Function;
12042 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12043 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12044
12045 // With invalid overloaded operators, it's possible that we think we
12046 // have an arity mismatch when in fact it looks like we have the
12047 // right number of arguments, because only overloaded operators have
12048 // the weird behavior of overloading member and non-member functions.
12049 // Just don't report anything.
12050 if (Fn->isInvalidDecl() &&
12051 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12052 return true;
12053
12054 if (NumArgs < MinParams) {
12055 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12057 Cand->DeductionFailure.getResult() ==
12059 } else {
12060 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12062 Cand->DeductionFailure.getResult() ==
12064 }
12065
12066 return false;
12067}
12068
12069/// General arity mismatch diagnosis over a candidate in a candidate set.
12071 unsigned NumFormalArgs,
12072 bool IsAddressOf = false) {
12073 assert(isa<FunctionDecl>(D) &&
12074 "The templated declaration should at least be a function"
12075 " when diagnosing bad template argument deduction due to too many"
12076 " or too few arguments");
12077
12079
12080 // TODO: treat calls to a missing default constructor as a special case
12081 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12082 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12083 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12084
12085 // at least / at most / exactly
12086 bool HasExplicitObjectParam =
12087 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12088
12089 unsigned ParamCount =
12090 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12091 unsigned mode, modeCount;
12092
12093 if (NumFormalArgs < MinParams) {
12094 if (MinParams != ParamCount || FnTy->isVariadic() ||
12095 FnTy->isTemplateVariadic())
12096 mode = 0; // "at least"
12097 else
12098 mode = 2; // "exactly"
12099 modeCount = MinParams;
12100 } else {
12101 if (MinParams != ParamCount)
12102 mode = 1; // "at most"
12103 else
12104 mode = 2; // "exactly"
12105 modeCount = ParamCount;
12106 }
12107
12108 std::string Description;
12109 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12110 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12111
12112 if (modeCount == 1 && !IsAddressOf &&
12113 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12114 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12115 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12116 << Description << mode
12117 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12118 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12119 else
12120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12121 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12122 << Description << mode << modeCount << NumFormalArgs
12123 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12124
12125 MaybeEmitInheritedConstructorNote(S, Found);
12126}
12127
12128/// Arity mismatch diagnosis specific to a function overload candidate.
12130 unsigned NumFormalArgs) {
12131 assert(Cand->Function && "Candidate must be a function");
12132 FunctionDecl *Fn = Cand->Function;
12133 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12134 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12135 Cand->TookAddressOfOverload);
12136}
12137
12139 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12140 return TD;
12141 llvm_unreachable("Unsupported: Getting the described template declaration"
12142 " for bad deduction diagnosis");
12143}
12144
12145/// Diagnose a failed template-argument deduction.
12146static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12147 DeductionFailureInfo &DeductionFailure,
12148 unsigned NumArgs,
12149 bool TakingCandidateAddress) {
12150 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12151 NamedDecl *ParamD;
12152 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12153 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12154 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12155 switch (DeductionFailure.getResult()) {
12157 llvm_unreachable(
12158 "TemplateDeductionResult::Success while diagnosing bad deduction");
12160 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12161 "while diagnosing bad deduction");
12164 return;
12165
12167 assert(ParamD && "no parameter found for incomplete deduction result");
12168 S.Diag(Templated->getLocation(),
12169 diag::note_ovl_candidate_incomplete_deduction)
12170 << ParamD->getDeclName();
12171 MaybeEmitInheritedConstructorNote(S, Found);
12172 return;
12173 }
12174
12176 assert(ParamD && "no parameter found for incomplete deduction result");
12177 S.Diag(Templated->getLocation(),
12178 diag::note_ovl_candidate_incomplete_deduction_pack)
12179 << ParamD->getDeclName()
12180 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12181 << *DeductionFailure.getFirstArg();
12182 MaybeEmitInheritedConstructorNote(S, Found);
12183 return;
12184 }
12185
12187 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12189
12190 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12191
12192 // Param will have been canonicalized, but it should just be a
12193 // qualified version of ParamD, so move the qualifiers to that.
12195 Qs.strip(Param);
12196 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12197 assert(S.Context.hasSameType(Param, NonCanonParam));
12198
12199 // Arg has also been canonicalized, but there's nothing we can do
12200 // about that. It also doesn't matter as much, because it won't
12201 // have any template parameters in it (because deduction isn't
12202 // done on dependent types).
12203 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12204
12205 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12206 << ParamD->getDeclName() << Arg << NonCanonParam;
12207 MaybeEmitInheritedConstructorNote(S, Found);
12208 return;
12209 }
12210
12212 assert(ParamD && "no parameter found for inconsistent deduction result");
12213 int which = 0;
12214 if (isa<TemplateTypeParmDecl>(ParamD))
12215 which = 0;
12216 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12217 // Deduction might have failed because we deduced arguments of two
12218 // different types for a non-type template parameter.
12219 // FIXME: Use a different TDK value for this.
12220 QualType T1 =
12221 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12222 QualType T2 =
12223 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12224 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12225 S.Diag(Templated->getLocation(),
12226 diag::note_ovl_candidate_inconsistent_deduction_types)
12227 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12228 << *DeductionFailure.getSecondArg() << T2;
12229 MaybeEmitInheritedConstructorNote(S, Found);
12230 return;
12231 }
12232
12233 which = 1;
12234 } else {
12235 which = 2;
12236 }
12237
12238 // Tweak the diagnostic if the problem is that we deduced packs of
12239 // different arities. We'll print the actual packs anyway in case that
12240 // includes additional useful information.
12241 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12242 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12243 DeductionFailure.getFirstArg()->pack_size() !=
12244 DeductionFailure.getSecondArg()->pack_size()) {
12245 which = 3;
12246 }
12247
12248 S.Diag(Templated->getLocation(),
12249 diag::note_ovl_candidate_inconsistent_deduction)
12250 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12251 << *DeductionFailure.getSecondArg();
12252 MaybeEmitInheritedConstructorNote(S, Found);
12253 return;
12254 }
12255
12257 assert(ParamD && "no parameter found for invalid explicit arguments");
12258 if (ParamD->getDeclName())
12259 S.Diag(Templated->getLocation(),
12260 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12261 << ParamD->getDeclName();
12262 else {
12263 int index = 0;
12264 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12265 index = TTP->getIndex();
12266 else if (NonTypeTemplateParmDecl *NTTP
12267 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12268 index = NTTP->getIndex();
12269 else
12270 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12271 S.Diag(Templated->getLocation(),
12272 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12273 << (index + 1);
12274 }
12275 MaybeEmitInheritedConstructorNote(S, Found);
12276 return;
12277
12279 // Format the template argument list into the argument string.
12280 SmallString<128> TemplateArgString;
12281 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12282 TemplateArgString = " ";
12283 TemplateArgString += S.getTemplateArgumentBindingsText(
12284 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12285 if (TemplateArgString.size() == 1)
12286 TemplateArgString.clear();
12287 S.Diag(Templated->getLocation(),
12288 diag::note_ovl_candidate_unsatisfied_constraints)
12289 << TemplateArgString;
12290
12292 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12293 return;
12294 }
12297 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12298 return;
12299
12301 S.Diag(Templated->getLocation(),
12302 diag::note_ovl_candidate_instantiation_depth);
12303 MaybeEmitInheritedConstructorNote(S, Found);
12304 return;
12305
12307 // Format the template argument list into the argument string.
12308 SmallString<128> TemplateArgString;
12309 if (TemplateArgumentList *Args =
12310 DeductionFailure.getTemplateArgumentList()) {
12311 TemplateArgString = " ";
12312 TemplateArgString += S.getTemplateArgumentBindingsText(
12313 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12314 if (TemplateArgString.size() == 1)
12315 TemplateArgString.clear();
12316 }
12317
12318 // If this candidate was disabled by enable_if, say so.
12319 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12320 if (PDiag && PDiag->second.getDiagID() ==
12321 diag::err_typename_nested_not_found_enable_if) {
12322 // FIXME: Use the source range of the condition, and the fully-qualified
12323 // name of the enable_if template. These are both present in PDiag.
12324 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12325 << "'enable_if'" << TemplateArgString;
12326 return;
12327 }
12328
12329 // We found a specific requirement that disabled the enable_if.
12330 if (PDiag && PDiag->second.getDiagID() ==
12331 diag::err_typename_nested_not_found_requirement) {
12332 S.Diag(Templated->getLocation(),
12333 diag::note_ovl_candidate_disabled_by_requirement)
12334 << PDiag->second.getStringArg(0) << TemplateArgString;
12335 return;
12336 }
12337
12338 // Format the SFINAE diagnostic into the argument string.
12339 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12340 // formatted message in another diagnostic.
12341 SmallString<128> SFINAEArgString;
12342 SourceRange R;
12343 if (PDiag) {
12344 SFINAEArgString = ": ";
12345 R = SourceRange(PDiag->first, PDiag->first);
12346 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12347 }
12348
12349 S.Diag(Templated->getLocation(),
12350 diag::note_ovl_candidate_substitution_failure)
12351 << TemplateArgString << SFINAEArgString << R;
12352 MaybeEmitInheritedConstructorNote(S, Found);
12353 return;
12354 }
12355
12358 // Format the template argument list into the argument string.
12359 SmallString<128> TemplateArgString;
12360 if (TemplateArgumentList *Args =
12361 DeductionFailure.getTemplateArgumentList()) {
12362 TemplateArgString = " ";
12363 TemplateArgString += S.getTemplateArgumentBindingsText(
12364 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12365 if (TemplateArgString.size() == 1)
12366 TemplateArgString.clear();
12367 }
12368
12369 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12370 << (*DeductionFailure.getCallArgIndex() + 1)
12371 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12372 << TemplateArgString
12373 << (DeductionFailure.getResult() ==
12375 break;
12376 }
12377
12379 // FIXME: Provide a source location to indicate what we couldn't match.
12380 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12381 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12382 if (FirstTA.getKind() == TemplateArgument::Template &&
12383 SecondTA.getKind() == TemplateArgument::Template) {
12384 TemplateName FirstTN = FirstTA.getAsTemplate();
12385 TemplateName SecondTN = SecondTA.getAsTemplate();
12386 if (FirstTN.getKind() == TemplateName::Template &&
12387 SecondTN.getKind() == TemplateName::Template) {
12388 if (FirstTN.getAsTemplateDecl()->getName() ==
12389 SecondTN.getAsTemplateDecl()->getName()) {
12390 // FIXME: This fixes a bad diagnostic where both templates are named
12391 // the same. This particular case is a bit difficult since:
12392 // 1) It is passed as a string to the diagnostic printer.
12393 // 2) The diagnostic printer only attempts to find a better
12394 // name for types, not decls.
12395 // Ideally, this should folded into the diagnostic printer.
12396 S.Diag(Templated->getLocation(),
12397 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12398 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12399 return;
12400 }
12401 }
12402 }
12403
12404 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12406 return;
12407
12408 // FIXME: For generic lambda parameters, check if the function is a lambda
12409 // call operator, and if so, emit a prettier and more informative
12410 // diagnostic that mentions 'auto' and lambda in addition to
12411 // (or instead of?) the canonical template type parameters.
12412 S.Diag(Templated->getLocation(),
12413 diag::note_ovl_candidate_non_deduced_mismatch)
12414 << FirstTA << SecondTA;
12415 return;
12416 }
12417 // TODO: diagnose these individually, then kill off
12418 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12420 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12421 MaybeEmitInheritedConstructorNote(S, Found);
12422 return;
12424 S.Diag(Templated->getLocation(),
12425 diag::note_cuda_ovl_candidate_target_mismatch);
12426 return;
12427 }
12428}
12429
12430/// Diagnose a failed template-argument deduction, for function calls.
12432 unsigned NumArgs,
12433 bool TakingCandidateAddress) {
12434 assert(Cand->Function && "Candidate must be a function");
12435 FunctionDecl *Fn = Cand->Function;
12439 if (CheckArityMismatch(S, Cand, NumArgs))
12440 return;
12441 }
12442 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12443 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12444}
12445
12446/// CUDA: diagnose an invalid call across targets.
12448 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12449 assert(Cand->Function && "Candidate must be a Function.");
12450 FunctionDecl *Callee = Cand->Function;
12451
12452 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12453 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12454
12455 std::string FnDesc;
12456 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12457 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12458 Cand->getRewriteKind(), FnDesc);
12459
12460 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12461 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12462 << FnDesc /* Ignored */
12463 << CalleeTarget << CallerTarget;
12464
12465 // This could be an implicit constructor for which we could not infer the
12466 // target due to a collsion. Diagnose that case.
12467 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12468 if (Meth != nullptr && Meth->isImplicit()) {
12469 CXXRecordDecl *ParentClass = Meth->getParent();
12471
12472 switch (FnKindPair.first) {
12473 default:
12474 return;
12475 case oc_implicit_default_constructor:
12477 break;
12478 case oc_implicit_copy_constructor:
12480 break;
12481 case oc_implicit_move_constructor:
12483 break;
12484 case oc_implicit_copy_assignment:
12486 break;
12487 case oc_implicit_move_assignment:
12489 break;
12490 };
12491
12492 bool ConstRHS = false;
12493 if (Meth->getNumParams()) {
12494 if (const ReferenceType *RT =
12495 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12496 ConstRHS = RT->getPointeeType().isConstQualified();
12497 }
12498 }
12499
12500 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12501 /* ConstRHS */ ConstRHS,
12502 /* Diagnose */ true);
12503 }
12504}
12505
12507 assert(Cand->Function && "Candidate must be a function");
12508 FunctionDecl *Callee = Cand->Function;
12509 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12510
12511 S.Diag(Callee->getLocation(),
12512 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12513 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12514}
12515
12517 assert(Cand->Function && "Candidate must be a function");
12518 FunctionDecl *Fn = Cand->Function;
12520 assert(ES.isExplicit() && "not an explicit candidate");
12521
12522 unsigned Kind;
12523 switch (Fn->getDeclKind()) {
12524 case Decl::Kind::CXXConstructor:
12525 Kind = 0;
12526 break;
12527 case Decl::Kind::CXXConversion:
12528 Kind = 1;
12529 break;
12530 case Decl::Kind::CXXDeductionGuide:
12531 Kind = Fn->isImplicit() ? 0 : 2;
12532 break;
12533 default:
12534 llvm_unreachable("invalid Decl");
12535 }
12536
12537 // Note the location of the first (in-class) declaration; a redeclaration
12538 // (particularly an out-of-class definition) will typically lack the
12539 // 'explicit' specifier.
12540 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12541 FunctionDecl *First = Fn->getFirstDecl();
12542 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12543 First = Pattern->getFirstDecl();
12544
12545 S.Diag(First->getLocation(),
12546 diag::note_ovl_candidate_explicit)
12547 << Kind << (ES.getExpr() ? 1 : 0)
12548 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12549}
12550
12552 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12553 if (!DG)
12554 return;
12555 TemplateDecl *OriginTemplate =
12557 // We want to always print synthesized deduction guides for type aliases.
12558 // They would retain the explicit bit of the corresponding constructor.
12559 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12560 return;
12561 std::string FunctionProto;
12562 llvm::raw_string_ostream OS(FunctionProto);
12563 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12564 if (!Template) {
12565 // This also could be an instantiation. Find out the primary template.
12566 FunctionDecl *Pattern =
12567 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12568 if (!Pattern) {
12569 // The implicit deduction guide is built on an explicit non-template
12570 // deduction guide. Currently, this might be the case only for type
12571 // aliases.
12572 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12573 // gets merged.
12574 assert(OriginTemplate->isTypeAlias() &&
12575 "Non-template implicit deduction guides are only possible for "
12576 "type aliases");
12577 DG->print(OS);
12578 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12579 << FunctionProto;
12580 return;
12581 }
12583 assert(Template && "Cannot find the associated function template of "
12584 "CXXDeductionGuideDecl?");
12585 }
12586 Template->print(OS);
12587 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12588 << FunctionProto;
12589}
12590
12591/// Generates a 'note' diagnostic for an overload candidate. We've
12592/// already generated a primary error at the call site.
12593///
12594/// It really does need to be a single diagnostic with its caret
12595/// pointed at the candidate declaration. Yes, this creates some
12596/// major challenges of technical writing. Yes, this makes pointing
12597/// out problems with specific arguments quite awkward. It's still
12598/// better than generating twenty screens of text for every failed
12599/// overload.
12600///
12601/// It would be great to be able to express per-candidate problems
12602/// more richly for those diagnostic clients that cared, but we'd
12603/// still have to be just as careful with the default diagnostics.
12604/// \param CtorDestAS Addr space of object being constructed (for ctor
12605/// candidates only).
12607 unsigned NumArgs,
12608 bool TakingCandidateAddress,
12609 LangAS CtorDestAS = LangAS::Default) {
12610 assert(Cand->Function && "Candidate must be a function");
12611 FunctionDecl *Fn = Cand->Function;
12613 return;
12614
12615 // There is no physical candidate declaration to point to for OpenCL builtins.
12616 // Except for failed conversions, the notes are identical for each candidate,
12617 // so do not generate such notes.
12618 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12620 return;
12621
12622 // Skip implicit member functions when trying to resolve
12623 // the address of a an overload set for a function pointer.
12624 if (Cand->TookAddressOfOverload &&
12625 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12626 return;
12627
12628 // Note deleted candidates, but only if they're viable.
12629 if (Cand->Viable) {
12630 if (Fn->isDeleted()) {
12631 std::string FnDesc;
12632 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12633 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12634 Cand->getRewriteKind(), FnDesc);
12635
12636 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12637 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12638 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12639 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12640 return;
12641 }
12642
12643 // We don't really have anything else to say about viable candidates.
12644 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12645 return;
12646 }
12647
12648 // If this is a synthesized deduction guide we're deducing against, add a note
12649 // for it. These deduction guides are not explicitly spelled in the source
12650 // code, so simply printing a deduction failure note mentioning synthesized
12651 // template parameters or pointing to the header of the surrounding RecordDecl
12652 // would be confusing.
12653 //
12654 // We prefer adding such notes at the end of the deduction failure because
12655 // duplicate code snippets appearing in the diagnostic would likely become
12656 // noisy.
12657 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12658
12659 switch (Cand->FailureKind) {
12662 return DiagnoseArityMismatch(S, Cand, NumArgs);
12663
12665 return DiagnoseBadDeduction(S, Cand, NumArgs,
12666 TakingCandidateAddress);
12667
12669 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12670 << (Fn->getPrimaryTemplate() ? 1 : 0);
12671 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12672 return;
12673 }
12674
12676 Qualifiers QualsForPrinting;
12677 QualsForPrinting.setAddressSpace(CtorDestAS);
12678 S.Diag(Fn->getLocation(),
12679 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12680 << QualsForPrinting;
12681 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12682 return;
12683 }
12684
12688 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12689
12691 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12692 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12693 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12694 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12695
12696 // FIXME: this currently happens when we're called from SemaInit
12697 // when user-conversion overload fails. Figure out how to handle
12698 // those conditions and diagnose them well.
12699 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12700 }
12701
12703 return DiagnoseBadTarget(S, Cand);
12704
12705 case ovl_fail_enable_if:
12706 return DiagnoseFailedEnableIfAttr(S, Cand);
12707
12708 case ovl_fail_explicit:
12709 return DiagnoseFailedExplicitSpec(S, Cand);
12710
12712 // It's generally not interesting to note copy/move constructors here.
12713 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12714 return;
12715 S.Diag(Fn->getLocation(),
12716 diag::note_ovl_candidate_inherited_constructor_slice)
12717 << (Fn->getPrimaryTemplate() ? 1 : 0)
12718 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12719 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12720 return;
12721
12723 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12724 (void)Available;
12725 assert(!Available);
12726 break;
12727 }
12729 // Do nothing, these should simply be ignored.
12730 break;
12731
12733 std::string FnDesc;
12734 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12735 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12736 Cand->getRewriteKind(), FnDesc);
12737
12738 S.Diag(Fn->getLocation(),
12739 diag::note_ovl_candidate_constraints_not_satisfied)
12740 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12741 << FnDesc /* Ignored */;
12742 ConstraintSatisfaction Satisfaction;
12743 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12744 /*ForOverloadResolution=*/true))
12745 break;
12746 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12747 }
12748 }
12749}
12750
12753 return;
12754
12755 // Desugar the type of the surrogate down to a function type,
12756 // retaining as many typedefs as possible while still showing
12757 // the function type (and, therefore, its parameter types).
12758 QualType FnType = Cand->Surrogate->getConversionType();
12759 bool isLValueReference = false;
12760 bool isRValueReference = false;
12761 bool isPointer = false;
12762 if (const LValueReferenceType *FnTypeRef =
12763 FnType->getAs<LValueReferenceType>()) {
12764 FnType = FnTypeRef->getPointeeType();
12765 isLValueReference = true;
12766 } else if (const RValueReferenceType *FnTypeRef =
12767 FnType->getAs<RValueReferenceType>()) {
12768 FnType = FnTypeRef->getPointeeType();
12769 isRValueReference = true;
12770 }
12771 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12772 FnType = FnTypePtr->getPointeeType();
12773 isPointer = true;
12774 }
12775 // Desugar down to a function type.
12776 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12777 // Reconstruct the pointer/reference as appropriate.
12778 if (isPointer) FnType = S.Context.getPointerType(FnType);
12779 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12780 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12781
12782 if (!Cand->Viable &&
12784 S.Diag(Cand->Surrogate->getLocation(),
12785 diag::note_ovl_surrogate_constraints_not_satisfied)
12786 << Cand->Surrogate;
12787 ConstraintSatisfaction Satisfaction;
12788 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12789 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12790 } else {
12791 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12792 << FnType;
12793 }
12794}
12795
12796static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12797 SourceLocation OpLoc,
12798 OverloadCandidate *Cand) {
12799 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12800 std::string TypeStr("operator");
12801 TypeStr += Opc;
12802 TypeStr += "(";
12803 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12804 if (Cand->Conversions.size() == 1) {
12805 TypeStr += ")";
12806 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12807 } else {
12808 TypeStr += ", ";
12809 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12810 TypeStr += ")";
12811 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12812 }
12813}
12814
12816 OverloadCandidate *Cand) {
12817 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12818 if (ICS.isBad()) break; // all meaningless after first invalid
12819 if (!ICS.isAmbiguous()) continue;
12820
12822 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12823 }
12824}
12825
12827 if (Cand->Function)
12828 return Cand->Function->getLocation();
12829 if (Cand->IsSurrogate)
12830 return Cand->Surrogate->getLocation();
12831 return SourceLocation();
12832}
12833
12834static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12835 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12839 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12840
12844 return 1;
12845
12848 return 2;
12849
12857 return 3;
12858
12860 return 4;
12861
12863 return 5;
12864
12867 return 6;
12868 }
12869 llvm_unreachable("Unhandled deduction result");
12870}
12871
12872namespace {
12873
12874struct CompareOverloadCandidatesForDisplay {
12875 Sema &S;
12876 SourceLocation Loc;
12877 size_t NumArgs;
12879
12880 CompareOverloadCandidatesForDisplay(
12881 Sema &S, SourceLocation Loc, size_t NArgs,
12883 : S(S), NumArgs(NArgs), CSK(CSK) {}
12884
12885 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12886 // If there are too many or too few arguments, that's the high-order bit we
12887 // want to sort by, even if the immediate failure kind was something else.
12888 if (C->FailureKind == ovl_fail_too_many_arguments ||
12889 C->FailureKind == ovl_fail_too_few_arguments)
12890 return static_cast<OverloadFailureKind>(C->FailureKind);
12891
12892 if (C->Function) {
12893 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12895 if (NumArgs < C->Function->getMinRequiredArguments())
12897 }
12898
12899 return static_cast<OverloadFailureKind>(C->FailureKind);
12900 }
12901
12902 bool operator()(const OverloadCandidate *L,
12903 const OverloadCandidate *R) {
12904 // Fast-path this check.
12905 if (L == R) return false;
12906
12907 // Order first by viability.
12908 if (L->Viable) {
12909 if (!R->Viable) return true;
12910
12911 if (int Ord = CompareConversions(*L, *R))
12912 return Ord < 0;
12913 // Use other tie breakers.
12914 } else if (R->Viable)
12915 return false;
12916
12917 assert(L->Viable == R->Viable);
12918
12919 // Criteria by which we can sort non-viable candidates:
12920 if (!L->Viable) {
12921 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12922 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12923
12924 // 1. Arity mismatches come after other candidates.
12925 if (LFailureKind == ovl_fail_too_many_arguments ||
12926 LFailureKind == ovl_fail_too_few_arguments) {
12927 if (RFailureKind == ovl_fail_too_many_arguments ||
12928 RFailureKind == ovl_fail_too_few_arguments) {
12929 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12930 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12931 if (LDist == RDist) {
12932 if (LFailureKind == RFailureKind)
12933 // Sort non-surrogates before surrogates.
12934 return !L->IsSurrogate && R->IsSurrogate;
12935 // Sort candidates requiring fewer parameters than there were
12936 // arguments given after candidates requiring more parameters
12937 // than there were arguments given.
12938 return LFailureKind == ovl_fail_too_many_arguments;
12939 }
12940 return LDist < RDist;
12941 }
12942 return false;
12943 }
12944 if (RFailureKind == ovl_fail_too_many_arguments ||
12945 RFailureKind == ovl_fail_too_few_arguments)
12946 return true;
12947
12948 // 2. Bad conversions come first and are ordered by the number
12949 // of bad conversions and quality of good conversions.
12950 if (LFailureKind == ovl_fail_bad_conversion) {
12951 if (RFailureKind != ovl_fail_bad_conversion)
12952 return true;
12953
12954 // The conversion that can be fixed with a smaller number of changes,
12955 // comes first.
12956 unsigned numLFixes = L->Fix.NumConversionsFixed;
12957 unsigned numRFixes = R->Fix.NumConversionsFixed;
12958 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12959 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12960 if (numLFixes != numRFixes) {
12961 return numLFixes < numRFixes;
12962 }
12963
12964 // If there's any ordering between the defined conversions...
12965 if (int Ord = CompareConversions(*L, *R))
12966 return Ord < 0;
12967 } else if (RFailureKind == ovl_fail_bad_conversion)
12968 return false;
12969
12970 if (LFailureKind == ovl_fail_bad_deduction) {
12971 if (RFailureKind != ovl_fail_bad_deduction)
12972 return true;
12973
12975 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12976 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12977 if (LRank != RRank)
12978 return LRank < RRank;
12979 }
12980 } else if (RFailureKind == ovl_fail_bad_deduction)
12981 return false;
12982
12983 // TODO: others?
12984 }
12985
12986 // Sort everything else by location.
12987 SourceLocation LLoc = GetLocationForCandidate(L);
12988 SourceLocation RLoc = GetLocationForCandidate(R);
12989
12990 // Put candidates without locations (e.g. builtins) at the end.
12991 if (LLoc.isValid() && RLoc.isValid())
12992 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12993 if (LLoc.isValid() && !RLoc.isValid())
12994 return true;
12995 if (RLoc.isValid() && !LLoc.isValid())
12996 return false;
12997 assert(!LLoc.isValid() && !RLoc.isValid());
12998 // For builtins and other functions without locations, fallback to the order
12999 // in which they were added into the candidate set.
13000 return L < R;
13001 }
13002
13003private:
13004 struct ConversionSignals {
13005 unsigned KindRank = 0;
13007
13008 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13009 ConversionSignals Sig;
13010 Sig.KindRank = Seq.getKindRank();
13011 if (Seq.isStandard())
13012 Sig.Rank = Seq.Standard.getRank();
13013 else if (Seq.isUserDefined())
13014 Sig.Rank = Seq.UserDefined.After.getRank();
13015 // We intend StaticObjectArgumentConversion to compare the same as
13016 // StandardConversion with ICR_ExactMatch rank.
13017 return Sig;
13018 }
13019
13020 static ConversionSignals ForObjectArgument() {
13021 // We intend StaticObjectArgumentConversion to compare the same as
13022 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13023 return {};
13024 }
13025 };
13026
13027 // Returns -1 if conversions in L are considered better.
13028 // 0 if they are considered indistinguishable.
13029 // 1 if conversions in R are better.
13030 int CompareConversions(const OverloadCandidate &L,
13031 const OverloadCandidate &R) {
13032 // We cannot use `isBetterOverloadCandidate` because it is defined
13033 // according to the C++ standard and provides a partial order, but we need
13034 // a total order as this function is used in sort.
13035 assert(L.Conversions.size() == R.Conversions.size());
13036 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13037 auto LS = L.IgnoreObjectArgument && I == 0
13038 ? ConversionSignals::ForObjectArgument()
13039 : ConversionSignals::ForSequence(L.Conversions[I]);
13040 auto RS = R.IgnoreObjectArgument
13041 ? ConversionSignals::ForObjectArgument()
13042 : ConversionSignals::ForSequence(R.Conversions[I]);
13043 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13044 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13045 ? -1
13046 : 1;
13047 }
13048 // FIXME: find a way to compare templates for being more or less
13049 // specialized that provides a strict weak ordering.
13050 return 0;
13051 }
13052};
13053}
13054
13055/// CompleteNonViableCandidate - Normally, overload resolution only
13056/// computes up to the first bad conversion. Produces the FixIt set if
13057/// possible.
13058static void
13060 ArrayRef<Expr *> Args,
13062 assert(!Cand->Viable);
13063
13064 // Don't do anything on failures other than bad conversion.
13066 return;
13067
13068 // We only want the FixIts if all the arguments can be corrected.
13069 bool Unfixable = false;
13070 // Use a implicit copy initialization to check conversion fixes.
13072
13073 // Attempt to fix the bad conversion.
13074 unsigned ConvCount = Cand->Conversions.size();
13075 for (unsigned ConvIdx =
13076 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13077 : 0);
13078 /**/; ++ConvIdx) {
13079 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13080 if (Cand->Conversions[ConvIdx].isInitialized() &&
13081 Cand->Conversions[ConvIdx].isBad()) {
13082 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13083 break;
13084 }
13085 }
13086
13087 // FIXME: this should probably be preserved from the overload
13088 // operation somehow.
13089 bool SuppressUserConversions = false;
13090
13091 unsigned ConvIdx = 0;
13092 unsigned ArgIdx = 0;
13093 ArrayRef<QualType> ParamTypes;
13094 bool Reversed = Cand->isReversed();
13095
13096 if (Cand->IsSurrogate) {
13097 QualType ConvType
13099 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13100 ConvType = ConvPtrType->getPointeeType();
13101 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13102 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13103 ConvIdx = 1;
13104 } else if (Cand->Function) {
13105 ParamTypes =
13106 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13107 if (isa<CXXMethodDecl>(Cand->Function) &&
13110 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13111 ConvIdx = 1;
13113 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13115 OO_Subscript)
13116 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13117 ArgIdx = 1;
13118 }
13119 } else {
13120 // Builtin operator.
13121 assert(ConvCount <= 3);
13122 ParamTypes = Cand->BuiltinParamTypes;
13123 }
13124
13125 // Fill in the rest of the conversions.
13126 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13127 ConvIdx != ConvCount && ArgIdx < Args.size();
13128 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13129 if (Cand->Conversions[ConvIdx].isInitialized()) {
13130 // We've already checked this conversion.
13131 } else if (ParamIdx < ParamTypes.size()) {
13132 if (ParamTypes[ParamIdx]->isDependentType())
13133 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13134 Args[ArgIdx]->getType());
13135 else {
13136 Cand->Conversions[ConvIdx] =
13137 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13138 SuppressUserConversions,
13139 /*InOverloadResolution=*/true,
13140 /*AllowObjCWritebackConversion=*/
13141 S.getLangOpts().ObjCAutoRefCount);
13142 // Store the FixIt in the candidate if it exists.
13143 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13144 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13145 }
13146 } else
13147 Cand->Conversions[ConvIdx].setEllipsis();
13148 }
13149}
13150
13153 SourceLocation OpLoc,
13154 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13155
13157
13158 // Sort the candidates by viability and position. Sorting directly would
13159 // be prohibitive, so we make a set of pointers and sort those.
13161 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13162 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13163 Cand != LastCand; ++Cand) {
13164 if (!Filter(*Cand))
13165 continue;
13166 switch (OCD) {
13167 case OCD_AllCandidates:
13168 if (!Cand->Viable) {
13169 if (!Cand->Function && !Cand->IsSurrogate) {
13170 // This a non-viable builtin candidate. We do not, in general,
13171 // want to list every possible builtin candidate.
13172 continue;
13173 }
13174 CompleteNonViableCandidate(S, Cand, Args, Kind);
13175 }
13176 break;
13177
13179 if (!Cand->Viable)
13180 continue;
13181 break;
13182
13184 if (!Cand->Best)
13185 continue;
13186 break;
13187 }
13188
13189 Cands.push_back(Cand);
13190 }
13191
13192 llvm::stable_sort(
13193 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13194
13195 return Cands;
13196}
13197
13199 SourceLocation OpLoc) {
13200 bool DeferHint = false;
13201 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13202 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13203 // host device candidates.
13204 auto WrongSidedCands =
13205 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13206 return (Cand.Viable == false &&
13208 (Cand.Function &&
13209 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13210 Cand.Function->template hasAttr<CUDADeviceAttr>());
13211 });
13212 DeferHint = !WrongSidedCands.empty();
13213 }
13214 return DeferHint;
13215}
13216
13217/// When overload resolution fails, prints diagnostic messages containing the
13218/// candidates in the candidate set.
13221 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13222 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13223
13224 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13225
13226 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
13227
13228 // In WebAssembly we don't want to emit further diagnostics if a table is
13229 // passed as an argument to a function.
13230 bool NoteCands = true;
13231 for (const Expr *Arg : Args) {
13232 if (Arg->getType()->isWebAssemblyTableType())
13233 NoteCands = false;
13234 }
13235
13236 if (NoteCands)
13237 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13238
13239 if (OCD == OCD_AmbiguousCandidates)
13241 {Candidates.begin(), Candidates.end()});
13242}
13243
13246 StringRef Opc, SourceLocation OpLoc) {
13247 bool ReportedAmbiguousConversions = false;
13248
13249 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13250 unsigned CandsShown = 0;
13251 auto I = Cands.begin(), E = Cands.end();
13252 for (; I != E; ++I) {
13253 OverloadCandidate *Cand = *I;
13254
13255 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13256 ShowOverloads == Ovl_Best) {
13257 break;
13258 }
13259 ++CandsShown;
13260
13261 if (Cand->Function)
13262 NoteFunctionCandidate(S, Cand, Args.size(),
13263 Kind == CSK_AddressOfOverloadSet, DestAS);
13264 else if (Cand->IsSurrogate)
13265 NoteSurrogateCandidate(S, Cand);
13266 else {
13267 assert(Cand->Viable &&
13268 "Non-viable built-in candidates are not added to Cands.");
13269 // Generally we only see ambiguities including viable builtin
13270 // operators if overload resolution got screwed up by an
13271 // ambiguous user-defined conversion.
13272 //
13273 // FIXME: It's quite possible for different conversions to see
13274 // different ambiguities, though.
13275 if (!ReportedAmbiguousConversions) {
13276 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13277 ReportedAmbiguousConversions = true;
13278 }
13279
13280 // If this is a viable builtin, print it.
13281 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13282 }
13283 }
13284
13285 // Inform S.Diags that we've shown an overload set with N elements. This may
13286 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13287 S.Diags.overloadCandidatesShown(CandsShown);
13288
13289 if (I != E)
13290 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
13291 shouldDeferDiags(S, Args, OpLoc))
13292 << int(E - I);
13293}
13294
13295static SourceLocation
13297 return Cand->Specialization ? Cand->Specialization->getLocation()
13298 : SourceLocation();
13299}
13300
13301namespace {
13302struct CompareTemplateSpecCandidatesForDisplay {
13303 Sema &S;
13304 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13305
13306 bool operator()(const TemplateSpecCandidate *L,
13307 const TemplateSpecCandidate *R) {
13308 // Fast-path this check.
13309 if (L == R)
13310 return false;
13311
13312 // Assuming that both candidates are not matches...
13313
13314 // Sort by the ranking of deduction failures.
13318
13319 // Sort everything else by location.
13320 SourceLocation LLoc = GetLocationForCandidate(L);
13321 SourceLocation RLoc = GetLocationForCandidate(R);
13322
13323 // Put candidates without locations (e.g. builtins) at the end.
13324 if (LLoc.isInvalid())
13325 return false;
13326 if (RLoc.isInvalid())
13327 return true;
13328
13329 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13330 }
13331};
13332}
13333
13334/// Diagnose a template argument deduction failure.
13335/// We are treating these failures as overload failures due to bad
13336/// deductions.
13338 bool ForTakingAddress) {
13340 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13341}
13342
13343void TemplateSpecCandidateSet::destroyCandidates() {
13344 for (iterator i = begin(), e = end(); i != e; ++i) {
13345 i->DeductionFailure.Destroy();
13346 }
13347}
13348
13350 destroyCandidates();
13351 Candidates.clear();
13352}
13353
13354/// NoteCandidates - When no template specialization match is found, prints
13355/// diagnostic messages containing the non-matching specializations that form
13356/// the candidate set.
13357/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13358/// OCD == OCD_AllCandidates and Cand->Viable == false.
13360 // Sort the candidates by position (assuming no candidate is a match).
13361 // Sorting directly would be prohibitive, so we make a set of pointers
13362 // and sort those.
13364 Cands.reserve(size());
13365 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13366 if (Cand->Specialization)
13367 Cands.push_back(Cand);
13368 // Otherwise, this is a non-matching builtin candidate. We do not,
13369 // in general, want to list every possible builtin candidate.
13370 }
13371
13372 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13373
13374 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13375 // for generalization purposes (?).
13376 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13377
13379 unsigned CandsShown = 0;
13380 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13381 TemplateSpecCandidate *Cand = *I;
13382
13383 // Set an arbitrary limit on the number of candidates we'll spam
13384 // the user with. FIXME: This limit should depend on details of the
13385 // candidate list.
13386 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13387 break;
13388 ++CandsShown;
13389
13390 assert(Cand->Specialization &&
13391 "Non-matching built-in candidates are not added to Cands.");
13392 Cand->NoteDeductionFailure(S, ForTakingAddress);
13393 }
13394
13395 if (I != E)
13396 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13397}
13398
13399// [PossiblyAFunctionType] --> [Return]
13400// NonFunctionType --> NonFunctionType
13401// R (A) --> R(A)
13402// R (*)(A) --> R (A)
13403// R (&)(A) --> R (A)
13404// R (S::*)(A) --> R (A)
13406 QualType Ret = PossiblyAFunctionType;
13407 if (const PointerType *ToTypePtr =
13408 PossiblyAFunctionType->getAs<PointerType>())
13409 Ret = ToTypePtr->getPointeeType();
13410 else if (const ReferenceType *ToTypeRef =
13411 PossiblyAFunctionType->getAs<ReferenceType>())
13412 Ret = ToTypeRef->getPointeeType();
13413 else if (const MemberPointerType *MemTypePtr =
13414 PossiblyAFunctionType->getAs<MemberPointerType>())
13415 Ret = MemTypePtr->getPointeeType();
13416 Ret =
13417 Context.getCanonicalType(Ret).getUnqualifiedType();
13418 return Ret;
13419}
13420
13422 bool Complain = true) {
13423 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13424 S.DeduceReturnType(FD, Loc, Complain))
13425 return true;
13426
13427 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13428 if (S.getLangOpts().CPlusPlus17 &&
13429 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13430 !S.ResolveExceptionSpec(Loc, FPT))
13431 return true;
13432
13433 return false;
13434}
13435
13436namespace {
13437// A helper class to help with address of function resolution
13438// - allows us to avoid passing around all those ugly parameters
13439class AddressOfFunctionResolver {
13440 Sema& S;
13441 Expr* SourceExpr;
13442 const QualType& TargetType;
13443 QualType TargetFunctionType; // Extracted function type from target type
13444
13445 bool Complain;
13446 //DeclAccessPair& ResultFunctionAccessPair;
13447 ASTContext& Context;
13448
13449 bool TargetTypeIsNonStaticMemberFunction;
13450 bool FoundNonTemplateFunction;
13451 bool StaticMemberFunctionFromBoundPointer;
13452 bool HasComplained;
13453
13454 OverloadExpr::FindResult OvlExprInfo;
13455 OverloadExpr *OvlExpr;
13456 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13457 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13458 TemplateSpecCandidateSet FailedCandidates;
13459
13460public:
13461 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13462 const QualType &TargetType, bool Complain)
13463 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13464 Complain(Complain), Context(S.getASTContext()),
13465 TargetTypeIsNonStaticMemberFunction(
13466 !!TargetType->getAs<MemberPointerType>()),
13467 FoundNonTemplateFunction(false),
13468 StaticMemberFunctionFromBoundPointer(false),
13469 HasComplained(false),
13470 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13471 OvlExpr(OvlExprInfo.Expression),
13472 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13473 ExtractUnqualifiedFunctionTypeFromTargetType();
13474
13475 if (TargetFunctionType->isFunctionType()) {
13476 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13477 if (!UME->isImplicitAccess() &&
13479 StaticMemberFunctionFromBoundPointer = true;
13480 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13481 DeclAccessPair dap;
13482 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13483 OvlExpr, false, &dap)) {
13484 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13485 if (!Method->isStatic()) {
13486 // If the target type is a non-function type and the function found
13487 // is a non-static member function, pretend as if that was the
13488 // target, it's the only possible type to end up with.
13489 TargetTypeIsNonStaticMemberFunction = true;
13490
13491 // And skip adding the function if its not in the proper form.
13492 // We'll diagnose this due to an empty set of functions.
13493 if (!OvlExprInfo.HasFormOfMemberPointer)
13494 return;
13495 }
13496
13497 Matches.push_back(std::make_pair(dap, Fn));
13498 }
13499 return;
13500 }
13501
13502 if (OvlExpr->hasExplicitTemplateArgs())
13503 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13504
13505 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13506 // C++ [over.over]p4:
13507 // If more than one function is selected, [...]
13508 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13509 if (FoundNonTemplateFunction) {
13510 EliminateAllTemplateMatches();
13511 EliminateLessPartialOrderingConstrainedMatches();
13512 } else
13513 EliminateAllExceptMostSpecializedTemplate();
13514 }
13515 }
13516
13517 if (S.getLangOpts().CUDA && Matches.size() > 1)
13518 EliminateSuboptimalCudaMatches();
13519 }
13520
13521 bool hasComplained() const { return HasComplained; }
13522
13523private:
13524 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13525 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13526 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13527 }
13528
13529 /// \return true if A is considered a better overload candidate for the
13530 /// desired type than B.
13531 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13532 // If A doesn't have exactly the correct type, we don't want to classify it
13533 // as "better" than anything else. This way, the user is required to
13534 // disambiguate for us if there are multiple candidates and no exact match.
13535 return candidateHasExactlyCorrectType(A) &&
13536 (!candidateHasExactlyCorrectType(B) ||
13537 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13538 }
13539
13540 /// \return true if we were able to eliminate all but one overload candidate,
13541 /// false otherwise.
13542 bool eliminiateSuboptimalOverloadCandidates() {
13543 // Same algorithm as overload resolution -- one pass to pick the "best",
13544 // another pass to be sure that nothing is better than the best.
13545 auto Best = Matches.begin();
13546 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13547 if (isBetterCandidate(I->second, Best->second))
13548 Best = I;
13549
13550 const FunctionDecl *BestFn = Best->second;
13551 auto IsBestOrInferiorToBest = [this, BestFn](
13552 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13553 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13554 };
13555
13556 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13557 // option, so we can potentially give the user a better error
13558 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13559 return false;
13560 Matches[0] = *Best;
13561 Matches.resize(1);
13562 return true;
13563 }
13564
13565 bool isTargetTypeAFunction() const {
13566 return TargetFunctionType->isFunctionType();
13567 }
13568
13569 // [ToType] [Return]
13570
13571 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13572 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13573 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13574 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13575 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13576 }
13577
13578 // return true if any matching specializations were found
13579 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13580 const DeclAccessPair& CurAccessFunPair) {
13581 if (CXXMethodDecl *Method
13582 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13583 // Skip non-static function templates when converting to pointer, and
13584 // static when converting to member pointer.
13585 bool CanConvertToFunctionPointer =
13586 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13587 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13588 return false;
13589 }
13590 else if (TargetTypeIsNonStaticMemberFunction)
13591 return false;
13592
13593 // C++ [over.over]p2:
13594 // If the name is a function template, template argument deduction is
13595 // done (14.8.2.2), and if the argument deduction succeeds, the
13596 // resulting template argument list is used to generate a single
13597 // function template specialization, which is added to the set of
13598 // overloaded functions considered.
13599 FunctionDecl *Specialization = nullptr;
13600 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13602 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13603 Specialization, Info, /*IsAddressOfFunction*/ true);
13604 Result != TemplateDeductionResult::Success) {
13605 // Make a note of the failed deduction for diagnostics.
13606 FailedCandidates.addCandidate()
13607 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13608 MakeDeductionFailureInfo(Context, Result, Info));
13609 return false;
13610 }
13611
13612 // Template argument deduction ensures that we have an exact match or
13613 // compatible pointer-to-function arguments that would be adjusted by ICS.
13614 // This function template specicalization works.
13616 Context.getCanonicalType(Specialization->getType()),
13617 Context.getCanonicalType(TargetFunctionType)));
13618
13620 return false;
13621
13622 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13623 return true;
13624 }
13625
13626 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13627 const DeclAccessPair& CurAccessFunPair) {
13628 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13629 // Skip non-static functions when converting to pointer, and static
13630 // when converting to member pointer.
13631 bool CanConvertToFunctionPointer =
13632 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13633 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13634 return false;
13635 }
13636 else if (TargetTypeIsNonStaticMemberFunction)
13637 return false;
13638
13639 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13640 if (S.getLangOpts().CUDA) {
13641 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13642 if (!(Caller && Caller->isImplicit()) &&
13643 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13644 return false;
13645 }
13646 if (FunDecl->isMultiVersion()) {
13647 const auto *TA = FunDecl->getAttr<TargetAttr>();
13648 if (TA && !TA->isDefaultVersion())
13649 return false;
13650 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13651 if (TVA && !TVA->isDefaultVersion())
13652 return false;
13653 }
13654
13655 // If any candidate has a placeholder return type, trigger its deduction
13656 // now.
13657 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13658 Complain)) {
13659 HasComplained |= Complain;
13660 return false;
13661 }
13662
13663 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13664 return false;
13665
13666 // If we're in C, we need to support types that aren't exactly identical.
13667 if (!S.getLangOpts().CPlusPlus ||
13668 candidateHasExactlyCorrectType(FunDecl)) {
13669 Matches.push_back(std::make_pair(
13670 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13671 FoundNonTemplateFunction = true;
13672 return true;
13673 }
13674 }
13675
13676 return false;
13677 }
13678
13679 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13680 bool Ret = false;
13681
13682 // If the overload expression doesn't have the form of a pointer to
13683 // member, don't try to convert it to a pointer-to-member type.
13684 if (IsInvalidFormOfPointerToMemberFunction())
13685 return false;
13686
13687 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13688 E = OvlExpr->decls_end();
13689 I != E; ++I) {
13690 // Look through any using declarations to find the underlying function.
13691 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13692
13693 // C++ [over.over]p3:
13694 // Non-member functions and static member functions match
13695 // targets of type "pointer-to-function" or "reference-to-function."
13696 // Nonstatic member functions match targets of
13697 // type "pointer-to-member-function."
13698 // Note that according to DR 247, the containing class does not matter.
13699 if (FunctionTemplateDecl *FunctionTemplate
13700 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13701 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13702 Ret = true;
13703 }
13704 // If we have explicit template arguments supplied, skip non-templates.
13705 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13706 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13707 Ret = true;
13708 }
13709 assert(Ret || Matches.empty());
13710 return Ret;
13711 }
13712
13713 void EliminateAllExceptMostSpecializedTemplate() {
13714 // [...] and any given function template specialization F1 is
13715 // eliminated if the set contains a second function template
13716 // specialization whose function template is more specialized
13717 // than the function template of F1 according to the partial
13718 // ordering rules of 14.5.5.2.
13719
13720 // The algorithm specified above is quadratic. We instead use a
13721 // two-pass algorithm (similar to the one used to identify the
13722 // best viable function in an overload set) that identifies the
13723 // best function template (if it exists).
13724
13725 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13726 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13727 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13728
13729 // TODO: It looks like FailedCandidates does not serve much purpose
13730 // here, since the no_viable diagnostic has index 0.
13731 UnresolvedSetIterator Result = S.getMostSpecialized(
13732 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13733 SourceExpr->getBeginLoc(), S.PDiag(),
13734 S.PDiag(diag::err_addr_ovl_ambiguous)
13735 << Matches[0].second->getDeclName(),
13736 S.PDiag(diag::note_ovl_candidate)
13737 << (unsigned)oc_function << (unsigned)ocs_described_template,
13738 Complain, TargetFunctionType);
13739
13740 if (Result != MatchesCopy.end()) {
13741 // Make it the first and only element
13742 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13743 Matches[0].second = cast<FunctionDecl>(*Result);
13744 Matches.resize(1);
13745 } else
13746 HasComplained |= Complain;
13747 }
13748
13749 void EliminateAllTemplateMatches() {
13750 // [...] any function template specializations in the set are
13751 // eliminated if the set also contains a non-template function, [...]
13752 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13753 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13754 ++I;
13755 else {
13756 Matches[I] = Matches[--N];
13757 Matches.resize(N);
13758 }
13759 }
13760 }
13761
13762 void EliminateLessPartialOrderingConstrainedMatches() {
13763 // C++ [over.over]p5:
13764 // [...] Any given non-template function F0 is eliminated if the set
13765 // contains a second non-template function that is more
13766 // partial-ordering-constrained than F0. [...]
13767 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13768 "Call EliminateAllTemplateMatches() first");
13769 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13770 Results.push_back(Matches[0]);
13771 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13772 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13773 FunctionDecl *F = getMorePartialOrderingConstrained(
13774 S, Matches[I].second, Results[0].second,
13775 /*IsFn1Reversed=*/false,
13776 /*IsFn2Reversed=*/false);
13777 if (!F) {
13778 Results.push_back(Matches[I]);
13779 continue;
13780 }
13781 if (F == Matches[I].second) {
13782 Results.clear();
13783 Results.push_back(Matches[I]);
13784 }
13785 }
13786 std::swap(Matches, Results);
13787 }
13788
13789 void EliminateSuboptimalCudaMatches() {
13790 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13791 Matches);
13792 }
13793
13794public:
13795 void ComplainNoMatchesFound() const {
13796 assert(Matches.empty());
13797 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13798 << OvlExpr->getName() << TargetFunctionType
13799 << OvlExpr->getSourceRange();
13800 if (FailedCandidates.empty())
13801 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13802 /*TakingAddress=*/true);
13803 else {
13804 // We have some deduction failure messages. Use them to diagnose
13805 // the function templates, and diagnose the non-template candidates
13806 // normally.
13807 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13808 IEnd = OvlExpr->decls_end();
13809 I != IEnd; ++I)
13810 if (FunctionDecl *Fun =
13811 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13813 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13814 /*TakingAddress=*/true);
13815 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13816 }
13817 }
13818
13819 bool IsInvalidFormOfPointerToMemberFunction() const {
13820 return TargetTypeIsNonStaticMemberFunction &&
13821 !OvlExprInfo.HasFormOfMemberPointer;
13822 }
13823
13824 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13825 // TODO: Should we condition this on whether any functions might
13826 // have matched, or is it more appropriate to do that in callers?
13827 // TODO: a fixit wouldn't hurt.
13828 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13829 << TargetType << OvlExpr->getSourceRange();
13830 }
13831
13832 bool IsStaticMemberFunctionFromBoundPointer() const {
13833 return StaticMemberFunctionFromBoundPointer;
13834 }
13835
13836 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13837 S.Diag(OvlExpr->getBeginLoc(),
13838 diag::err_invalid_form_pointer_member_function)
13839 << OvlExpr->getSourceRange();
13840 }
13841
13842 void ComplainOfInvalidConversion() const {
13843 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13844 << OvlExpr->getName() << TargetType;
13845 }
13846
13847 void ComplainMultipleMatchesFound() const {
13848 assert(Matches.size() > 1);
13849 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13850 << OvlExpr->getName() << OvlExpr->getSourceRange();
13851 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13852 /*TakingAddress=*/true);
13853 }
13854
13855 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13856
13857 int getNumMatches() const { return Matches.size(); }
13858
13859 FunctionDecl* getMatchingFunctionDecl() const {
13860 if (Matches.size() != 1) return nullptr;
13861 return Matches[0].second;
13862 }
13863
13864 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13865 if (Matches.size() != 1) return nullptr;
13866 return &Matches[0].first;
13867 }
13868};
13869}
13870
13871FunctionDecl *
13873 QualType TargetType,
13874 bool Complain,
13875 DeclAccessPair &FoundResult,
13876 bool *pHadMultipleCandidates) {
13877 assert(AddressOfExpr->getType() == Context.OverloadTy);
13878
13879 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13880 Complain);
13881 int NumMatches = Resolver.getNumMatches();
13882 FunctionDecl *Fn = nullptr;
13883 bool ShouldComplain = Complain && !Resolver.hasComplained();
13884 if (NumMatches == 0 && ShouldComplain) {
13885 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13886 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13887 else
13888 Resolver.ComplainNoMatchesFound();
13889 }
13890 else if (NumMatches > 1 && ShouldComplain)
13891 Resolver.ComplainMultipleMatchesFound();
13892 else if (NumMatches == 1) {
13893 Fn = Resolver.getMatchingFunctionDecl();
13894 assert(Fn);
13895 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13896 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13897 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13898 if (Complain) {
13899 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13900 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13901 else
13902 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13903 }
13904 }
13905
13906 if (pHadMultipleCandidates)
13907 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13908 return Fn;
13909}
13910
13914 OverloadExpr *Ovl = R.Expression;
13915 bool IsResultAmbiguous = false;
13916 FunctionDecl *Result = nullptr;
13917 DeclAccessPair DAP;
13918 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13919
13920 // Return positive for better, negative for worse, 0 for equal preference.
13921 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13922 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13923 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13924 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13925 };
13926
13927 // Don't use the AddressOfResolver because we're specifically looking for
13928 // cases where we have one overload candidate that lacks
13929 // enable_if/pass_object_size/...
13930 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13931 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13932 if (!FD)
13933 return nullptr;
13934
13936 continue;
13937
13938 // If we found a better result, update Result.
13939 auto FoundBetter = [&]() {
13940 IsResultAmbiguous = false;
13941 DAP = I.getPair();
13942 Result = FD;
13943 };
13944
13945 // We have more than one result - see if it is more
13946 // partial-ordering-constrained than the previous one.
13947 if (Result) {
13948 // Check CUDA preference first. If the candidates have differennt CUDA
13949 // preference, choose the one with higher CUDA preference. Otherwise,
13950 // choose the one with more constraints.
13951 if (getLangOpts().CUDA) {
13952 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13953 // FD has different preference than Result.
13954 if (PreferenceByCUDA != 0) {
13955 // FD is more preferable than Result.
13956 if (PreferenceByCUDA > 0)
13957 FoundBetter();
13958 continue;
13959 }
13960 }
13961 // FD has the same CUDA preference than Result. Continue to check
13962 // constraints.
13963
13964 // C++ [over.over]p5:
13965 // [...] Any given non-template function F0 is eliminated if the set
13966 // contains a second non-template function that is more
13967 // partial-ordering-constrained than F0 [...]
13968 FunctionDecl *MoreConstrained =
13970 /*IsFn1Reversed=*/false,
13971 /*IsFn2Reversed=*/false);
13972 if (MoreConstrained != FD) {
13973 if (!MoreConstrained) {
13974 IsResultAmbiguous = true;
13975 AmbiguousDecls.push_back(FD);
13976 }
13977 continue;
13978 }
13979 // FD is more constrained - replace Result with it.
13980 }
13981 FoundBetter();
13982 }
13983
13984 if (IsResultAmbiguous)
13985 return nullptr;
13986
13987 if (Result) {
13988 // We skipped over some ambiguous declarations which might be ambiguous with
13989 // the selected result.
13990 for (FunctionDecl *Skipped : AmbiguousDecls) {
13991 // If skipped candidate has different CUDA preference than the result,
13992 // there is no ambiguity. Otherwise check whether they have different
13993 // constraints.
13994 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13995 continue;
13996 if (!getMoreConstrainedFunction(Skipped, Result))
13997 return nullptr;
13998 }
13999 Pair = DAP;
14000 }
14001 return Result;
14002}
14003
14005 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14006 Expr *E = SrcExpr.get();
14007 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14008
14009 DeclAccessPair DAP;
14011 if (!Found || Found->isCPUDispatchMultiVersion() ||
14012 Found->isCPUSpecificMultiVersion())
14013 return false;
14014
14015 // Emitting multiple diagnostics for a function that is both inaccessible and
14016 // unavailable is consistent with our behavior elsewhere. So, always check
14017 // for both.
14021 if (Res.isInvalid())
14022 return false;
14023 Expr *Fixed = Res.get();
14024 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14025 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14026 else
14027 SrcExpr = Fixed;
14028 return true;
14029}
14030
14032 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14033 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14034 // C++ [over.over]p1:
14035 // [...] [Note: any redundant set of parentheses surrounding the
14036 // overloaded function name is ignored (5.1). ]
14037 // C++ [over.over]p1:
14038 // [...] The overloaded function name can be preceded by the &
14039 // operator.
14040
14041 // If we didn't actually find any template-ids, we're done.
14042 if (!ovl->hasExplicitTemplateArgs())
14043 return nullptr;
14044
14045 TemplateArgumentListInfo ExplicitTemplateArgs;
14046 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14047
14048 // Look through all of the overloaded functions, searching for one
14049 // whose type matches exactly.
14050 FunctionDecl *Matched = nullptr;
14051 for (UnresolvedSetIterator I = ovl->decls_begin(),
14052 E = ovl->decls_end(); I != E; ++I) {
14053 // C++0x [temp.arg.explicit]p3:
14054 // [...] In contexts where deduction is done and fails, or in contexts
14055 // where deduction is not done, if a template argument list is
14056 // specified and it, along with any default template arguments,
14057 // identifies a single function template specialization, then the
14058 // template-id is an lvalue for the function template specialization.
14060 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14061 if (!FunctionTemplate)
14062 continue;
14063
14064 // C++ [over.over]p2:
14065 // If the name is a function template, template argument deduction is
14066 // done (14.8.2.2), and if the argument deduction succeeds, the
14067 // resulting template argument list is used to generate a single
14068 // function template specialization, which is added to the set of
14069 // overloaded functions considered.
14070 FunctionDecl *Specialization = nullptr;
14071 TemplateDeductionInfo Info(ovl->getNameLoc());
14073 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14074 /*IsAddressOfFunction*/ true);
14076 // Make a note of the failed deduction for diagnostics.
14077 if (FailedTSC)
14078 FailedTSC->addCandidate().set(
14079 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14081 continue;
14082 }
14083
14084 assert(Specialization && "no specialization and no error?");
14085
14086 // C++ [temp.deduct.call]p6:
14087 // [...] If all successful deductions yield the same deduced A, that
14088 // deduced A is the result of deduction; otherwise, the parameter is
14089 // treated as a non-deduced context.
14090 if (Matched) {
14091 if (ForTypeDeduction &&
14093 Specialization->getType()))
14094 continue;
14095 // Multiple matches; we can't resolve to a single declaration.
14096 if (Complain) {
14097 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14098 << ovl->getName();
14100 }
14101 return nullptr;
14102 }
14103
14104 Matched = Specialization;
14105 if (FoundResult) *FoundResult = I.getPair();
14106 }
14107
14108 if (Matched &&
14109 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14110 return nullptr;
14111
14112 return Matched;
14113}
14114
14116 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14117 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14118 unsigned DiagIDForComplaining) {
14119 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14120
14122
14123 DeclAccessPair found;
14124 ExprResult SingleFunctionExpression;
14126 ovl.Expression, /*complain*/ false, &found)) {
14127 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14128 SrcExpr = ExprError();
14129 return true;
14130 }
14131
14132 // It is only correct to resolve to an instance method if we're
14133 // resolving a form that's permitted to be a pointer to member.
14134 // Otherwise we'll end up making a bound member expression, which
14135 // is illegal in all the contexts we resolve like this.
14136 if (!ovl.HasFormOfMemberPointer &&
14137 isa<CXXMethodDecl>(fn) &&
14138 cast<CXXMethodDecl>(fn)->isInstance()) {
14139 if (!complain) return false;
14140
14141 Diag(ovl.Expression->getExprLoc(),
14142 diag::err_bound_member_function)
14143 << 0 << ovl.Expression->getSourceRange();
14144
14145 // TODO: I believe we only end up here if there's a mix of
14146 // static and non-static candidates (otherwise the expression
14147 // would have 'bound member' type, not 'overload' type).
14148 // Ideally we would note which candidate was chosen and why
14149 // the static candidates were rejected.
14150 SrcExpr = ExprError();
14151 return true;
14152 }
14153
14154 // Fix the expression to refer to 'fn'.
14155 SingleFunctionExpression =
14156 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14157
14158 // If desired, do function-to-pointer decay.
14159 if (doFunctionPointerConversion) {
14160 SingleFunctionExpression =
14161 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14162 if (SingleFunctionExpression.isInvalid()) {
14163 SrcExpr = ExprError();
14164 return true;
14165 }
14166 }
14167 }
14168
14169 if (!SingleFunctionExpression.isUsable()) {
14170 if (complain) {
14171 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14172 << ovl.Expression->getName()
14173 << DestTypeForComplaining
14174 << OpRangeForComplaining
14176 NoteAllOverloadCandidates(SrcExpr.get());
14177
14178 SrcExpr = ExprError();
14179 return true;
14180 }
14181
14182 return false;
14183 }
14184
14185 SrcExpr = SingleFunctionExpression;
14186 return true;
14187}
14188
14189/// Add a single candidate to the overload set.
14191 DeclAccessPair FoundDecl,
14192 TemplateArgumentListInfo *ExplicitTemplateArgs,
14193 ArrayRef<Expr *> Args,
14194 OverloadCandidateSet &CandidateSet,
14195 bool PartialOverloading,
14196 bool KnownValid) {
14197 NamedDecl *Callee = FoundDecl.getDecl();
14198 if (isa<UsingShadowDecl>(Callee))
14199 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14200
14201 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14202 if (ExplicitTemplateArgs) {
14203 assert(!KnownValid && "Explicit template arguments?");
14204 return;
14205 }
14206 // Prevent ill-formed function decls to be added as overload candidates.
14207 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14208 return;
14209
14210 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14211 /*SuppressUserConversions=*/false,
14212 PartialOverloading);
14213 return;
14214 }
14215
14216 if (FunctionTemplateDecl *FuncTemplate
14217 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14218 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14219 ExplicitTemplateArgs, Args, CandidateSet,
14220 /*SuppressUserConversions=*/false,
14221 PartialOverloading);
14222 return;
14223 }
14224
14225 assert(!KnownValid && "unhandled case in overloaded call candidate");
14226}
14227
14229 ArrayRef<Expr *> Args,
14230 OverloadCandidateSet &CandidateSet,
14231 bool PartialOverloading) {
14232
14233#ifndef NDEBUG
14234 // Verify that ArgumentDependentLookup is consistent with the rules
14235 // in C++0x [basic.lookup.argdep]p3:
14236 //
14237 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14238 // and let Y be the lookup set produced by argument dependent
14239 // lookup (defined as follows). If X contains
14240 //
14241 // -- a declaration of a class member, or
14242 //
14243 // -- a block-scope function declaration that is not a
14244 // using-declaration, or
14245 //
14246 // -- a declaration that is neither a function or a function
14247 // template
14248 //
14249 // then Y is empty.
14250
14251 if (ULE->requiresADL()) {
14253 E = ULE->decls_end(); I != E; ++I) {
14254 assert(!(*I)->getDeclContext()->isRecord());
14255 assert(isa<UsingShadowDecl>(*I) ||
14256 !(*I)->getDeclContext()->isFunctionOrMethod());
14257 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14258 }
14259 }
14260#endif
14261
14262 // It would be nice to avoid this copy.
14263 TemplateArgumentListInfo TABuffer;
14264 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14265 if (ULE->hasExplicitTemplateArgs()) {
14266 ULE->copyTemplateArgumentsInto(TABuffer);
14267 ExplicitTemplateArgs = &TABuffer;
14268 }
14269
14271 E = ULE->decls_end(); I != E; ++I)
14272 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14273 CandidateSet, PartialOverloading,
14274 /*KnownValid*/ true);
14275
14276 if (ULE->requiresADL())
14278 Args, ExplicitTemplateArgs,
14279 CandidateSet, PartialOverloading);
14280}
14281
14283 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14284 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14285 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14286 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14287 CandidateSet, false, /*KnownValid*/ false);
14288}
14289
14290/// Determine whether a declaration with the specified name could be moved into
14291/// a different namespace.
14293 switch (Name.getCXXOverloadedOperator()) {
14294 case OO_New: case OO_Array_New:
14295 case OO_Delete: case OO_Array_Delete:
14296 return false;
14297
14298 default:
14299 return true;
14300 }
14301}
14302
14303/// Attempt to recover from an ill-formed use of a non-dependent name in a
14304/// template, where the non-dependent name was declared after the template
14305/// was defined. This is common in code written for a compilers which do not
14306/// correctly implement two-stage name lookup.
14307///
14308/// Returns true if a viable candidate was found and a diagnostic was issued.
14310 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14312 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14313 CXXRecordDecl **FoundInClass = nullptr) {
14314 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14315 return false;
14316
14317 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14318 if (DC->isTransparentContext())
14319 continue;
14320
14321 SemaRef.LookupQualifiedName(R, DC);
14322
14323 if (!R.empty()) {
14325
14326 OverloadCandidateSet Candidates(FnLoc, CSK);
14327 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14328 Candidates);
14329
14332 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14333
14334 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14335 // We either found non-function declarations or a best viable function
14336 // at class scope. A class-scope lookup result disables ADL. Don't
14337 // look past this, but let the caller know that we found something that
14338 // either is, or might be, usable in this class.
14339 if (FoundInClass) {
14340 *FoundInClass = RD;
14341 if (OR == OR_Success) {
14342 R.clear();
14343 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14344 R.resolveKind();
14345 }
14346 }
14347 return false;
14348 }
14349
14350 if (OR != OR_Success) {
14351 // There wasn't a unique best function or function template.
14352 return false;
14353 }
14354
14355 // Find the namespaces where ADL would have looked, and suggest
14356 // declaring the function there instead.
14357 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14358 Sema::AssociatedClassSet AssociatedClasses;
14359 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14360 AssociatedNamespaces,
14361 AssociatedClasses);
14362 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14364 DeclContext *Std = SemaRef.getStdNamespace();
14365 for (Sema::AssociatedNamespaceSet::iterator
14366 it = AssociatedNamespaces.begin(),
14367 end = AssociatedNamespaces.end(); it != end; ++it) {
14368 // Never suggest declaring a function within namespace 'std'.
14369 if (Std && Std->Encloses(*it))
14370 continue;
14371
14372 // Never suggest declaring a function within a namespace with a
14373 // reserved name, like __gnu_cxx.
14374 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14375 if (NS &&
14376 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14377 continue;
14378
14379 SuggestedNamespaces.insert(*it);
14380 }
14381 }
14382
14383 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14384 << R.getLookupName();
14385 if (SuggestedNamespaces.empty()) {
14386 SemaRef.Diag(Best->Function->getLocation(),
14387 diag::note_not_found_by_two_phase_lookup)
14388 << R.getLookupName() << 0;
14389 } else if (SuggestedNamespaces.size() == 1) {
14390 SemaRef.Diag(Best->Function->getLocation(),
14391 diag::note_not_found_by_two_phase_lookup)
14392 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14393 } else {
14394 // FIXME: It would be useful to list the associated namespaces here,
14395 // but the diagnostics infrastructure doesn't provide a way to produce
14396 // a localized representation of a list of items.
14397 SemaRef.Diag(Best->Function->getLocation(),
14398 diag::note_not_found_by_two_phase_lookup)
14399 << R.getLookupName() << 2;
14400 }
14401
14402 // Try to recover by calling this function.
14403 return true;
14404 }
14405
14406 R.clear();
14407 }
14408
14409 return false;
14410}
14411
14412/// Attempt to recover from ill-formed use of a non-dependent operator in a
14413/// template, where the non-dependent operator was declared after the template
14414/// was defined.
14415///
14416/// Returns true if a viable candidate was found and a diagnostic was issued.
14417static bool
14419 SourceLocation OpLoc,
14420 ArrayRef<Expr *> Args) {
14421 DeclarationName OpName =
14423 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14424 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14426 /*ExplicitTemplateArgs=*/nullptr, Args);
14427}
14428
14429namespace {
14430class BuildRecoveryCallExprRAII {
14431 Sema &SemaRef;
14432 Sema::SatisfactionStackResetRAII SatStack;
14433
14434public:
14435 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14436 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14437 SemaRef.IsBuildingRecoveryCallExpr = true;
14438 }
14439
14440 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14441};
14442}
14443
14444/// Attempts to recover from a call where no functions were found.
14445///
14446/// This function will do one of three things:
14447/// * Diagnose, recover, and return a recovery expression.
14448/// * Diagnose, fail to recover, and return ExprError().
14449/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14450/// expected to diagnose as appropriate.
14451static ExprResult
14454 SourceLocation LParenLoc,
14456 SourceLocation RParenLoc,
14457 bool EmptyLookup, bool AllowTypoCorrection) {
14458 // Do not try to recover if it is already building a recovery call.
14459 // This stops infinite loops for template instantiations like
14460 //
14461 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14462 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14463 if (SemaRef.IsBuildingRecoveryCallExpr)
14464 return ExprResult();
14465 BuildRecoveryCallExprRAII RCE(SemaRef);
14466
14467 CXXScopeSpec SS;
14468 SS.Adopt(ULE->getQualifierLoc());
14469 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14470
14471 TemplateArgumentListInfo TABuffer;
14472 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14473 if (ULE->hasExplicitTemplateArgs()) {
14474 ULE->copyTemplateArgumentsInto(TABuffer);
14475 ExplicitTemplateArgs = &TABuffer;
14476 }
14477
14478 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14480 CXXRecordDecl *FoundInClass = nullptr;
14481 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14483 ExplicitTemplateArgs, Args, &FoundInClass)) {
14484 // OK, diagnosed a two-phase lookup issue.
14485 } else if (EmptyLookup) {
14486 // Try to recover from an empty lookup with typo correction.
14487 R.clear();
14488 NoTypoCorrectionCCC NoTypoValidator{};
14489 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14490 ExplicitTemplateArgs != nullptr,
14491 dyn_cast<MemberExpr>(Fn));
14492 CorrectionCandidateCallback &Validator =
14493 AllowTypoCorrection
14494 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14495 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14496 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14497 Args))
14498 return ExprError();
14499 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14500 // We found a usable declaration of the name in a dependent base of some
14501 // enclosing class.
14502 // FIXME: We should also explain why the candidates found by name lookup
14503 // were not viable.
14504 if (SemaRef.DiagnoseDependentMemberLookup(R))
14505 return ExprError();
14506 } else {
14507 // We had viable candidates and couldn't recover; let the caller diagnose
14508 // this.
14509 return ExprResult();
14510 }
14511
14512 // If we get here, we should have issued a diagnostic and formed a recovery
14513 // lookup result.
14514 assert(!R.empty() && "lookup results empty despite recovery");
14515
14516 // If recovery created an ambiguity, just bail out.
14517 if (R.isAmbiguous()) {
14519 return ExprError();
14520 }
14521
14522 // Build an implicit member call if appropriate. Just drop the
14523 // casts and such from the call, we don't really care.
14524 ExprResult NewFn = ExprError();
14525 if ((*R.begin())->isCXXClassMember())
14526 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14527 ExplicitTemplateArgs, S);
14528 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14529 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14530 ExplicitTemplateArgs);
14531 else
14532 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14533
14534 if (NewFn.isInvalid())
14535 return ExprError();
14536
14537 // This shouldn't cause an infinite loop because we're giving it
14538 // an expression with viable lookup results, which should never
14539 // end up here.
14540 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14541 MultiExprArg(Args.data(), Args.size()),
14542 RParenLoc);
14543}
14544
14547 MultiExprArg Args,
14548 SourceLocation RParenLoc,
14549 OverloadCandidateSet *CandidateSet,
14550 ExprResult *Result) {
14551#ifndef NDEBUG
14552 if (ULE->requiresADL()) {
14553 // To do ADL, we must have found an unqualified name.
14554 assert(!ULE->getQualifier() && "qualified name with ADL");
14555
14556 // We don't perform ADL for implicit declarations of builtins.
14557 // Verify that this was correctly set up.
14558 FunctionDecl *F;
14559 if (ULE->decls_begin() != ULE->decls_end() &&
14560 ULE->decls_begin() + 1 == ULE->decls_end() &&
14561 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14562 F->getBuiltinID() && F->isImplicit())
14563 llvm_unreachable("performing ADL for builtin");
14564
14565 // We don't perform ADL in C.
14566 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14567 }
14568#endif
14569
14570 UnbridgedCastsSet UnbridgedCasts;
14571 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14572 *Result = ExprError();
14573 return true;
14574 }
14575
14576 // Add the functions denoted by the callee to the set of candidate
14577 // functions, including those from argument-dependent lookup.
14578 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14579
14580 if (getLangOpts().MSVCCompat &&
14581 CurContext->isDependentContext() && !isSFINAEContext() &&
14583
14585 if (CandidateSet->empty() ||
14586 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14588 // In Microsoft mode, if we are inside a template class member function
14589 // then create a type dependent CallExpr. The goal is to postpone name
14590 // lookup to instantiation time to be able to search into type dependent
14591 // base classes.
14592 CallExpr *CE =
14593 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14594 RParenLoc, CurFPFeatureOverrides());
14596 *Result = CE;
14597 return true;
14598 }
14599 }
14600
14601 if (CandidateSet->empty())
14602 return false;
14603
14604 UnbridgedCasts.restore();
14605 return false;
14606}
14607
14608// Guess at what the return type for an unresolvable overload should be.
14611 std::optional<QualType> Result;
14612 // Adjust Type after seeing a candidate.
14613 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14614 if (!Candidate.Function)
14615 return;
14616 if (Candidate.Function->isInvalidDecl())
14617 return;
14618 QualType T = Candidate.Function->getReturnType();
14619 if (T.isNull())
14620 return;
14621 if (!Result)
14622 Result = T;
14623 else if (Result != T)
14624 Result = QualType();
14625 };
14626
14627 // Look for an unambiguous type from a progressively larger subset.
14628 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14629 //
14630 // First, consider only the best candidate.
14631 if (Best && *Best != CS.end())
14632 ConsiderCandidate(**Best);
14633 // Next, consider only viable candidates.
14634 if (!Result)
14635 for (const auto &C : CS)
14636 if (C.Viable)
14637 ConsiderCandidate(C);
14638 // Finally, consider all candidates.
14639 if (!Result)
14640 for (const auto &C : CS)
14641 ConsiderCandidate(C);
14642
14643 if (!Result)
14644 return QualType();
14645 auto Value = *Result;
14646 if (Value.isNull() || Value->isUndeducedType())
14647 return QualType();
14648 return Value;
14649}
14650
14651/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14652/// the completed call expression. If overload resolution fails, emits
14653/// diagnostics and returns ExprError()
14656 SourceLocation LParenLoc,
14657 MultiExprArg Args,
14658 SourceLocation RParenLoc,
14659 Expr *ExecConfig,
14660 OverloadCandidateSet *CandidateSet,
14662 OverloadingResult OverloadResult,
14663 bool AllowTypoCorrection) {
14664 switch (OverloadResult) {
14665 case OR_Success: {
14666 FunctionDecl *FDecl = (*Best)->Function;
14667 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14668 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14669 return ExprError();
14670 ExprResult Res =
14671 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14672 if (Res.isInvalid())
14673 return ExprError();
14674 return SemaRef.BuildResolvedCallExpr(
14675 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14676 /*IsExecConfig=*/false,
14677 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14678 }
14679
14680 case OR_No_Viable_Function: {
14681 if (*Best != CandidateSet->end() &&
14682 CandidateSet->getKind() ==
14684 if (CXXMethodDecl *M =
14685 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14687 CandidateSet->NoteCandidates(
14689 Fn->getBeginLoc(),
14690 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14691 SemaRef, OCD_AmbiguousCandidates, Args);
14692 return ExprError();
14693 }
14694 }
14695
14696 // Try to recover by looking for viable functions which the user might
14697 // have meant to call.
14698 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14699 Args, RParenLoc,
14700 CandidateSet->empty(),
14701 AllowTypoCorrection);
14702 if (Recovery.isInvalid() || Recovery.isUsable())
14703 return Recovery;
14704
14705 // If the user passes in a function that we can't take the address of, we
14706 // generally end up emitting really bad error messages. Here, we attempt to
14707 // emit better ones.
14708 for (const Expr *Arg : Args) {
14709 if (!Arg->getType()->isFunctionType())
14710 continue;
14711 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14712 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14713 if (FD &&
14714 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14715 Arg->getExprLoc()))
14716 return ExprError();
14717 }
14718 }
14719
14720 CandidateSet->NoteCandidates(
14722 Fn->getBeginLoc(),
14723 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14724 << ULE->getName() << Fn->getSourceRange()),
14725 SemaRef, OCD_AllCandidates, Args);
14726 break;
14727 }
14728
14729 case OR_Ambiguous:
14730 CandidateSet->NoteCandidates(
14731 PartialDiagnosticAt(Fn->getBeginLoc(),
14732 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14733 << ULE->getName() << Fn->getSourceRange()),
14734 SemaRef, OCD_AmbiguousCandidates, Args);
14735 break;
14736
14737 case OR_Deleted: {
14738 FunctionDecl *FDecl = (*Best)->Function;
14739 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14740 Fn->getSourceRange(), ULE->getName(),
14741 *CandidateSet, FDecl, Args);
14742
14743 // We emitted an error for the unavailable/deleted function call but keep
14744 // the call in the AST.
14745 ExprResult Res =
14746 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14747 if (Res.isInvalid())
14748 return ExprError();
14749 return SemaRef.BuildResolvedCallExpr(
14750 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14751 /*IsExecConfig=*/false,
14752 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14753 }
14754 }
14755
14756 // Overload resolution failed, try to recover.
14757 SmallVector<Expr *, 8> SubExprs = {Fn};
14758 SubExprs.append(Args.begin(), Args.end());
14759 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14760 chooseRecoveryType(*CandidateSet, Best));
14761}
14762
14765 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14766 if (I->Viable &&
14767 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14768 I->Viable = false;
14769 I->FailureKind = ovl_fail_addr_not_available;
14770 }
14771 }
14772}
14773
14776 SourceLocation LParenLoc,
14777 MultiExprArg Args,
14778 SourceLocation RParenLoc,
14779 Expr *ExecConfig,
14780 bool AllowTypoCorrection,
14781 bool CalleesAddressIsTaken) {
14782
14786
14787 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14788 ExprResult result;
14789
14790 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14791 &result))
14792 return result;
14793
14794 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14795 // functions that aren't addressible are considered unviable.
14796 if (CalleesAddressIsTaken)
14797 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14798
14800 OverloadingResult OverloadResult =
14801 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14802
14803 // [C++23][over.call.func]
14804 // if overload resolution selects a non-static member function,
14805 // the call is ill-formed;
14807 Best != CandidateSet.end()) {
14808 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14809 M && M->isImplicitObjectMemberFunction()) {
14810 OverloadResult = OR_No_Viable_Function;
14811 }
14812 }
14813
14814 // Model the case with a call to a templated function whose definition
14815 // encloses the call and whose return type contains a placeholder type as if
14816 // the UnresolvedLookupExpr was type-dependent.
14817 if (OverloadResult == OR_Success) {
14818 const FunctionDecl *FDecl = Best->Function;
14819 if (LangOpts.CUDA)
14820 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14821 if (FDecl && FDecl->isTemplateInstantiation() &&
14822 FDecl->getReturnType()->isUndeducedType()) {
14823
14824 // Creating dependent CallExpr is not okay if the enclosing context itself
14825 // is not dependent. This situation notably arises if a non-dependent
14826 // member function calls the later-defined overloaded static function.
14827 //
14828 // For example, in
14829 // class A {
14830 // void c() { callee(1); }
14831 // static auto callee(auto x) { }
14832 // };
14833 //
14834 // Here callee(1) is unresolved at the call site, but is not inside a
14835 // dependent context. There will be no further attempt to resolve this
14836 // call if it is made dependent.
14837
14838 if (const auto *TP =
14839 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14840 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14841 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14842 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14843 }
14844 }
14845 }
14846
14847 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14848 ExecConfig, &CandidateSet, &Best,
14849 OverloadResult, AllowTypoCorrection);
14850}
14851
14855 const UnresolvedSetImpl &Fns,
14856 bool PerformADL) {
14858 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14859 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14860}
14861
14864 bool HadMultipleCandidates) {
14865 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14866 // the FoundDecl as it impedes TransformMemberExpr.
14867 // We go a bit further here: if there's no difference in UnderlyingDecl,
14868 // then using FoundDecl vs Method shouldn't make a difference either.
14869 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14870 FoundDecl = Method;
14871 // Convert the expression to match the conversion function's implicit object
14872 // parameter.
14873 ExprResult Exp;
14874 if (Method->isExplicitObjectMemberFunction())
14876 else
14878 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14879 if (Exp.isInvalid())
14880 return true;
14881
14882 if (Method->getParent()->isLambda() &&
14883 Method->getConversionType()->isBlockPointerType()) {
14884 // This is a lambda conversion to block pointer; check if the argument
14885 // was a LambdaExpr.
14886 Expr *SubE = E;
14887 auto *CE = dyn_cast<CastExpr>(SubE);
14888 if (CE && CE->getCastKind() == CK_NoOp)
14889 SubE = CE->getSubExpr();
14890 SubE = SubE->IgnoreParens();
14891 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14892 SubE = BE->getSubExpr();
14893 if (isa<LambdaExpr>(SubE)) {
14894 // For the conversion to block pointer on a lambda expression, we
14895 // construct a special BlockLiteral instead; this doesn't really make
14896 // a difference in ARC, but outside of ARC the resulting block literal
14897 // follows the normal lifetime rules for block literals instead of being
14898 // autoreleased.
14902 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14904
14905 // FIXME: This note should be produced by a CodeSynthesisContext.
14906 if (BlockExp.isInvalid())
14907 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14908 return BlockExp;
14909 }
14910 }
14911 CallExpr *CE;
14912 QualType ResultType = Method->getReturnType();
14914 ResultType = ResultType.getNonLValueExprType(Context);
14915 if (Method->isExplicitObjectMemberFunction()) {
14916 ExprResult FnExpr =
14917 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14918 HadMultipleCandidates, E->getBeginLoc());
14919 if (FnExpr.isInvalid())
14920 return ExprError();
14921 Expr *ObjectParam = Exp.get();
14922 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14923 ResultType, VK, Exp.get()->getEndLoc(),
14925 CE->setUsesMemberSyntax(true);
14926 } else {
14927 MemberExpr *ME =
14928 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14930 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14931 HadMultipleCandidates, DeclarationNameInfo(),
14932 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14933
14934 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14935 Exp.get()->getEndLoc(),
14937 }
14938
14939 if (CheckFunctionCall(Method, CE,
14940 Method->getType()->castAs<FunctionProtoType>()))
14941 return ExprError();
14942
14944}
14945
14948 const UnresolvedSetImpl &Fns,
14949 Expr *Input, bool PerformADL) {
14951 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14952 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14953 // TODO: provide better source location info.
14954 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14955
14956 if (checkPlaceholderForOverload(*this, Input))
14957 return ExprError();
14958
14959 Expr *Args[2] = { Input, nullptr };
14960 unsigned NumArgs = 1;
14961
14962 // For post-increment and post-decrement, add the implicit '0' as
14963 // the second argument, so that we know this is a post-increment or
14964 // post-decrement.
14965 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14966 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14967 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14968 SourceLocation());
14969 NumArgs = 2;
14970 }
14971
14972 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14973
14974 if (Input->isTypeDependent()) {
14976 // [C++26][expr.unary.op][expr.pre.incr]
14977 // The * operator yields an lvalue of type
14978 // The pre/post increment operators yied an lvalue.
14979 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14980 VK = VK_LValue;
14981
14982 if (Fns.empty())
14983 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14984 OK_Ordinary, OpLoc, false,
14986
14987 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14989 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14990 if (Fn.isInvalid())
14991 return ExprError();
14992 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14993 Context.DependentTy, VK_PRValue, OpLoc,
14995 }
14996
14997 // Build an empty overload set.
14999
15000 // Add the candidates from the given function set.
15001 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15002
15003 // Add operator candidates that are member functions.
15004 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15005
15006 // Add candidates from ADL.
15007 if (PerformADL) {
15008 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15009 /*ExplicitTemplateArgs*/nullptr,
15010 CandidateSet);
15011 }
15012
15013 // Add builtin operator candidates.
15014 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15015
15016 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15017
15018 // Perform overload resolution.
15020 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15021 case OR_Success: {
15022 // We found a built-in operator or an overloaded operator.
15023 FunctionDecl *FnDecl = Best->Function;
15024
15025 if (FnDecl) {
15026 Expr *Base = nullptr;
15027 // We matched an overloaded operator. Build a call to that
15028 // operator.
15029
15030 // Convert the arguments.
15031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15032 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15033
15034 ExprResult InputInit;
15035 if (Method->isExplicitObjectMemberFunction())
15036 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15037 else
15039 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15040 if (InputInit.isInvalid())
15041 return ExprError();
15042 Base = Input = InputInit.get();
15043 } else {
15044 // Convert the arguments.
15045 ExprResult InputInit
15047 Context,
15048 FnDecl->getParamDecl(0)),
15050 Input);
15051 if (InputInit.isInvalid())
15052 return ExprError();
15053 Input = InputInit.get();
15054 }
15055
15056 // Build the actual expression node.
15057 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15058 Base, HadMultipleCandidates,
15059 OpLoc);
15060 if (FnExpr.isInvalid())
15061 return ExprError();
15062
15063 // Determine the result type.
15064 QualType ResultTy = FnDecl->getReturnType();
15066 ResultTy = ResultTy.getNonLValueExprType(Context);
15067
15068 Args[0] = Input;
15070 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15072 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15073
15074 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15075 return ExprError();
15076
15077 if (CheckFunctionCall(FnDecl, TheCall,
15078 FnDecl->getType()->castAs<FunctionProtoType>()))
15079 return ExprError();
15080 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15081 } else {
15082 // We matched a built-in operator. Convert the arguments, then
15083 // break out so that we will build the appropriate built-in
15084 // operator node.
15086 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15089 if (InputRes.isInvalid())
15090 return ExprError();
15091 Input = InputRes.get();
15092 break;
15093 }
15094 }
15095
15097 // This is an erroneous use of an operator which can be overloaded by
15098 // a non-member function. Check for non-member operators which were
15099 // defined too late to be candidates.
15100 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15101 // FIXME: Recover by calling the found function.
15102 return ExprError();
15103
15104 // No viable function; fall through to handling this as a
15105 // built-in operator, which will produce an error message for us.
15106 break;
15107
15108 case OR_Ambiguous:
15109 CandidateSet.NoteCandidates(
15110 PartialDiagnosticAt(OpLoc,
15111 PDiag(diag::err_ovl_ambiguous_oper_unary)
15113 << Input->getType() << Input->getSourceRange()),
15114 *this, OCD_AmbiguousCandidates, ArgsArray,
15115 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15116 return ExprError();
15117
15118 case OR_Deleted: {
15119 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15120 // object whose method was called. Later in NoteCandidates size of ArgsArray
15121 // is passed further and it eventually ends up compared to number of
15122 // function candidate parameters which never includes the object parameter,
15123 // so slice ArgsArray to make sure apples are compared to apples.
15124 StringLiteral *Msg = Best->Function->getDeletedMessage();
15125 CandidateSet.NoteCandidates(
15126 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15128 << (Msg != nullptr)
15129 << (Msg ? Msg->getString() : StringRef())
15130 << Input->getSourceRange()),
15131 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15132 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15133 return ExprError();
15134 }
15135 }
15136
15137 // Either we found no viable overloaded operator or we matched a
15138 // built-in operator. In either case, fall through to trying to
15139 // build a built-in operation.
15140 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15141}
15142
15145 const UnresolvedSetImpl &Fns,
15146 ArrayRef<Expr *> Args, bool PerformADL) {
15147 SourceLocation OpLoc = CandidateSet.getLocation();
15148
15149 OverloadedOperatorKind ExtraOp =
15152 : OO_None;
15153
15154 // Add the candidates from the given function set. This also adds the
15155 // rewritten candidates using these functions if necessary.
15156 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15157
15158 // As template candidates are not deduced immediately,
15159 // persist the array in the overload set.
15160 ArrayRef<Expr *> ReversedArgs;
15161 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15162 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15163 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15164
15165 // Add operator candidates that are member functions.
15166 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15167 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15168 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15170
15171 // In C++20, also add any rewritten member candidates.
15172 if (ExtraOp) {
15173 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15174 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15175 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15177 }
15178
15179 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15180 // performed for an assignment operator (nor for operator[] nor operator->,
15181 // which don't get here).
15182 if (Op != OO_Equal && PerformADL) {
15183 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15184 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15185 /*ExplicitTemplateArgs*/ nullptr,
15186 CandidateSet);
15187 if (ExtraOp) {
15188 DeclarationName ExtraOpName =
15189 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15190 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15191 /*ExplicitTemplateArgs*/ nullptr,
15192 CandidateSet);
15193 }
15194 }
15195
15196 // Add builtin operator candidates.
15197 //
15198 // FIXME: We don't add any rewritten candidates here. This is strictly
15199 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15200 // resulting in our selecting a rewritten builtin candidate. For example:
15201 //
15202 // enum class E { e };
15203 // bool operator!=(E, E) requires false;
15204 // bool k = E::e != E::e;
15205 //
15206 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15207 // it seems unreasonable to consider rewritten builtin candidates. A core
15208 // issue has been filed proposing to removed this requirement.
15209 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15210}
15211
15214 const UnresolvedSetImpl &Fns, Expr *LHS,
15215 Expr *RHS, bool PerformADL,
15216 bool AllowRewrittenCandidates,
15217 FunctionDecl *DefaultedFn) {
15218 Expr *Args[2] = { LHS, RHS };
15219 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15220
15221 if (!getLangOpts().CPlusPlus20)
15222 AllowRewrittenCandidates = false;
15223
15225
15226 // If either side is type-dependent, create an appropriate dependent
15227 // expression.
15228 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15229 if (Fns.empty()) {
15230 // If there are no functions to store, just build a dependent
15231 // BinaryOperator or CompoundAssignment.
15234 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15235 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15236 Context.DependentTy);
15238 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15240 }
15241
15242 // FIXME: save results of ADL from here?
15243 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15244 // TODO: provide better source location info in DNLoc component.
15245 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15246 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15248 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15249 if (Fn.isInvalid())
15250 return ExprError();
15251 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15252 Context.DependentTy, VK_PRValue, OpLoc,
15254 }
15255
15256 // If this is the .* operator, which is not overloadable, just
15257 // create a built-in binary operator.
15258 if (Opc == BO_PtrMemD) {
15259 auto CheckPlaceholder = [&](Expr *&Arg) {
15261 if (Res.isUsable())
15262 Arg = Res.get();
15263 return !Res.isUsable();
15264 };
15265
15266 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15267 // expression that contains placeholders (in either the LHS or RHS).
15268 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15269 return ExprError();
15270 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15271 }
15272
15273 // Always do placeholder-like conversions on the RHS.
15274 if (checkPlaceholderForOverload(*this, Args[1]))
15275 return ExprError();
15276
15277 // Do placeholder-like conversion on the LHS; note that we should
15278 // not get here with a PseudoObject LHS.
15279 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15280 if (checkPlaceholderForOverload(*this, Args[0]))
15281 return ExprError();
15282
15283 // If this is the assignment operator, we only perform overload resolution
15284 // if the left-hand side is a class or enumeration type. This is actually
15285 // a hack. The standard requires that we do overload resolution between the
15286 // various built-in candidates, but as DR507 points out, this can lead to
15287 // problems. So we do it this way, which pretty much follows what GCC does.
15288 // Note that we go the traditional code path for compound assignment forms.
15289 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15290 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15291
15292 // Build the overload set.
15295 Op, OpLoc, AllowRewrittenCandidates));
15296 if (DefaultedFn)
15297 CandidateSet.exclude(DefaultedFn);
15298 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15299
15300 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15301
15302 // Perform overload resolution.
15304 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15305 case OR_Success: {
15306 // We found a built-in operator or an overloaded operator.
15307 FunctionDecl *FnDecl = Best->Function;
15308
15309 bool IsReversed = Best->isReversed();
15310 if (IsReversed)
15311 std::swap(Args[0], Args[1]);
15312
15313 if (FnDecl) {
15314
15315 if (FnDecl->isInvalidDecl())
15316 return ExprError();
15317
15318 Expr *Base = nullptr;
15319 // We matched an overloaded operator. Build a call to that
15320 // operator.
15321
15322 OverloadedOperatorKind ChosenOp =
15324
15325 // C++2a [over.match.oper]p9:
15326 // If a rewritten operator== candidate is selected by overload
15327 // resolution for an operator@, its return type shall be cv bool
15328 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15329 !FnDecl->getReturnType()->isBooleanType()) {
15330 bool IsExtension =
15332 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15333 : diag::err_ovl_rewrite_equalequal_not_bool)
15334 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15335 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15336 Diag(FnDecl->getLocation(), diag::note_declared_at);
15337 if (!IsExtension)
15338 return ExprError();
15339 }
15340
15341 if (AllowRewrittenCandidates && !IsReversed &&
15342 CandidateSet.getRewriteInfo().isReversible()) {
15343 // We could have reversed this operator, but didn't. Check if some
15344 // reversed form was a viable candidate, and if so, if it had a
15345 // better conversion for either parameter. If so, this call is
15346 // formally ambiguous, and allowing it is an extension.
15348 for (OverloadCandidate &Cand : CandidateSet) {
15349 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15350 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15351 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15353 *this, OpLoc, Cand.Conversions[ArgIdx],
15354 Best->Conversions[ArgIdx]) ==
15356 AmbiguousWith.push_back(Cand.Function);
15357 break;
15358 }
15359 }
15360 }
15361 }
15362
15363 if (!AmbiguousWith.empty()) {
15364 bool AmbiguousWithSelf =
15365 AmbiguousWith.size() == 1 &&
15366 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15367 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15369 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15370 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15371 if (AmbiguousWithSelf) {
15372 Diag(FnDecl->getLocation(),
15373 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15374 // Mark member== const or provide matching != to disallow reversed
15375 // args. Eg.
15376 // struct S { bool operator==(const S&); };
15377 // S()==S();
15378 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15379 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15380 !MD->isConst() &&
15381 !MD->hasCXXExplicitFunctionObjectParameter() &&
15382 Context.hasSameUnqualifiedType(
15383 MD->getFunctionObjectParameterType(),
15384 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15385 Context.hasSameUnqualifiedType(
15386 MD->getFunctionObjectParameterType(),
15387 Args[0]->getType()) &&
15388 Context.hasSameUnqualifiedType(
15389 MD->getFunctionObjectParameterType(),
15390 Args[1]->getType()))
15391 Diag(FnDecl->getLocation(),
15392 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15393 } else {
15394 Diag(FnDecl->getLocation(),
15395 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15396 for (auto *F : AmbiguousWith)
15397 Diag(F->getLocation(),
15398 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15399 }
15400 }
15401 }
15402
15403 // Check for nonnull = nullable.
15404 // This won't be caught in the arg's initialization: the parameter to
15405 // the assignment operator is not marked nonnull.
15406 if (Op == OO_Equal)
15408 Args[1]->getType(), OpLoc);
15409
15410 // Convert the arguments.
15411 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15412 // Best->Access is only meaningful for class members.
15413 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15414
15415 ExprResult Arg0, Arg1;
15416 unsigned ParamIdx = 0;
15417 if (Method->isExplicitObjectMemberFunction()) {
15418 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15419 ParamIdx = 1;
15420 } else {
15422 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15423 }
15426 Context, FnDecl->getParamDecl(ParamIdx)),
15427 SourceLocation(), Args[1]);
15428 if (Arg0.isInvalid() || Arg1.isInvalid())
15429 return ExprError();
15430
15431 Base = Args[0] = Arg0.getAs<Expr>();
15432 Args[1] = RHS = Arg1.getAs<Expr>();
15433 } else {
15434 // Convert the arguments.
15437 FnDecl->getParamDecl(0)),
15438 SourceLocation(), Args[0]);
15439 if (Arg0.isInvalid())
15440 return ExprError();
15441
15442 ExprResult Arg1 =
15445 FnDecl->getParamDecl(1)),
15446 SourceLocation(), Args[1]);
15447 if (Arg1.isInvalid())
15448 return ExprError();
15449 Args[0] = LHS = Arg0.getAs<Expr>();
15450 Args[1] = RHS = Arg1.getAs<Expr>();
15451 }
15452
15453 // Build the actual expression node.
15454 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15455 Best->FoundDecl, Base,
15456 HadMultipleCandidates, OpLoc);
15457 if (FnExpr.isInvalid())
15458 return ExprError();
15459
15460 // Determine the result type.
15461 QualType ResultTy = FnDecl->getReturnType();
15463 ResultTy = ResultTy.getNonLValueExprType(Context);
15464
15465 CallExpr *TheCall;
15466 ArrayRef<const Expr *> ArgsArray(Args, 2);
15467 const Expr *ImplicitThis = nullptr;
15468
15469 // We always create a CXXOperatorCallExpr, even for explicit object
15470 // members; CodeGen should take care not to emit the this pointer.
15472 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15474 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15475
15476 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15477 Method && Method->isImplicitObjectMemberFunction()) {
15478 // Cut off the implicit 'this'.
15479 ImplicitThis = ArgsArray[0];
15480 ArgsArray = ArgsArray.slice(1);
15481 }
15482
15483 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15484 FnDecl))
15485 return ExprError();
15486
15487 if (Op == OO_Equal) {
15488 // Check for a self move.
15489 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15490 // lifetime check.
15492 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15493 Args[1]);
15494 }
15495 if (ImplicitThis) {
15496 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15497 QualType ThisTypeFromDecl = Context.getPointerType(
15498 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15499
15500 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15501 ThisTypeFromDecl);
15502 }
15503
15504 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15505 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15507
15508 ExprResult R = MaybeBindToTemporary(TheCall);
15509 if (R.isInvalid())
15510 return ExprError();
15511
15512 R = CheckForImmediateInvocation(R, FnDecl);
15513 if (R.isInvalid())
15514 return ExprError();
15515
15516 // For a rewritten candidate, we've already reversed the arguments
15517 // if needed. Perform the rest of the rewrite now.
15518 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15519 (Op == OO_Spaceship && IsReversed)) {
15520 if (Op == OO_ExclaimEqual) {
15521 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15522 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15523 } else {
15524 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15525 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15526 Expr *ZeroLiteral =
15528
15531 Ctx.Entity = FnDecl;
15533
15535 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15536 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15537 /*AllowRewrittenCandidates=*/false);
15538
15540 }
15541 if (R.isInvalid())
15542 return ExprError();
15543 } else {
15544 assert(ChosenOp == Op && "unexpected operator name");
15545 }
15546
15547 // Make a note in the AST if we did any rewriting.
15548 if (Best->RewriteKind != CRK_None)
15549 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15550
15551 return R;
15552 } else {
15553 // We matched a built-in operator. Convert the arguments, then
15554 // break out so that we will build the appropriate built-in
15555 // operator node.
15557 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15560 if (ArgsRes0.isInvalid())
15561 return ExprError();
15562 Args[0] = ArgsRes0.get();
15563
15565 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15568 if (ArgsRes1.isInvalid())
15569 return ExprError();
15570 Args[1] = ArgsRes1.get();
15571 break;
15572 }
15573 }
15574
15575 case OR_No_Viable_Function: {
15576 // C++ [over.match.oper]p9:
15577 // If the operator is the operator , [...] and there are no
15578 // viable functions, then the operator is assumed to be the
15579 // built-in operator and interpreted according to clause 5.
15580 if (Opc == BO_Comma)
15581 break;
15582
15583 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15584 // compare result using '==' and '<'.
15585 if (DefaultedFn && Opc == BO_Cmp) {
15586 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15587 Args[1], DefaultedFn);
15588 if (E.isInvalid() || E.isUsable())
15589 return E;
15590 }
15591
15592 // For class as left operand for assignment or compound assignment
15593 // operator do not fall through to handling in built-in, but report that
15594 // no overloaded assignment operator found
15596 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15597 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15598 Args, OpLoc);
15599 DeferDiagsRAII DDR(*this,
15600 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15601 if (Args[0]->getType()->isRecordType() &&
15602 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15603 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15605 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15606 if (Args[0]->getType()->isIncompleteType()) {
15607 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15608 << Args[0]->getType()
15609 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15610 }
15611 } else {
15612 // This is an erroneous use of an operator which can be overloaded by
15613 // a non-member function. Check for non-member operators which were
15614 // defined too late to be candidates.
15615 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15616 // FIXME: Recover by calling the found function.
15617 return ExprError();
15618
15619 // No viable function; try to create a built-in operation, which will
15620 // produce an error. Then, show the non-viable candidates.
15621 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15622 }
15623 assert(Result.isInvalid() &&
15624 "C++ binary operator overloading is missing candidates!");
15625 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15626 return Result;
15627 }
15628
15629 case OR_Ambiguous:
15630 CandidateSet.NoteCandidates(
15631 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15633 << Args[0]->getType()
15634 << Args[1]->getType()
15635 << Args[0]->getSourceRange()
15636 << Args[1]->getSourceRange()),
15638 OpLoc);
15639 return ExprError();
15640
15641 case OR_Deleted: {
15642 if (isImplicitlyDeleted(Best->Function)) {
15643 FunctionDecl *DeletedFD = Best->Function;
15645 if (DFK.isSpecialMember()) {
15646 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15647 << Args[0]->getType() << DFK.asSpecialMember();
15648 } else {
15649 assert(DFK.isComparison());
15650 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15651 << Args[0]->getType() << DeletedFD;
15652 }
15653
15654 // The user probably meant to call this special member. Just
15655 // explain why it's deleted.
15656 NoteDeletedFunction(DeletedFD);
15657 return ExprError();
15658 }
15659
15660 StringLiteral *Msg = Best->Function->getDeletedMessage();
15661 CandidateSet.NoteCandidates(
15663 OpLoc,
15664 PDiag(diag::err_ovl_deleted_oper)
15665 << getOperatorSpelling(Best->Function->getDeclName()
15666 .getCXXOverloadedOperator())
15667 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15668 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15670 OpLoc);
15671 return ExprError();
15672 }
15673 }
15674
15675 // We matched a built-in operator; build it.
15676 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15677}
15678
15680 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15681 FunctionDecl *DefaultedFn) {
15682 const ComparisonCategoryInfo *Info =
15683 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15684 // If we're not producing a known comparison category type, we can't
15685 // synthesize a three-way comparison. Let the caller diagnose this.
15686 if (!Info)
15687 return ExprResult((Expr*)nullptr);
15688
15689 // If we ever want to perform this synthesis more generally, we will need to
15690 // apply the temporary materialization conversion to the operands.
15691 assert(LHS->isGLValue() && RHS->isGLValue() &&
15692 "cannot use prvalue expressions more than once");
15693 Expr *OrigLHS = LHS;
15694 Expr *OrigRHS = RHS;
15695
15696 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15697 // each of them multiple times below.
15698 LHS = new (Context)
15699 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15700 LHS->getObjectKind(), LHS);
15701 RHS = new (Context)
15702 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15703 RHS->getObjectKind(), RHS);
15704
15705 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15706 DefaultedFn);
15707 if (Eq.isInvalid())
15708 return ExprError();
15709
15710 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15711 true, DefaultedFn);
15712 if (Less.isInvalid())
15713 return ExprError();
15714
15716 if (Info->isPartial()) {
15717 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15718 DefaultedFn);
15719 if (Greater.isInvalid())
15720 return ExprError();
15721 }
15722
15723 // Form the list of comparisons we're going to perform.
15724 struct Comparison {
15725 ExprResult Cmp;
15727 } Comparisons[4] =
15733 };
15734
15735 int I = Info->isPartial() ? 3 : 2;
15736
15737 // Combine the comparisons with suitable conditional expressions.
15739 for (; I >= 0; --I) {
15740 // Build a reference to the comparison category constant.
15741 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15742 // FIXME: Missing a constant for a comparison category. Diagnose this?
15743 if (!VI)
15744 return ExprResult((Expr*)nullptr);
15745 ExprResult ThisResult =
15747 if (ThisResult.isInvalid())
15748 return ExprError();
15749
15750 // Build a conditional unless this is the final case.
15751 if (Result.get()) {
15752 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15753 ThisResult.get(), Result.get());
15754 if (Result.isInvalid())
15755 return ExprError();
15756 } else {
15757 Result = ThisResult;
15758 }
15759 }
15760
15761 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15762 // bind the OpaqueValueExprs before they're (repeatedly) used.
15763 Expr *SyntacticForm = BinaryOperator::Create(
15764 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15765 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15767 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15768 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15769}
15770
15772 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15773 MultiExprArg Args, SourceLocation LParenLoc) {
15774
15775 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15776 unsigned NumParams = Proto->getNumParams();
15777 unsigned NumArgsSlots =
15778 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15779 // Build the full argument list for the method call (the implicit object
15780 // parameter is placed at the beginning of the list).
15781 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15782 bool IsError = false;
15783 // Initialize the implicit object parameter.
15784 // Check the argument types.
15785 for (unsigned i = 0; i != NumParams; i++) {
15786 Expr *Arg;
15787 if (i < Args.size()) {
15788 Arg = Args[i];
15789 ExprResult InputInit =
15791 S.Context, Method->getParamDecl(i)),
15792 SourceLocation(), Arg);
15793 IsError |= InputInit.isInvalid();
15794 Arg = InputInit.getAs<Expr>();
15795 } else {
15796 ExprResult DefArg =
15797 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15798 if (DefArg.isInvalid()) {
15799 IsError = true;
15800 break;
15801 }
15802 Arg = DefArg.getAs<Expr>();
15803 }
15804
15805 MethodArgs.push_back(Arg);
15806 }
15807 return IsError;
15808}
15809
15811 SourceLocation RLoc,
15812 Expr *Base,
15813 MultiExprArg ArgExpr) {
15815 Args.push_back(Base);
15816 for (auto *e : ArgExpr) {
15817 Args.push_back(e);
15818 }
15819 DeclarationName OpName =
15820 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15821
15822 SourceRange Range = ArgExpr.empty()
15823 ? SourceRange{}
15824 : SourceRange(ArgExpr.front()->getBeginLoc(),
15825 ArgExpr.back()->getEndLoc());
15826
15827 // If either side is type-dependent, create an appropriate dependent
15828 // expression.
15830
15831 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15832 // CHECKME: no 'operator' keyword?
15833 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15834 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15836 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15837 if (Fn.isInvalid())
15838 return ExprError();
15839 // Can't add any actual overloads yet
15840
15841 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15842 Context.DependentTy, VK_PRValue, RLoc,
15844 }
15845
15846 // Handle placeholders
15847 UnbridgedCastsSet UnbridgedCasts;
15848 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15849 return ExprError();
15850 }
15851 // Build an empty overload set.
15853
15854 // Subscript can only be overloaded as a member function.
15855
15856 // Add operator candidates that are member functions.
15857 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15858
15859 // Add builtin operator candidates.
15860 if (Args.size() == 2)
15861 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15862
15863 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15864
15865 // Perform overload resolution.
15867 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15868 case OR_Success: {
15869 // We found a built-in operator or an overloaded operator.
15870 FunctionDecl *FnDecl = Best->Function;
15871
15872 if (FnDecl) {
15873 // We matched an overloaded operator. Build a call to that
15874 // operator.
15875
15876 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15877
15878 // Convert the arguments.
15880 SmallVector<Expr *, 2> MethodArgs;
15881
15882 // Initialize the object parameter.
15883 if (Method->isExplicitObjectMemberFunction()) {
15884 ExprResult Res =
15886 if (Res.isInvalid())
15887 return ExprError();
15888 Args[0] = Res.get();
15889 ArgExpr = Args;
15890 } else {
15892 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15893 if (Arg0.isInvalid())
15894 return ExprError();
15895
15896 MethodArgs.push_back(Arg0.get());
15897 }
15898
15900 *this, MethodArgs, Method, ArgExpr, LLoc);
15901 if (IsError)
15902 return ExprError();
15903
15904 // Build the actual expression node.
15905 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15906 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15908 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15909 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15910 if (FnExpr.isInvalid())
15911 return ExprError();
15912
15913 // Determine the result type
15914 QualType ResultTy = FnDecl->getReturnType();
15916 ResultTy = ResultTy.getNonLValueExprType(Context);
15917
15919 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15921
15922 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15923 return ExprError();
15924
15925 if (CheckFunctionCall(Method, TheCall,
15926 Method->getType()->castAs<FunctionProtoType>()))
15927 return ExprError();
15928
15930 FnDecl);
15931 } else {
15932 // We matched a built-in operator. Convert the arguments, then
15933 // break out so that we will build the appropriate built-in
15934 // operator node.
15936 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15939 if (ArgsRes0.isInvalid())
15940 return ExprError();
15941 Args[0] = ArgsRes0.get();
15942
15944 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15947 if (ArgsRes1.isInvalid())
15948 return ExprError();
15949 Args[1] = ArgsRes1.get();
15950
15951 break;
15952 }
15953 }
15954
15955 case OR_No_Viable_Function: {
15957 CandidateSet.empty()
15958 ? (PDiag(diag::err_ovl_no_oper)
15959 << Args[0]->getType() << /*subscript*/ 0
15960 << Args[0]->getSourceRange() << Range)
15961 : (PDiag(diag::err_ovl_no_viable_subscript)
15962 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15963 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15964 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15965 return ExprError();
15966 }
15967
15968 case OR_Ambiguous:
15969 if (Args.size() == 2) {
15970 CandidateSet.NoteCandidates(
15972 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15973 << "[]" << Args[0]->getType() << Args[1]->getType()
15974 << Args[0]->getSourceRange() << Range),
15975 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15976 } else {
15977 CandidateSet.NoteCandidates(
15979 PDiag(diag::err_ovl_ambiguous_subscript_call)
15980 << Args[0]->getType()
15981 << Args[0]->getSourceRange() << Range),
15982 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15983 }
15984 return ExprError();
15985
15986 case OR_Deleted: {
15987 StringLiteral *Msg = Best->Function->getDeletedMessage();
15988 CandidateSet.NoteCandidates(
15990 PDiag(diag::err_ovl_deleted_oper)
15991 << "[]" << (Msg != nullptr)
15992 << (Msg ? Msg->getString() : StringRef())
15993 << Args[0]->getSourceRange() << Range),
15994 *this, OCD_AllCandidates, Args, "[]", LLoc);
15995 return ExprError();
15996 }
15997 }
15998
15999 // We matched a built-in operator; build it.
16000 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16001}
16002
16004 SourceLocation LParenLoc,
16005 MultiExprArg Args,
16006 SourceLocation RParenLoc,
16007 Expr *ExecConfig, bool IsExecConfig,
16008 bool AllowRecovery) {
16009 assert(MemExprE->getType() == Context.BoundMemberTy ||
16010 MemExprE->getType() == Context.OverloadTy);
16011
16012 // Dig out the member expression. This holds both the object
16013 // argument and the member function we're referring to.
16014 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16015
16016 // Determine whether this is a call to a pointer-to-member function.
16017 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16018 assert(op->getType() == Context.BoundMemberTy);
16019 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16020
16021 QualType fnType =
16022 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16023
16024 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16025 QualType resultType = proto->getCallResultType(Context);
16027
16028 // Check that the object type isn't more qualified than the
16029 // member function we're calling.
16030 Qualifiers funcQuals = proto->getMethodQuals();
16031
16032 QualType objectType = op->getLHS()->getType();
16033 if (op->getOpcode() == BO_PtrMemI)
16034 objectType = objectType->castAs<PointerType>()->getPointeeType();
16035 Qualifiers objectQuals = objectType.getQualifiers();
16036
16037 Qualifiers difference = objectQuals - funcQuals;
16038 difference.removeObjCGCAttr();
16039 difference.removeAddressSpace();
16040 if (difference) {
16041 std::string qualsString = difference.getAsString();
16042 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16043 << fnType.getUnqualifiedType()
16044 << qualsString
16045 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16046 }
16047
16049 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16051
16052 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16053 call, nullptr))
16054 return ExprError();
16055
16056 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16057 return ExprError();
16058
16059 if (CheckOtherCall(call, proto))
16060 return ExprError();
16061
16062 return MaybeBindToTemporary(call);
16063 }
16064
16065 // We only try to build a recovery expr at this level if we can preserve
16066 // the return type, otherwise we return ExprError() and let the caller
16067 // recover.
16068 auto BuildRecoveryExpr = [&](QualType Type) {
16069 if (!AllowRecovery)
16070 return ExprError();
16071 std::vector<Expr *> SubExprs = {MemExprE};
16072 llvm::append_range(SubExprs, Args);
16073 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16074 Type);
16075 };
16076 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16077 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16078 RParenLoc, CurFPFeatureOverrides());
16079
16080 UnbridgedCastsSet UnbridgedCasts;
16081 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16082 return ExprError();
16083
16084 MemberExpr *MemExpr;
16085 CXXMethodDecl *Method = nullptr;
16086 bool HadMultipleCandidates = false;
16087 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16088 NestedNameSpecifier Qualifier = std::nullopt;
16089 if (isa<MemberExpr>(NakedMemExpr)) {
16090 MemExpr = cast<MemberExpr>(NakedMemExpr);
16092 FoundDecl = MemExpr->getFoundDecl();
16093 Qualifier = MemExpr->getQualifier();
16094 UnbridgedCasts.restore();
16095 } else {
16096 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16097 Qualifier = UnresExpr->getQualifier();
16098
16099 QualType ObjectType = UnresExpr->getBaseType();
16100 Expr::Classification ObjectClassification
16102 : UnresExpr->getBase()->Classify(Context);
16103
16104 // Add overload candidates
16105 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16107
16108 // FIXME: avoid copy.
16109 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16110 if (UnresExpr->hasExplicitTemplateArgs()) {
16111 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16112 TemplateArgs = &TemplateArgsBuffer;
16113 }
16114
16116 E = UnresExpr->decls_end(); I != E; ++I) {
16117
16118 QualType ExplicitObjectType = ObjectType;
16119
16120 NamedDecl *Func = *I;
16121 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16123 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16124
16125 bool HasExplicitParameter = false;
16126 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16127 M && M->hasCXXExplicitFunctionObjectParameter())
16128 HasExplicitParameter = true;
16129 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16130 M &&
16131 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16132 HasExplicitParameter = true;
16133
16134 if (HasExplicitParameter)
16135 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16136
16137 // Microsoft supports direct constructor calls.
16138 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16140 CandidateSet,
16141 /*SuppressUserConversions*/ false);
16142 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16143 // If explicit template arguments were provided, we can't call a
16144 // non-template member function.
16145 if (TemplateArgs)
16146 continue;
16147
16148 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16149 ObjectClassification, Args, CandidateSet,
16150 /*SuppressUserConversions=*/false);
16151 } else {
16153 I.getPair(), ActingDC, TemplateArgs,
16154 ExplicitObjectType, ObjectClassification,
16155 Args, CandidateSet,
16156 /*SuppressUserConversions=*/false);
16157 }
16158 }
16159
16160 HadMultipleCandidates = (CandidateSet.size() > 1);
16161
16162 DeclarationName DeclName = UnresExpr->getMemberName();
16163
16164 UnbridgedCasts.restore();
16165
16167 bool Succeeded = false;
16168 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16169 Best)) {
16170 case OR_Success:
16171 Method = cast<CXXMethodDecl>(Best->Function);
16172 FoundDecl = Best->FoundDecl;
16173 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16174 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16175 break;
16176 // If FoundDecl is different from Method (such as if one is a template
16177 // and the other a specialization), make sure DiagnoseUseOfDecl is
16178 // called on both.
16179 // FIXME: This would be more comprehensively addressed by modifying
16180 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16181 // being used.
16182 if (Method != FoundDecl.getDecl() &&
16184 break;
16185 Succeeded = true;
16186 break;
16187
16189 CandidateSet.NoteCandidates(
16191 UnresExpr->getMemberLoc(),
16192 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16193 << DeclName << MemExprE->getSourceRange()),
16194 *this, OCD_AllCandidates, Args);
16195 break;
16196 case OR_Ambiguous:
16197 CandidateSet.NoteCandidates(
16198 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16199 PDiag(diag::err_ovl_ambiguous_member_call)
16200 << DeclName << MemExprE->getSourceRange()),
16201 *this, OCD_AmbiguousCandidates, Args);
16202 break;
16203 case OR_Deleted:
16205 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16206 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16207 break;
16208 }
16209 // Overload resolution fails, try to recover.
16210 if (!Succeeded)
16211 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16212
16213 ExprResult Res =
16214 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16215 if (Res.isInvalid())
16216 return ExprError();
16217 MemExprE = Res.get();
16218
16219 // If overload resolution picked a static member
16220 // build a non-member call based on that function.
16221 if (Method->isStatic()) {
16222 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16223 ExecConfig, IsExecConfig);
16224 }
16225
16226 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16227 }
16228
16229 QualType ResultType = Method->getReturnType();
16231 ResultType = ResultType.getNonLValueExprType(Context);
16232
16233 assert(Method && "Member call to something that isn't a method?");
16234 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16235
16236 CallExpr *TheCall = nullptr;
16238 if (Method->isExplicitObjectMemberFunction()) {
16239 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16240 NewArgs))
16241 return ExprError();
16242
16243 // Build the actual expression node.
16244 ExprResult FnExpr =
16245 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16246 HadMultipleCandidates, MemExpr->getExprLoc());
16247 if (FnExpr.isInvalid())
16248 return ExprError();
16249
16250 TheCall =
16251 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16252 CurFPFeatureOverrides(), Proto->getNumParams());
16253 TheCall->setUsesMemberSyntax(true);
16254 } else {
16255 // Convert the object argument (for a non-static member function call).
16257 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16258 if (ObjectArg.isInvalid())
16259 return ExprError();
16260 MemExpr->setBase(ObjectArg.get());
16261 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16262 RParenLoc, CurFPFeatureOverrides(),
16263 Proto->getNumParams());
16264 }
16265
16266 // Check for a valid return type.
16267 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16268 TheCall, Method))
16269 return BuildRecoveryExpr(ResultType);
16270
16271 // Convert the rest of the arguments
16272 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16273 RParenLoc))
16274 return BuildRecoveryExpr(ResultType);
16275
16276 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16277
16278 if (CheckFunctionCall(Method, TheCall, Proto))
16279 return ExprError();
16280
16281 // In the case the method to call was not selected by the overloading
16282 // resolution process, we still need to handle the enable_if attribute. Do
16283 // that here, so it will not hide previous -- and more relevant -- errors.
16284 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16285 if (const EnableIfAttr *Attr =
16286 CheckEnableIf(Method, LParenLoc, Args, true)) {
16287 Diag(MemE->getMemberLoc(),
16288 diag::err_ovl_no_viable_member_function_in_call)
16289 << Method << Method->getSourceRange();
16290 Diag(Method->getLocation(),
16291 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16292 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16293 return ExprError();
16294 }
16295 }
16296
16298 TheCall->getDirectCallee()->isPureVirtual()) {
16299 const FunctionDecl *MD = TheCall->getDirectCallee();
16300
16301 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16303 Diag(MemExpr->getBeginLoc(),
16304 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16306 << MD->getParent();
16307
16308 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16309 if (getLangOpts().AppleKext)
16310 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16311 << MD->getParent() << MD->getDeclName();
16312 }
16313 }
16314
16315 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16316 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16317 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16318 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16319 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16320 MemExpr->getMemberLoc());
16321 }
16322
16324 TheCall->getDirectCallee());
16325}
16326
16329 SourceLocation LParenLoc,
16330 MultiExprArg Args,
16331 SourceLocation RParenLoc) {
16332 if (checkPlaceholderForOverload(*this, Obj))
16333 return ExprError();
16334 ExprResult Object = Obj;
16335
16336 UnbridgedCastsSet UnbridgedCasts;
16337 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16338 return ExprError();
16339
16340 assert(Object.get()->getType()->isRecordType() &&
16341 "Requires object type argument");
16342
16343 // C++ [over.call.object]p1:
16344 // If the primary-expression E in the function call syntax
16345 // evaluates to a class object of type "cv T", then the set of
16346 // candidate functions includes at least the function call
16347 // operators of T. The function call operators of T are obtained by
16348 // ordinary lookup of the name operator() in the context of
16349 // (E).operator().
16350 OverloadCandidateSet CandidateSet(LParenLoc,
16352 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16353
16354 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16355 diag::err_incomplete_object_call, Object.get()))
16356 return true;
16357
16358 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16359 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16362
16363 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16364 Oper != OperEnd; ++Oper) {
16365 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16366 Object.get()->Classify(Context), Args, CandidateSet,
16367 /*SuppressUserConversion=*/false);
16368 }
16369
16370 // When calling a lambda, both the call operator, and
16371 // the conversion operator to function pointer
16372 // are considered. But when constraint checking
16373 // on the call operator fails, it will also fail on the
16374 // conversion operator as the constraints are always the same.
16375 // As the user probably does not intend to perform a surrogate call,
16376 // we filter them out to produce better error diagnostics, ie to avoid
16377 // showing 2 failed overloads instead of one.
16378 bool IgnoreSurrogateFunctions = false;
16379 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16380 const OverloadCandidate &Candidate = *CandidateSet.begin();
16381 if (!Candidate.Viable &&
16383 IgnoreSurrogateFunctions = true;
16384 }
16385
16386 // C++ [over.call.object]p2:
16387 // In addition, for each (non-explicit in C++0x) conversion function
16388 // declared in T of the form
16389 //
16390 // operator conversion-type-id () cv-qualifier;
16391 //
16392 // where cv-qualifier is the same cv-qualification as, or a
16393 // greater cv-qualification than, cv, and where conversion-type-id
16394 // denotes the type "pointer to function of (P1,...,Pn) returning
16395 // R", or the type "reference to pointer to function of
16396 // (P1,...,Pn) returning R", or the type "reference to function
16397 // of (P1,...,Pn) returning R", a surrogate call function [...]
16398 // is also considered as a candidate function. Similarly,
16399 // surrogate call functions are added to the set of candidate
16400 // functions for each conversion function declared in an
16401 // accessible base class provided the function is not hidden
16402 // within T by another intervening declaration.
16403 const auto &Conversions = Record->getVisibleConversionFunctions();
16404 for (auto I = Conversions.begin(), E = Conversions.end();
16405 !IgnoreSurrogateFunctions && I != E; ++I) {
16406 NamedDecl *D = *I;
16407 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16408 if (isa<UsingShadowDecl>(D))
16409 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16410
16411 // Skip over templated conversion functions; they aren't
16412 // surrogates.
16414 continue;
16415
16417 if (!Conv->isExplicit()) {
16418 // Strip the reference type (if any) and then the pointer type (if
16419 // any) to get down to what might be a function type.
16420 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16421 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16422 ConvType = ConvPtrType->getPointeeType();
16423
16424 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16425 {
16426 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16427 Object.get(), Args, CandidateSet);
16428 }
16429 }
16430 }
16431
16432 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16433
16434 // Perform overload resolution.
16436 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16437 Best)) {
16438 case OR_Success:
16439 // Overload resolution succeeded; we'll build the appropriate call
16440 // below.
16441 break;
16442
16443 case OR_No_Viable_Function: {
16445 CandidateSet.empty()
16446 ? (PDiag(diag::err_ovl_no_oper)
16447 << Object.get()->getType() << /*call*/ 1
16448 << Object.get()->getSourceRange())
16449 : (PDiag(diag::err_ovl_no_viable_object_call)
16450 << Object.get()->getType() << Object.get()->getSourceRange());
16451 CandidateSet.NoteCandidates(
16452 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16453 OCD_AllCandidates, Args);
16454 break;
16455 }
16456 case OR_Ambiguous:
16457 if (!R.isAmbiguous())
16458 CandidateSet.NoteCandidates(
16459 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16460 PDiag(diag::err_ovl_ambiguous_object_call)
16461 << Object.get()->getType()
16462 << Object.get()->getSourceRange()),
16463 *this, OCD_AmbiguousCandidates, Args);
16464 break;
16465
16466 case OR_Deleted: {
16467 // FIXME: Is this diagnostic here really necessary? It seems that
16468 // 1. we don't have any tests for this diagnostic, and
16469 // 2. we already issue err_deleted_function_use for this later on anyway.
16470 StringLiteral *Msg = Best->Function->getDeletedMessage();
16471 CandidateSet.NoteCandidates(
16472 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16473 PDiag(diag::err_ovl_deleted_object_call)
16474 << Object.get()->getType() << (Msg != nullptr)
16475 << (Msg ? Msg->getString() : StringRef())
16476 << Object.get()->getSourceRange()),
16477 *this, OCD_AllCandidates, Args);
16478 break;
16479 }
16480 }
16481
16482 if (Best == CandidateSet.end())
16483 return true;
16484
16485 UnbridgedCasts.restore();
16486
16487 if (Best->Function == nullptr) {
16488 // Since there is no function declaration, this is one of the
16489 // surrogate candidates. Dig out the conversion function.
16490 CXXConversionDecl *Conv
16492 Best->Conversions[0].UserDefined.ConversionFunction);
16493
16494 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16495 Best->FoundDecl);
16496 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16497 return ExprError();
16498 assert(Conv == Best->FoundDecl.getDecl() &&
16499 "Found Decl & conversion-to-functionptr should be same, right?!");
16500 // We selected one of the surrogate functions that converts the
16501 // object parameter to a function pointer. Perform the conversion
16502 // on the object argument, then let BuildCallExpr finish the job.
16503
16504 // Create an implicit member expr to refer to the conversion operator.
16505 // and then call it.
16506 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16507 Conv, HadMultipleCandidates);
16508 if (Call.isInvalid())
16509 return ExprError();
16510 // Record usage of conversion in an implicit cast.
16512 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16513 nullptr, VK_PRValue, CurFPFeatureOverrides());
16514
16515 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16516 }
16517
16518 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16519
16520 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16521 // that calls this method, using Object for the implicit object
16522 // parameter and passing along the remaining arguments.
16523 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16524
16525 // An error diagnostic has already been printed when parsing the declaration.
16526 if (Method->isInvalidDecl())
16527 return ExprError();
16528
16529 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16530 unsigned NumParams = Proto->getNumParams();
16531
16532 DeclarationNameInfo OpLocInfo(
16533 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16534 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16535 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16536 Obj, HadMultipleCandidates,
16537 OpLocInfo.getLoc(),
16538 OpLocInfo.getInfo());
16539 if (NewFn.isInvalid())
16540 return true;
16541
16542 SmallVector<Expr *, 8> MethodArgs;
16543 MethodArgs.reserve(NumParams + 1);
16544
16545 bool IsError = false;
16546
16547 // Initialize the object parameter.
16549 if (Method->isExplicitObjectMemberFunction()) {
16550 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16551 } else {
16553 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16554 if (ObjRes.isInvalid())
16555 IsError = true;
16556 else
16557 Object = ObjRes;
16558 MethodArgs.push_back(Object.get());
16559 }
16560
16562 *this, MethodArgs, Method, Args, LParenLoc);
16563
16564 // If this is a variadic call, handle args passed through "...".
16565 if (Proto->isVariadic()) {
16566 // Promote the arguments (C99 6.5.2.2p7).
16567 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16569 Args[i], VariadicCallType::Method, nullptr);
16570 IsError |= Arg.isInvalid();
16571 MethodArgs.push_back(Arg.get());
16572 }
16573 }
16574
16575 if (IsError)
16576 return true;
16577
16578 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16579
16580 // Once we've built TheCall, all of the expressions are properly owned.
16581 QualType ResultTy = Method->getReturnType();
16583 ResultTy = ResultTy.getNonLValueExprType(Context);
16584
16586 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16588
16589 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16590 return true;
16591
16592 if (CheckFunctionCall(Method, TheCall, Proto))
16593 return true;
16594
16596}
16597
16599 SourceLocation OpLoc,
16600 bool *NoArrowOperatorFound) {
16601 assert(Base->getType()->isRecordType() &&
16602 "left-hand side must have class type");
16603
16605 return ExprError();
16606
16607 SourceLocation Loc = Base->getExprLoc();
16608
16609 // C++ [over.ref]p1:
16610 //
16611 // [...] An expression x->m is interpreted as (x.operator->())->m
16612 // for a class object x of type T if T::operator->() exists and if
16613 // the operator is selected as the best match function by the
16614 // overload resolution mechanism (13.3).
16615 DeclarationName OpName =
16616 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16618
16619 if (RequireCompleteType(Loc, Base->getType(),
16620 diag::err_typecheck_incomplete_tag, Base))
16621 return ExprError();
16622
16623 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16624 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16626
16627 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16628 Oper != OperEnd; ++Oper) {
16629 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16630 {}, CandidateSet,
16631 /*SuppressUserConversion=*/false);
16632 }
16633
16634 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16635
16636 // Perform overload resolution.
16638 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16639 case OR_Success:
16640 // Overload resolution succeeded; we'll build the call below.
16641 break;
16642
16643 case OR_No_Viable_Function: {
16644 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16645 if (CandidateSet.empty()) {
16646 QualType BaseType = Base->getType();
16647 if (NoArrowOperatorFound) {
16648 // Report this specific error to the caller instead of emitting a
16649 // diagnostic, as requested.
16650 *NoArrowOperatorFound = true;
16651 return ExprError();
16652 }
16653 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16654 << BaseType << Base->getSourceRange();
16655 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16656 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16657 << FixItHint::CreateReplacement(OpLoc, ".");
16658 }
16659 } else
16660 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16661 << "operator->" << Base->getSourceRange();
16662 CandidateSet.NoteCandidates(*this, Base, Cands);
16663 return ExprError();
16664 }
16665 case OR_Ambiguous:
16666 if (!R.isAmbiguous())
16667 CandidateSet.NoteCandidates(
16668 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16669 << "->" << Base->getType()
16670 << Base->getSourceRange()),
16672 return ExprError();
16673
16674 case OR_Deleted: {
16675 StringLiteral *Msg = Best->Function->getDeletedMessage();
16676 CandidateSet.NoteCandidates(
16677 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16678 << "->" << (Msg != nullptr)
16679 << (Msg ? Msg->getString() : StringRef())
16680 << Base->getSourceRange()),
16681 *this, OCD_AllCandidates, Base);
16682 return ExprError();
16683 }
16684 }
16685
16686 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16687
16688 // Convert the object parameter.
16689 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16690
16691 if (Method->isExplicitObjectMemberFunction()) {
16693 if (R.isInvalid())
16694 return ExprError();
16695 Base = R.get();
16696 } else {
16698 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16699 if (BaseResult.isInvalid())
16700 return ExprError();
16701 Base = BaseResult.get();
16702 }
16703
16704 // Build the operator call.
16705 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16706 Base, HadMultipleCandidates, OpLoc);
16707 if (FnExpr.isInvalid())
16708 return ExprError();
16709
16710 QualType ResultTy = Method->getReturnType();
16712 ResultTy = ResultTy.getNonLValueExprType(Context);
16713
16714 CallExpr *TheCall =
16715 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16716 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16717
16718 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16719 return ExprError();
16720
16721 if (CheckFunctionCall(Method, TheCall,
16722 Method->getType()->castAs<FunctionProtoType>()))
16723 return ExprError();
16724
16726}
16727
16729 DeclarationNameInfo &SuffixInfo,
16730 ArrayRef<Expr*> Args,
16731 SourceLocation LitEndLoc,
16732 TemplateArgumentListInfo *TemplateArgs) {
16733 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16734
16735 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16737 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16738 TemplateArgs);
16739
16740 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16741
16742 // Perform overload resolution. This will usually be trivial, but might need
16743 // to perform substitutions for a literal operator template.
16745 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16746 case OR_Success:
16747 case OR_Deleted:
16748 break;
16749
16751 CandidateSet.NoteCandidates(
16752 PartialDiagnosticAt(UDSuffixLoc,
16753 PDiag(diag::err_ovl_no_viable_function_in_call)
16754 << R.getLookupName()),
16755 *this, OCD_AllCandidates, Args);
16756 return ExprError();
16757
16758 case OR_Ambiguous:
16759 CandidateSet.NoteCandidates(
16760 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16761 << R.getLookupName()),
16762 *this, OCD_AmbiguousCandidates, Args);
16763 return ExprError();
16764 }
16765
16766 FunctionDecl *FD = Best->Function;
16767 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16768 nullptr, HadMultipleCandidates,
16769 SuffixInfo.getLoc(),
16770 SuffixInfo.getInfo());
16771 if (Fn.isInvalid())
16772 return true;
16773
16774 // Check the argument types. This should almost always be a no-op, except
16775 // that array-to-pointer decay is applied to string literals.
16776 Expr *ConvArgs[2];
16777 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16780 SourceLocation(), Args[ArgIdx]);
16781 if (InputInit.isInvalid())
16782 return true;
16783 ConvArgs[ArgIdx] = InputInit.get();
16784 }
16785
16786 QualType ResultTy = FD->getReturnType();
16788 ResultTy = ResultTy.getNonLValueExprType(Context);
16789
16791 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16792 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16793
16794 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16795 return ExprError();
16796
16797 if (CheckFunctionCall(FD, UDL, nullptr))
16798 return ExprError();
16799
16801}
16802
16805 SourceLocation RangeLoc,
16806 const DeclarationNameInfo &NameInfo,
16807 LookupResult &MemberLookup,
16808 OverloadCandidateSet *CandidateSet,
16809 Expr *Range, ExprResult *CallExpr) {
16810 Scope *S = nullptr;
16811
16813 if (!MemberLookup.empty()) {
16814 ExprResult MemberRef =
16815 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16816 /*IsPtr=*/false, CXXScopeSpec(),
16817 /*TemplateKWLoc=*/SourceLocation(),
16818 /*FirstQualifierInScope=*/nullptr,
16819 MemberLookup,
16820 /*TemplateArgs=*/nullptr, S);
16821 if (MemberRef.isInvalid()) {
16822 *CallExpr = ExprError();
16823 return FRS_DiagnosticIssued;
16824 }
16825 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16826 if (CallExpr->isInvalid()) {
16827 *CallExpr = ExprError();
16828 return FRS_DiagnosticIssued;
16829 }
16830 } else {
16831 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16833 NameInfo, UnresolvedSet<0>());
16834 if (FnR.isInvalid())
16835 return FRS_DiagnosticIssued;
16837
16838 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16839 CandidateSet, CallExpr);
16840 if (CandidateSet->empty() || CandidateSetError) {
16841 *CallExpr = ExprError();
16842 return FRS_NoViableFunction;
16843 }
16845 OverloadingResult OverloadResult =
16846 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16847
16848 if (OverloadResult == OR_No_Viable_Function) {
16849 *CallExpr = ExprError();
16850 return FRS_NoViableFunction;
16851 }
16852 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16853 Loc, nullptr, CandidateSet, &Best,
16854 OverloadResult,
16855 /*AllowTypoCorrection=*/false);
16856 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16857 *CallExpr = ExprError();
16858 return FRS_DiagnosticIssued;
16859 }
16860 }
16861 return FRS_Success;
16862}
16863
16865 FunctionDecl *Fn) {
16866 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16867 ExprResult SubExpr =
16868 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16869 if (SubExpr.isInvalid())
16870 return ExprError();
16871 if (SubExpr.get() == PE->getSubExpr())
16872 return PE;
16873
16874 return new (Context)
16875 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16876 }
16877
16878 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16879 ExprResult SubExpr =
16880 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16881 if (SubExpr.isInvalid())
16882 return ExprError();
16883 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16884 SubExpr.get()->getType()) &&
16885 "Implicit cast type cannot be determined from overload");
16886 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16887 if (SubExpr.get() == ICE->getSubExpr())
16888 return ICE;
16889
16890 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16891 SubExpr.get(), nullptr, ICE->getValueKind(),
16893 }
16894
16895 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16896 if (!GSE->isResultDependent()) {
16897 ExprResult SubExpr =
16898 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16899 if (SubExpr.isInvalid())
16900 return ExprError();
16901 if (SubExpr.get() == GSE->getResultExpr())
16902 return GSE;
16903
16904 // Replace the resulting type information before rebuilding the generic
16905 // selection expression.
16906 ArrayRef<Expr *> A = GSE->getAssocExprs();
16907 SmallVector<Expr *, 4> AssocExprs(A);
16908 unsigned ResultIdx = GSE->getResultIndex();
16909 AssocExprs[ResultIdx] = SubExpr.get();
16910
16911 if (GSE->isExprPredicate())
16913 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16914 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16915 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16916 ResultIdx);
16918 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16919 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16920 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16921 ResultIdx);
16922 }
16923 // Rather than fall through to the unreachable, return the original generic
16924 // selection expression.
16925 return GSE;
16926 }
16927
16928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16929 assert(UnOp->getOpcode() == UO_AddrOf &&
16930 "Can only take the address of an overloaded function");
16931 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16932 if (!Method->isImplicitObjectMemberFunction()) {
16933 // Do nothing: the address of static and
16934 // explicit object member functions is a (non-member) function pointer.
16935 } else {
16936 // Fix the subexpression, which really has to be an
16937 // UnresolvedLookupExpr holding an overloaded member function
16938 // or template.
16939 ExprResult SubExpr =
16940 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16941 if (SubExpr.isInvalid())
16942 return ExprError();
16943 if (SubExpr.get() == UnOp->getSubExpr())
16944 return UnOp;
16945
16946 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16947 SubExpr.get(), Method))
16948 return ExprError();
16949
16950 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16951 "fixed to something other than a decl ref");
16952 NestedNameSpecifier Qualifier =
16953 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
16954 assert(Qualifier &&
16955 "fixed to a member ref with no nested name qualifier");
16956
16957 // We have taken the address of a pointer to member
16958 // function. Perform the computation here so that we get the
16959 // appropriate pointer to member type.
16960 QualType MemPtrType = Context.getMemberPointerType(
16961 Fn->getType(), Qualifier,
16962 cast<CXXRecordDecl>(Method->getDeclContext()));
16963 // Under the MS ABI, lock down the inheritance model now.
16964 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16965 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16966
16967 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16968 MemPtrType, VK_PRValue, OK_Ordinary,
16969 UnOp->getOperatorLoc(), false,
16971 }
16972 }
16973 ExprResult SubExpr =
16974 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16975 if (SubExpr.isInvalid())
16976 return ExprError();
16977 if (SubExpr.get() == UnOp->getSubExpr())
16978 return UnOp;
16979
16980 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16981 SubExpr.get());
16982 }
16983
16984 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16985 if (Found.getAccess() == AS_none) {
16987 }
16988 // FIXME: avoid copy.
16989 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16990 if (ULE->hasExplicitTemplateArgs()) {
16991 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16992 TemplateArgs = &TemplateArgsBuffer;
16993 }
16994
16995 QualType Type = Fn->getType();
16996 ExprValueKind ValueKind =
16997 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16998 ? VK_LValue
16999 : VK_PRValue;
17000
17001 // FIXME: Duplicated from BuildDeclarationNameExpr.
17002 if (unsigned BID = Fn->getBuiltinID()) {
17003 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17004 Type = Context.BuiltinFnTy;
17005 ValueKind = VK_PRValue;
17006 }
17007 }
17008
17010 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17011 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17012 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17013 return DRE;
17014 }
17015
17016 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17017 // FIXME: avoid copy.
17018 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17019 if (MemExpr->hasExplicitTemplateArgs()) {
17020 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17021 TemplateArgs = &TemplateArgsBuffer;
17022 }
17023
17024 Expr *Base;
17025
17026 // If we're filling in a static method where we used to have an
17027 // implicit member access, rewrite to a simple decl ref.
17028 if (MemExpr->isImplicitAccess()) {
17029 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17031 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17032 MemExpr->getQualifierLoc(), Found.getDecl(),
17033 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17034 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17035 return DRE;
17036 } else {
17037 SourceLocation Loc = MemExpr->getMemberLoc();
17038 if (MemExpr->getQualifier())
17039 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17040 Base =
17041 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17042 }
17043 } else
17044 Base = MemExpr->getBase();
17045
17046 ExprValueKind valueKind;
17047 QualType type;
17048 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17049 valueKind = VK_LValue;
17050 type = Fn->getType();
17051 } else {
17052 valueKind = VK_PRValue;
17053 type = Context.BoundMemberTy;
17054 }
17055
17056 return BuildMemberExpr(
17057 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17058 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17059 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17060 type, valueKind, OK_Ordinary, TemplateArgs);
17061 }
17062
17063 llvm_unreachable("Invalid reference to overloaded function");
17064}
17065
17071
17072bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17074 if (!PartialOverloading || !Function)
17075 return true;
17076 if (Function->isVariadic())
17077 return false;
17078 if (const auto *Proto =
17079 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17080 if (Proto->isTemplateVariadic())
17081 return false;
17082 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17083 if (const auto *Proto =
17084 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17085 if (Proto->isTemplateVariadic())
17086 return false;
17087 return true;
17088}
17089
17091 DeclarationName Name,
17092 OverloadCandidateSet &CandidateSet,
17093 FunctionDecl *Fn, MultiExprArg Args,
17094 bool IsMember) {
17095 StringLiteral *Msg = Fn->getDeletedMessage();
17096 CandidateSet.NoteCandidates(
17097 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17098 << IsMember << Name << (Msg != nullptr)
17099 << (Msg ? Msg->getString() : StringRef())
17100 << Range),
17101 *this, OCD_AllCandidates, Args);
17102}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:109
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
__device__ __2f16 b
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:463
bool isFloat() const
Definition APValue.h:468
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
DeclarationNameTable DeclarationNames
Definition ASTContext.h:776
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType NullPtrTy
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:892
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
CanQualType WCharTy
CanQualType Char8Ty
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:279
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8093
Attr - This represents one attribute.
Definition Attr.h:44
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2175
StringRef getOpcodeStr() const
Definition Expr.h:4038
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2128
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:4979
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
Pointer to a block type.
Definition TypeBase.h:3542
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3019
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3056
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2979
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2983
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:692
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition ExprCXX.cpp:624
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1977
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:286
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1513
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3041
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3259
Represents a canonical, potentially-qualified type.
bool isAtLeastAsQualifiedAs(CanQual< T > Other, const ASTContext &Ctx) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
static CanQual< Type > CreateUnsafe(QualType Other)
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isVolatileQualified() const
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:5001
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition Expr.h:1463
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:263
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:777
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:762
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:753
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1948
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1932
const Expr * getExpr() const
Definition DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2354
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:337
bool isLValue() const
Definition Expr.h:387
bool isPRValue() const
Definition Expr.h:390
bool isXValue() const
Definition Expr.h:388
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:395
bool isRValue() const
Definition Expr.h:391
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3334
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4205
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4042
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:412
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4181
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3750
param_iterator param_end()
Definition Decl.h:2787
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3654
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3853
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4252
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4301
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3125
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4317
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4245
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3857
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4118
bool isConsteval() const
Definition Decl.h:2482
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3698
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2862
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition Decl.cpp:3703
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3814
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5770
unsigned getNumParams() const
Definition TypeBase.h:5544
Qualifiers getMethodQuals() const
Definition TypeBase.h:5692
QualType getParamType(unsigned i) const
Definition TypeBase.h:5546
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5670
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5706
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4573
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4644
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4501
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4462
ExtInfo getExtInfo() const
Definition TypeBase.h:4818
CallingConv getCallConv() const
Definition TypeBase.h:4817
QualType getReturnType() const
Definition TypeBase.h:4802
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4830
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition Expr.cpp:4601
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:615
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:666
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:763
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:670
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:820
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:674
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:805
bool hasInitializerListContainerType() const
Definition Overload.h:802
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:727
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:809
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:678
QualType getInitializerListContainerType() const
Definition Overload.h:812
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5348
unsigned getNumInits() const
Definition Expr.h:5263
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2491
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2509
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3617
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Represents the results of name lookup.
Definition Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition Lookup.h:643
const UnresolvedSetImpl & asUnresolvedSet() const
Definition Lookup.h:354
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3487
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3409
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3395
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3375
void setBase(Expr *E)
Definition Expr.h:3374
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1790
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3493
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3385
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3685
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5457
QualType getPointeeType() const
Definition TypeBase.h:3671
Describes a module or submodule.
Definition Module.h:144
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7856
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7912
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8001
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7970
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7924
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7964
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7976
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void AddDeferredTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition Overload.h:1353
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1451
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1385
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1401
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1343
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1542
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1178
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1174
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1169
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition Overload.h:1361
SourceLocation getLocation() const
Definition Overload.h:1341
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1416
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1342
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1376
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3130
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3282
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3191
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3246
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3243
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3221
decls_iterator decls_begin() const
Definition ExprCXX.h:3223
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3234
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3256
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3252
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3344
decls_iterator decls_end() const
Definition ExprCXX.h:3226
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3240
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3050
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5073
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8378
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8372
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8383
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1225
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8294
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8420
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8334
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8479
QualType getCanonicalType() const
Definition TypeBase.h:8346
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8388
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8448
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8367
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8415
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8340
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8459
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8326
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8234
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8241
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4666
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:860
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
bool hasOnlyConst() const
Definition TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasRestrict() const
Definition TypeBase.h:477
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeUnaligned()
Definition TypeBase.h:515
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3635
Represents a struct/union/class.
Definition Decl.h:4312
field_range fields() const
Definition Decl.h:4515
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
Definition SemaARM.cpp:1473
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1517
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:186
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:134
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition SemaCUDA.cpp:374
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:315
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:321
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:228
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10268
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6321
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6350
RAII class to control scope of DeferDiags.
Definition Sema.h:10002
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12392
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12425
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10018
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9291
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9318
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9303
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9299
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:405
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:167
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
SemaCUDA & CUDA()
Definition Sema.h:1445
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10351
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10354
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10360
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10358
@ AR_dependent
Definition Sema.h:1660
@ AR_accessible
Definition Sema.h:1658
@ AR_inaccessible
Definition Sema.h:1659
@ AR_delayed
Definition Sema.h:1661
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2049
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1647
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1283
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:680
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition Sema.h:1490
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:748
ASTContext & getASTContext() const
Definition Sema.h:925
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
@ FRS_Success
Definition Sema.h:10739
@ FRS_DiagnosticIssued
Definition Sema.h:10741
@ FRS_NoViableFunction
Definition Sema.h:10740
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9284
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10069
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3581
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12106
bool AddingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function without the cfi_unchecked_callee attribut...
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
const LangOptions & getLangOpts() const
Definition Sema.h:918
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1281
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
SemaHLSL & HLSL()
Definition Sema.h:1455
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9283
MemberPointerConversionDirection
Definition Sema.h:10189
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10379
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15370
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:6935
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1418
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8130
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13847
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7430
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15325
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:123
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6706
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6675
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
MemberPointerConversionResult
Definition Sema.h:10181
SourceManager & SourceMgr
Definition Sema.h:1286
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1285
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:509
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6383
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
SemaARM & ARM()
Definition Sema.h:1425
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8609
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:292
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:386
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:351
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:303
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:297
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:356
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:333
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition Overload.h:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:385
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:328
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:361
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:312
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:323
void setToType(unsigned Idx, QualType T)
Definition Overload.h:390
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition Overload.h:378
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:343
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:308
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:347
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:338
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:368
QualType getToType(unsigned Idx) const
Definition Overload.h:405
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
StringRef getString() const
Definition Expr.h:1867
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:673
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:727
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:712
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3538
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBlockPointerType() const
Definition TypeBase.h:8551
bool isVoidType() const
Definition TypeBase.h:8887
bool isBooleanType() const
Definition TypeBase.h:9017
bool isObjCBuiltinType() const
Definition TypeBase.h:8751
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:1951
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isIncompleteArrayType() const
Definition TypeBase.h:8638
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isFloat16Type() const
Definition TypeBase.h:8896
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
bool isRValueReferenceType() const
Definition TypeBase.h:8563
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8634
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9047
bool isArrayType() const
Definition TypeBase.h:8630
bool isCharType() const
Definition Type.cpp:2132
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:8955
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2337
bool isPointerType() const
Definition TypeBase.h:8531
bool isArrayParameterType() const
Definition TypeBase.h:8646
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8931
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2574
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9174
bool isReferenceType() const
Definition TypeBase.h:8555
bool isEnumeralType() const
Definition TypeBase.h:8662
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8721
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9005
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2168
bool isExtVectorBoolType() const
Definition TypeBase.h:8678
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8708
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isLValueReferenceType() const
Definition TypeBase.h:8559
bool isBitIntType() const
Definition TypeBase.h:8796
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2411
bool isAnyComplexType() const
Definition TypeBase.h:8666
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8943
bool isHalfType() const
Definition TypeBase.h:8891
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8869
bool isQueueT() const
Definition TypeBase.h:8777
bool isMemberPointerType() const
Definition TypeBase.h:8612
bool isObjCIdType() const
Definition TypeBase.h:8733
bool isMatrixType() const
Definition TypeBase.h:8688
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9023
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8769
bool isBFloat16Type() const
Definition TypeBase.h:8908
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8527
bool isObjCObjectPointerType() const
Definition TypeBase.h:8700
bool isVectorType() const
Definition TypeBase.h:8670
bool isObjCClassType() const
Definition TypeBase.h:8739
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8844
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
bool isAnyPointerType() const
Definition TypeBase.h:8539
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSamplerT() const
Definition TypeBase.h:8765
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9107
bool isNullPtrType() const
Definition TypeBase.h:8924
bool isRecordType() const
Definition TypeBase.h:8658
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1426
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5036
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1402
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3392
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3461
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4128
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4236
QualType getBaseType() const
Definition ExprCXX.h:4210
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4220
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4201
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4246
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4240
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:640
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:966
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:312
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:809
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:60
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind, bool PartialOverloading=false)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition Overload.h:852
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:880
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:889
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:872
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:876
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition Overload.h:917
@ ovl_fail_too_few_arguments
Definition Overload.h:854
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:896
@ ovl_fail_too_many_arguments
Definition Overload.h:853
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:904
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:913
@ ovl_fail_bad_conversion
Definition Overload.h:855
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:885
@ ovl_fail_bad_deduction
Definition Overload.h:856
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:900
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:909
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:893
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:861
@ Comparison
A comparison.
Definition Sema.h:665
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:215
@ ICR_Conversion
Conversion.
Definition Overload.h:229
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:251
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:257
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:220
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:244
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:232
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:238
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:235
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:254
@ ICR_Promotion
Promotion.
Definition Overload.h:223
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:217
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:248
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:226
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:922
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:205
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:208
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:710
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:731
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:689
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:727
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:585
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:214
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:425
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:268
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:280
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:308
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:304
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:417
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:412
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:388
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:374
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:410
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:407
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:377
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:371
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:391
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:380
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:394
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:383
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:404
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:398
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:401
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1512
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:824
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:827
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:832
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:831
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:446
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h:515
ConversionSet::const_iterator const_iterator
Definition Overload.h:551
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:516
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:542
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:600
QualType getFromType() const
Definition Overload.h:599
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
DeferredTemplateOverloadCandidate * Next
Definition Overload.h:1095
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
Extra information about a function prototype.
Definition TypeBase.h:5351
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5356
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1188
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1199
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1201
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1237
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition Overload.h:1210
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1227
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:926
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:991
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:982
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1056
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1030
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:995
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:972
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:940
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:936
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:931
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1003
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:952
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:966
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1021
unsigned getNumParams() const
Definition Overload.h:1069
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:999
unsigned TookAddressOfOverload
Definition Overload.h:985
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1008
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1012
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:949
DeductionFailureInfo DeductionFailure
Definition Overload.h:1015
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:956
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:944
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1026
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10471
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10478
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13001
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13089
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13130
Abstract class used to diagnose incomplete types.
Definition Sema.h:8211
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
DeclAccessPair FoundDecl
The declaration that was looked up, together with its access.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:470
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:482
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:504
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:495
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:499
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:490
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:509
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.