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 = 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 Data = nullptr;
857 Diag->~PartialDiagnosticAt();
858 HasDiagnostic = false;
859 }
860 break;
861
862 // Unhandled
865 break;
866 }
867}
868
870 if (HasDiagnostic)
871 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
872 return nullptr;
873}
874
908
944
976
1008
1010 switch (static_cast<TemplateDeductionResult>(Result)) {
1013 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1014
1015 default:
1016 return std::nullopt;
1017 }
1018}
1019
1021 const FunctionDecl *Y) {
1022 if (!X || !Y)
1023 return false;
1024 if (X->getNumParams() != Y->getNumParams())
1025 return false;
1026 // FIXME: when do rewritten comparison operators
1027 // with explicit object parameters correspond?
1028 // https://cplusplus.github.io/CWG/issues/2797.html
1029 for (unsigned I = 0; I < X->getNumParams(); ++I)
1030 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1031 Y->getParamDecl(I)->getType()))
1032 return false;
1033 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1034 auto *FTY = Y->getDescribedFunctionTemplate();
1035 if (!FTY)
1036 return false;
1037 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1038 FTY->getTemplateParameters()))
1039 return false;
1040 }
1041 return true;
1042}
1043
1045 Expr *FirstOperand, FunctionDecl *EqFD) {
1046 assert(EqFD->getOverloadedOperator() ==
1047 OverloadedOperatorKind::OO_EqualEqual);
1048 // C++2a [over.match.oper]p4:
1049 // A non-template function or function template F named operator== is a
1050 // rewrite target with first operand o unless a search for the name operator!=
1051 // in the scope S from the instantiation context of the operator expression
1052 // finds a function or function template that would correspond
1053 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1054 // scope of the class type of o if F is a class member, and the namespace
1055 // scope of which F is a member otherwise. A function template specialization
1056 // named operator== is a rewrite target if its function template is a rewrite
1057 // target.
1059 OverloadedOperatorKind::OO_ExclaimEqual);
1060 if (isa<CXXMethodDecl>(EqFD)) {
1061 // If F is a class member, search scope is class type of first operand.
1062 QualType RHS = FirstOperand->getType();
1063 auto *RHSRec = RHS->getAsCXXRecordDecl();
1064 if (!RHSRec)
1065 return true;
1066 LookupResult Members(S, NotEqOp, OpLoc,
1068 S.LookupQualifiedName(Members, RHSRec);
1069 Members.suppressAccessDiagnostics();
1070 for (NamedDecl *Op : Members)
1071 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1072 return false;
1073 return true;
1074 }
1075 // Otherwise the search scope is the namespace scope of which F is a member.
1076 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1077 auto *NotEqFD = Op->getAsFunction();
1078 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1079 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1080 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1082 cast<Decl>(Op->getLexicalDeclContext())))
1083 return false;
1084 }
1085 return true;
1086}
1087
1091 return false;
1092 return Op == OO_EqualEqual || Op == OO_Spaceship;
1093}
1094
1096 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1097 auto Op = FD->getOverloadedOperator();
1098 if (!allowsReversed(Op))
1099 return false;
1100 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1101 assert(OriginalArgs.size() == 2);
1103 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1104 return false;
1105 }
1106 // Don't bother adding a reversed candidate that can never be a better
1107 // match than the non-reversed version.
1108 return FD->getNumNonObjectParams() != 2 ||
1110 FD->getParamDecl(1)->getType()) ||
1111 FD->hasAttr<EnableIfAttr>();
1112}
1113
1114void OverloadCandidateSet::destroyCandidates() {
1115 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1116 for (auto &C : i->Conversions)
1117 C.~ImplicitConversionSequence();
1118 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1119 i->DeductionFailure.Destroy();
1120 }
1121}
1122
1124 destroyCandidates();
1125 SlabAllocator.Reset();
1126 NumInlineBytesUsed = 0;
1127 Candidates.clear();
1128 Functions.clear();
1129 Kind = CSK;
1130 FirstDeferredCandidate = nullptr;
1131 DeferredCandidatesCount = 0;
1132 HasDeferredTemplateConstructors = false;
1133 ResolutionByPerfectCandidateIsDisabled = false;
1134}
1135
1136namespace {
1137 class UnbridgedCastsSet {
1138 struct Entry {
1139 Expr **Addr;
1140 Expr *Saved;
1141 };
1142 SmallVector<Entry, 2> Entries;
1143
1144 public:
1145 void save(Sema &S, Expr *&E) {
1146 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1147 Entry entry = { &E, E };
1148 Entries.push_back(entry);
1149 E = S.ObjC().stripARCUnbridgedCast(E);
1150 }
1151
1152 void restore() {
1153 for (SmallVectorImpl<Entry>::iterator
1154 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1155 *i->Addr = i->Saved;
1156 }
1157 };
1158}
1159
1160/// checkPlaceholderForOverload - Do any interesting placeholder-like
1161/// preprocessing on the given expression.
1162///
1163/// \param unbridgedCasts a collection to which to add unbridged casts;
1164/// without this, they will be immediately diagnosed as errors
1165///
1166/// Return true on unrecoverable error.
1167static bool
1169 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1170 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1171 // We can't handle overloaded expressions here because overload
1172 // resolution might reasonably tweak them.
1173 if (placeholder->getKind() == BuiltinType::Overload) return false;
1174
1175 // If the context potentially accepts unbridged ARC casts, strip
1176 // the unbridged cast and add it to the collection for later restoration.
1177 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1178 unbridgedCasts) {
1179 unbridgedCasts->save(S, E);
1180 return false;
1181 }
1182
1183 // Go ahead and check everything else.
1184 ExprResult result = S.CheckPlaceholderExpr(E);
1185 if (result.isInvalid())
1186 return true;
1187
1188 E = result.get();
1189 return false;
1190 }
1191
1192 // Nothing to do.
1193 return false;
1194}
1195
1196/// checkArgPlaceholdersForOverload - Check a set of call operands for
1197/// placeholders.
1199 UnbridgedCastsSet &unbridged) {
1200 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1201 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1202 return true;
1203
1204 return false;
1205}
1206
1208 const LookupResult &Old, NamedDecl *&Match,
1209 bool NewIsUsingDecl) {
1210 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1211 I != E; ++I) {
1212 NamedDecl *OldD = *I;
1213
1214 bool OldIsUsingDecl = false;
1215 if (isa<UsingShadowDecl>(OldD)) {
1216 OldIsUsingDecl = true;
1217
1218 // We can always introduce two using declarations into the same
1219 // context, even if they have identical signatures.
1220 if (NewIsUsingDecl) continue;
1221
1222 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1223 }
1224
1225 // A using-declaration does not conflict with another declaration
1226 // if one of them is hidden.
1227 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1228 continue;
1229
1230 // If either declaration was introduced by a using declaration,
1231 // we'll need to use slightly different rules for matching.
1232 // Essentially, these rules are the normal rules, except that
1233 // function templates hide function templates with different
1234 // return types or template parameter lists.
1235 bool UseMemberUsingDeclRules =
1236 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1237 !New->getFriendObjectKind();
1238
1239 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1240 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1241 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1243 continue;
1244 }
1245
1246 if (!isa<FunctionTemplateDecl>(OldD) &&
1247 !shouldLinkPossiblyHiddenDecl(*I, New))
1248 continue;
1249
1250 Match = *I;
1251 return OverloadKind::Match;
1252 }
1253
1254 // Builtins that have custom typechecking or have a reference should
1255 // not be overloadable or redeclarable.
1256 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1257 Match = *I;
1259 }
1260 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1261 // We can overload with these, which can show up when doing
1262 // redeclaration checks for UsingDecls.
1263 assert(Old.getLookupKind() == LookupUsingDeclName);
1264 } else if (isa<TagDecl>(OldD)) {
1265 // We can always overload with tags by hiding them.
1266 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1267 // Optimistically assume that an unresolved using decl will
1268 // overload; if it doesn't, we'll have to diagnose during
1269 // template instantiation.
1270 //
1271 // Exception: if the scope is dependent and this is not a class
1272 // member, the using declaration can only introduce an enumerator.
1273 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1274 Match = *I;
1276 }
1277 } else {
1278 // (C++ 13p1):
1279 // Only function declarations can be overloaded; object and type
1280 // declarations cannot be overloaded.
1281 Match = *I;
1283 }
1284 }
1285
1286 // C++ [temp.friend]p1:
1287 // For a friend function declaration that is not a template declaration:
1288 // -- if the name of the friend is a qualified or unqualified template-id,
1289 // [...], otherwise
1290 // -- if the name of the friend is a qualified-id and a matching
1291 // non-template function is found in the specified class or namespace,
1292 // the friend declaration refers to that function, otherwise,
1293 // -- if the name of the friend is a qualified-id and a matching function
1294 // template is found in the specified class or namespace, the friend
1295 // declaration refers to the deduced specialization of that function
1296 // template, otherwise
1297 // -- the name shall be an unqualified-id [...]
1298 // If we get here for a qualified friend declaration, we've just reached the
1299 // third bullet. If the type of the friend is dependent, skip this lookup
1300 // until instantiation.
1301 if (New->getFriendObjectKind() && New->getQualifier() &&
1302 !New->getDescribedFunctionTemplate() &&
1303 !New->getDependentSpecializationInfo() &&
1304 !New->getType()->isDependentType()) {
1305 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1306 TemplateSpecResult.addAllDecls(Old);
1307 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1308 /*QualifiedFriend*/true)) {
1309 New->setInvalidDecl();
1311 }
1312
1313 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1314 return OverloadKind::Match;
1315 }
1316
1318}
1319
1320template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1321 assert(D && "function decl should not be null");
1322 if (auto *A = D->getAttr<AttrT>())
1323 return !A->isImplicit();
1324 return false;
1325}
1326
1328 FunctionDecl *Old,
1329 bool UseMemberUsingDeclRules,
1330 bool ConsiderCudaAttrs,
1331 bool UseOverrideRules = false) {
1332 // C++ [basic.start.main]p2: This function shall not be overloaded.
1333 if (New->isMain())
1334 return false;
1335
1336 // MSVCRT user defined entry points cannot be overloaded.
1337 if (New->isMSVCRTEntryPoint())
1338 return false;
1339
1340 NamedDecl *OldDecl = Old;
1341 NamedDecl *NewDecl = New;
1343 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1344
1345 // C++ [temp.fct]p2:
1346 // A function template can be overloaded with other function templates
1347 // and with normal (non-template) functions.
1348 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1349 return true;
1350
1351 // Is the function New an overload of the function Old?
1352 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1353 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1354
1355 // Compare the signatures (C++ 1.3.10) of the two functions to
1356 // determine whether they are overloads. If we find any mismatch
1357 // in the signature, they are overloads.
1358
1359 // If either of these functions is a K&R-style function (no
1360 // prototype), then we consider them to have matching signatures.
1361 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1363 return false;
1364
1365 const auto *OldType = cast<FunctionProtoType>(OldQType);
1366 const auto *NewType = cast<FunctionProtoType>(NewQType);
1367
1368 // The signature of a function includes the types of its
1369 // parameters (C++ 1.3.10), which includes the presence or absence
1370 // of the ellipsis; see C++ DR 357).
1371 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1372 return true;
1373
1374 // For member-like friends, the enclosing class is part of the signature.
1375 if ((New->isMemberLikeConstrainedFriend() ||
1377 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1378 return true;
1379
1380 // Compare the parameter lists.
1381 // This can only be done once we have establish that friend functions
1382 // inhabit the same context, otherwise we might tried to instantiate
1383 // references to non-instantiated entities during constraint substitution.
1384 // GH78101.
1385 if (NewTemplate) {
1386 OldDecl = OldTemplate;
1387 NewDecl = NewTemplate;
1388 // C++ [temp.over.link]p4:
1389 // The signature of a function template consists of its function
1390 // signature, its return type and its template parameter list. The names
1391 // of the template parameters are significant only for establishing the
1392 // relationship between the template parameters and the rest of the
1393 // signature.
1394 //
1395 // We check the return type and template parameter lists for function
1396 // templates first; the remaining checks follow.
1397 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1398 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1399 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1400 bool SameReturnType = SemaRef.Context.hasSameType(
1401 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1402 // FIXME(GH58571): Match template parameter list even for non-constrained
1403 // template heads. This currently ensures that the code prior to C++20 is
1404 // not newly broken.
1405 bool ConstraintsInTemplateHead =
1408 // C++ [namespace.udecl]p11:
1409 // The set of declarations named by a using-declarator that inhabits a
1410 // class C does not include member functions and member function
1411 // templates of a base class that "correspond" to (and thus would
1412 // conflict with) a declaration of a function or function template in
1413 // C.
1414 // Comparing return types is not required for the "correspond" check to
1415 // decide whether a member introduced by a shadow declaration is hidden.
1416 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1417 !SameTemplateParameterList)
1418 return true;
1419 if (!UseMemberUsingDeclRules &&
1420 (!SameTemplateParameterList || !SameReturnType))
1421 return true;
1422 }
1423
1424 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1425 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1426
1427 int OldParamsOffset = 0;
1428 int NewParamsOffset = 0;
1429
1430 // When determining if a method is an overload from a base class, act as if
1431 // the implicit object parameter are of the same type.
1432
1433 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1435 auto ThisType = M->getFunctionObjectParameterReferenceType();
1436 if (ThisType.isConstQualified())
1437 Q.removeConst();
1438 return Q;
1439 }
1440
1441 // We do not allow overloading based off of '__restrict'.
1442 Q.removeRestrict();
1443
1444 // We may not have applied the implicit const for a constexpr member
1445 // function yet (because we haven't yet resolved whether this is a static
1446 // or non-static member function). Add it now, on the assumption that this
1447 // is a redeclaration of OldMethod.
1448 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1449 (M->isConstexpr() || M->isConsteval()) &&
1450 !isa<CXXConstructorDecl>(NewMethod))
1451 Q.addConst();
1452 return Q;
1453 };
1454
1455 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1456 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1457 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1458
1459 if (OldMethod->isExplicitObjectMemberFunction()) {
1460 BS.Quals.removeVolatile();
1461 DS.Quals.removeVolatile();
1462 }
1463
1464 return BS.Quals == DS.Quals;
1465 };
1466
1467 auto CompareType = [&](QualType Base, QualType D) {
1468 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1469 auto DS = D.getNonReferenceType().getCanonicalType().split();
1470
1471 if (!AreQualifiersEqual(BS, DS))
1472 return false;
1473
1474 if (OldMethod->isImplicitObjectMemberFunction() &&
1475 OldMethod->getParent() != NewMethod->getParent()) {
1476 CanQualType ParentType =
1477 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1478 if (ParentType.getTypePtr() != BS.Ty)
1479 return false;
1480 BS.Ty = DS.Ty;
1481 }
1482
1483 // FIXME: should we ignore some type attributes here?
1484 if (BS.Ty != DS.Ty)
1485 return false;
1486
1487 if (Base->isLValueReferenceType())
1488 return D->isLValueReferenceType();
1489 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1490 };
1491
1492 // If the function is a class member, its signature includes the
1493 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1494 auto DiagnoseInconsistentRefQualifiers = [&]() {
1495 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1496 return false;
1497 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1498 return false;
1499 if (OldMethod->isExplicitObjectMemberFunction() ||
1500 NewMethod->isExplicitObjectMemberFunction())
1501 return false;
1502 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1503 NewMethod->getRefQualifier() == RQ_None)) {
1504 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1505 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1506 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1507 return true;
1508 }
1509 return false;
1510 };
1511
1512 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1513 OldParamsOffset++;
1514 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1515 NewParamsOffset++;
1516
1517 if (OldType->getNumParams() - OldParamsOffset !=
1518 NewType->getNumParams() - NewParamsOffset ||
1520 {OldType->param_type_begin() + OldParamsOffset,
1521 OldType->param_type_end()},
1522 {NewType->param_type_begin() + NewParamsOffset,
1523 NewType->param_type_end()},
1524 nullptr)) {
1525 return true;
1526 }
1527
1528 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1529 !NewMethod->isStatic()) {
1530 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1531 const CXXMethodDecl *New) {
1532 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1533 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1534
1535 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1536 return F->getRefQualifier() == RQ_None &&
1537 !F->isExplicitObjectMemberFunction();
1538 };
1539
1540 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1541 CompareType(OldObjectType.getNonReferenceType(),
1542 NewObjectType.getNonReferenceType()))
1543 return true;
1544 return CompareType(OldObjectType, NewObjectType);
1545 }(OldMethod, NewMethod);
1546
1547 if (!HaveCorrespondingObjectParameters) {
1548 if (DiagnoseInconsistentRefQualifiers())
1549 return true;
1550 // CWG2554
1551 // and, if at least one is an explicit object member function, ignoring
1552 // object parameters
1553 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1554 !OldMethod->isExplicitObjectMemberFunction()))
1555 return true;
1556 }
1557 }
1558
1559 if (!UseOverrideRules &&
1560 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1561 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1562 OldRC = Old->getTrailingRequiresClause();
1563 if (!NewRC != !OldRC)
1564 return true;
1565 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1566 return true;
1567 if (NewRC &&
1568 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1569 NewDecl, NewRC.ConstraintExpr))
1570 return true;
1571 }
1572
1573 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1574 NewMethod->isImplicitObjectMemberFunction()) {
1575 if (DiagnoseInconsistentRefQualifiers())
1576 return true;
1577 }
1578
1579 // Though pass_object_size is placed on parameters and takes an argument, we
1580 // consider it to be a function-level modifier for the sake of function
1581 // identity. Either the function has one or more parameters with
1582 // pass_object_size or it doesn't.
1585 return true;
1586
1587 // enable_if attributes are an order-sensitive part of the signature.
1589 NewI = New->specific_attr_begin<EnableIfAttr>(),
1590 NewE = New->specific_attr_end<EnableIfAttr>(),
1591 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1592 OldE = Old->specific_attr_end<EnableIfAttr>();
1593 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1594 if (NewI == NewE || OldI == OldE)
1595 return true;
1596 llvm::FoldingSetNodeID NewID, OldID;
1597 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1598 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1599 if (NewID != OldID)
1600 return true;
1601 }
1602
1603 // At this point, it is known that the two functions have the same signature.
1604 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1605 // Don't allow overloading of destructors. (In theory we could, but it
1606 // would be a giant change to clang.)
1608 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1609 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1610 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1611 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1612 "Unexpected invalid target.");
1613
1614 // Allow overloading of functions with same signature and different CUDA
1615 // target attributes.
1616 if (NewTarget != OldTarget) {
1617 // Special case: non-constexpr function is allowed to override
1618 // constexpr virtual function
1619 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1620 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1625 return false;
1626 }
1627 return true;
1628 }
1629 }
1630 }
1631 }
1632
1633 // The signatures match; this is not an overload.
1634 return false;
1635}
1636
1638 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1639 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1640 ConsiderCudaAttrs);
1641}
1642
1644 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1645 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1646 /*UseMemberUsingDeclRules=*/false,
1647 /*ConsiderCudaAttrs=*/true,
1648 /*UseOverrideRules=*/true);
1649}
1650
1651/// Tries a user-defined conversion from From to ToType.
1652///
1653/// Produces an implicit conversion sequence for when a standard conversion
1654/// is not an option. See TryImplicitConversion for more information.
1657 bool SuppressUserConversions,
1658 AllowedExplicit AllowExplicit,
1659 bool InOverloadResolution,
1660 bool CStyle,
1661 bool AllowObjCWritebackConversion,
1662 bool AllowObjCConversionOnExplicit) {
1664
1665 if (SuppressUserConversions) {
1666 // We're not in the case above, so there is no conversion that
1667 // we can perform.
1669 return ICS;
1670 }
1671
1672 // Attempt user-defined conversion.
1673 OverloadCandidateSet Conversions(From->getExprLoc(),
1675 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1676 Conversions, AllowExplicit,
1677 AllowObjCConversionOnExplicit)) {
1678 case OR_Success:
1679 case OR_Deleted:
1680 ICS.setUserDefined();
1681 // C++ [over.ics.user]p4:
1682 // A conversion of an expression of class type to the same class
1683 // type is given Exact Match rank, and a conversion of an
1684 // expression of class type to a base class of that type is
1685 // given Conversion rank, in spite of the fact that a copy
1686 // constructor (i.e., a user-defined conversion function) is
1687 // called for those cases.
1689 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1690 QualType FromType;
1691 SourceLocation FromLoc;
1692 // C++11 [over.ics.list]p6, per DR2137:
1693 // C++17 [over.ics.list]p6:
1694 // If C is not an initializer-list constructor and the initializer list
1695 // has a single element of type cv U, where U is X or a class derived
1696 // from X, the implicit conversion sequence has Exact Match rank if U is
1697 // X, or Conversion rank if U is derived from X.
1698 bool FromListInit = false;
1699 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1700 InitList && InitList->getNumInits() == 1 &&
1702 const Expr *SingleInit = InitList->getInit(0);
1703 FromType = SingleInit->getType();
1704 FromLoc = SingleInit->getBeginLoc();
1705 FromListInit = true;
1706 } else {
1707 FromType = From->getType();
1708 FromLoc = From->getBeginLoc();
1709 }
1710 QualType FromCanon =
1712 QualType ToCanon
1714 if ((FromCanon == ToCanon ||
1715 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1716 // Turn this into a "standard" conversion sequence, so that it
1717 // gets ranked with standard conversion sequences.
1719 ICS.setStandard();
1721 ICS.Standard.setFromType(FromType);
1722 ICS.Standard.setAllToTypes(ToType);
1723 ICS.Standard.FromBracedInitList = FromListInit;
1726 if (ToCanon != FromCanon)
1728 }
1729 }
1730 break;
1731
1732 case OR_Ambiguous:
1733 ICS.setAmbiguous();
1734 ICS.Ambiguous.setFromType(From->getType());
1735 ICS.Ambiguous.setToType(ToType);
1736 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1737 Cand != Conversions.end(); ++Cand)
1738 if (Cand->Best)
1739 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1740 break;
1741
1742 // Fall through.
1745 break;
1746 }
1747
1748 return ICS;
1749}
1750
1751/// TryImplicitConversion - Attempt to perform an implicit conversion
1752/// from the given expression (Expr) to the given type (ToType). This
1753/// function returns an implicit conversion sequence that can be used
1754/// to perform the initialization. Given
1755///
1756/// void f(float f);
1757/// void g(int i) { f(i); }
1758///
1759/// this routine would produce an implicit conversion sequence to
1760/// describe the initialization of f from i, which will be a standard
1761/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1762/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1763//
1764/// Note that this routine only determines how the conversion can be
1765/// performed; it does not actually perform the conversion. As such,
1766/// it will not produce any diagnostics if no conversion is available,
1767/// but will instead return an implicit conversion sequence of kind
1768/// "BadConversion".
1769///
1770/// If @p SuppressUserConversions, then user-defined conversions are
1771/// not permitted.
1772/// If @p AllowExplicit, then explicit user-defined conversions are
1773/// permitted.
1774///
1775/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1776/// writeback conversion, which allows __autoreleasing id* parameters to
1777/// be initialized with __strong id* or __weak id* arguments.
1778static ImplicitConversionSequence
1780 bool SuppressUserConversions,
1781 AllowedExplicit AllowExplicit,
1782 bool InOverloadResolution,
1783 bool CStyle,
1784 bool AllowObjCWritebackConversion,
1785 bool AllowObjCConversionOnExplicit) {
1787 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1788 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1789 ICS.setStandard();
1790 return ICS;
1791 }
1792
1793 if (!S.getLangOpts().CPlusPlus) {
1795 return ICS;
1796 }
1797
1798 // C++ [over.ics.user]p4:
1799 // A conversion of an expression of class type to the same class
1800 // type is given Exact Match rank, and a conversion of an
1801 // expression of class type to a base class of that type is
1802 // given Conversion rank, in spite of the fact that a copy/move
1803 // constructor (i.e., a user-defined conversion function) is
1804 // called for those cases.
1805 QualType FromType = From->getType();
1806 if (ToType->isRecordType() &&
1807 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1808 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1809 ICS.setStandard();
1811 ICS.Standard.setFromType(FromType);
1812 ICS.Standard.setAllToTypes(ToType);
1813
1814 // We don't actually check at this point whether there is a valid
1815 // copy/move constructor, since overloading just assumes that it
1816 // exists. When we actually perform initialization, we'll find the
1817 // appropriate constructor to copy the returned object, if needed.
1818 ICS.Standard.CopyConstructor = nullptr;
1819
1820 // Determine whether this is considered a derived-to-base conversion.
1821 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1823
1824 return ICS;
1825 }
1826
1827 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1828 FromType->isHLSLAttributedResourceType()) {
1829 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1830 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1831 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1832 FromResType->getWrappedType()) &&
1833 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1834 FromResType->getContainedType()) &&
1835 ToResType->getAttrs() == FromResType->getAttrs()) {
1836 ICS.setStandard();
1838 ICS.Standard.setFromType(FromType);
1839 ICS.Standard.setAllToTypes(ToType);
1840 return ICS;
1841 }
1842 }
1843
1844 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1845 AllowExplicit, InOverloadResolution, CStyle,
1846 AllowObjCWritebackConversion,
1847 AllowObjCConversionOnExplicit);
1848}
1849
1850ImplicitConversionSequence
1852 bool SuppressUserConversions,
1853 AllowedExplicit AllowExplicit,
1854 bool InOverloadResolution,
1855 bool CStyle,
1856 bool AllowObjCWritebackConversion) {
1857 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1858 AllowExplicit, InOverloadResolution, CStyle,
1859 AllowObjCWritebackConversion,
1860 /*AllowObjCConversionOnExplicit=*/false);
1861}
1862
1864 AssignmentAction Action,
1865 bool AllowExplicit) {
1866 if (checkPlaceholderForOverload(*this, From))
1867 return ExprError();
1868
1869 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1870 bool AllowObjCWritebackConversion =
1871 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1872 Action == AssignmentAction::Sending);
1873 if (getLangOpts().ObjC)
1874 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1875 From->getType(), From);
1877 *this, From, ToType,
1878 /*SuppressUserConversions=*/false,
1879 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1880 /*InOverloadResolution=*/false,
1881 /*CStyle=*/false, AllowObjCWritebackConversion,
1882 /*AllowObjCConversionOnExplicit=*/false);
1883 return PerformImplicitConversion(From, ToType, ICS, Action);
1884}
1885
1887 QualType &ResultTy) const {
1888 bool Changed = IsFunctionConversion(FromType, ToType);
1889 if (Changed)
1890 ResultTy = ToType;
1891 return Changed;
1892}
1893
1896 bool *AddingCFIUncheckedCallee) const {
1900 *AddingCFIUncheckedCallee = false;
1901
1902 if (Context.hasSameUnqualifiedType(FromType, ToType))
1903 return false;
1904
1905 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1906 // or F(t noexcept) -> F(t)
1907 // where F adds one of the following at most once:
1908 // - a pointer
1909 // - a member pointer
1910 // - a block pointer
1911 // Changes here need matching changes in FindCompositePointerType.
1912 CanQualType CanTo = Context.getCanonicalType(ToType);
1913 CanQualType CanFrom = Context.getCanonicalType(FromType);
1914 Type::TypeClass TyClass = CanTo->getTypeClass();
1915 if (TyClass != CanFrom->getTypeClass()) return false;
1916 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1917 if (TyClass == Type::Pointer) {
1918 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1919 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1920 } else if (TyClass == Type::BlockPointer) {
1921 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1922 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1923 } else if (TyClass == Type::MemberPointer) {
1924 auto ToMPT = CanTo.castAs<MemberPointerType>();
1925 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1926 // A function pointer conversion cannot change the class of the function.
1927 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1928 FromMPT->getMostRecentCXXRecordDecl()))
1929 return false;
1930 CanTo = ToMPT->getPointeeType();
1931 CanFrom = FromMPT->getPointeeType();
1932 } else {
1933 return false;
1934 }
1935
1936 TyClass = CanTo->getTypeClass();
1937 if (TyClass != CanFrom->getTypeClass()) return false;
1938 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1939 return false;
1940 }
1941
1942 const auto *FromFn = cast<FunctionType>(CanFrom);
1943 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1944
1945 const auto *ToFn = cast<FunctionType>(CanTo);
1946 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1947
1948 bool Changed = false;
1949
1950 // Drop 'noreturn' if not present in target type.
1951 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1952 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1953 Changed = true;
1954 }
1955
1956 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1957 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1958
1959 if (FromFPT && ToFPT) {
1960 if (FromFPT->hasCFIUncheckedCallee() && !ToFPT->hasCFIUncheckedCallee()) {
1961 QualType NewTy = Context.getFunctionType(
1962 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1963 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(false));
1964 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1965 FromFn = FromFPT;
1966 Changed = true;
1969 } else if (!FromFPT->hasCFIUncheckedCallee() &&
1970 ToFPT->hasCFIUncheckedCallee()) {
1971 QualType NewTy = Context.getFunctionType(
1972 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1973 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(true));
1974 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1975 FromFn = FromFPT;
1976 Changed = true;
1979 }
1980 }
1981
1982 // Drop 'noexcept' if not present in target type.
1983 if (FromFPT && ToFPT) {
1984 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1985 FromFn = cast<FunctionType>(
1986 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1987 EST_None)
1988 .getTypePtr());
1989 Changed = true;
1990 }
1991
1992 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1993 // only if the ExtParameterInfo lists of the two function prototypes can be
1994 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1996 bool CanUseToFPT, CanUseFromFPT;
1997 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1998 CanUseFromFPT, NewParamInfos) &&
1999 CanUseToFPT && !CanUseFromFPT) {
2000 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2001 ExtInfo.ExtParameterInfos =
2002 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2003 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2004 FromFPT->getParamTypes(), ExtInfo);
2005 FromFn = QT->getAs<FunctionType>();
2006 Changed = true;
2007 }
2008
2009 // For C, when called from checkPointerTypesForAssignment,
2010 // we need to not alter FromFn, or else even an innocuous cast
2011 // like dropping effects will fail. In C++ however we do want to
2012 // alter FromFn (because of the way PerformImplicitConversion works).
2013 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
2014 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2015
2016 // Transparently add/drop effects; here we are concerned with
2017 // language rules/canonicalization. Adding/dropping effects is a warning.
2018 const auto FromFX = FromFPT->getFunctionEffects();
2019 const auto ToFX = ToFPT->getFunctionEffects();
2020 if (FromFX != ToFX) {
2021 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2022 ExtInfo.FunctionEffects = ToFX;
2023 QualType QT = Context.getFunctionType(
2024 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2025 FromFn = QT->getAs<FunctionType>();
2026 Changed = true;
2027 }
2028 }
2029 }
2030
2031 if (!Changed)
2032 return false;
2033
2034 assert(QualType(FromFn, 0).isCanonical());
2035 if (QualType(FromFn, 0) != CanTo) return false;
2036
2037 return true;
2038}
2039
2040/// Determine whether the conversion from FromType to ToType is a valid
2041/// floating point conversion.
2042///
2043static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2044 QualType ToType) {
2045 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2046 return false;
2047 // FIXME: disable conversions between long double, __ibm128 and __float128
2048 // if their representation is different until there is back end support
2049 // We of course allow this conversion if long double is really double.
2050
2051 // Conversions between bfloat16 and float16 are currently not supported.
2052 if ((FromType->isBFloat16Type() &&
2053 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2054 (ToType->isBFloat16Type() &&
2055 (FromType->isFloat16Type() || FromType->isHalfType())))
2056 return false;
2057
2058 // Conversions between IEEE-quad and IBM-extended semantics are not
2059 // permitted.
2060 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2061 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2062 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2063 &ToSem == &llvm::APFloat::IEEEquad()) ||
2064 (&FromSem == &llvm::APFloat::IEEEquad() &&
2065 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2066 return false;
2067 return true;
2068}
2069
2070static bool IsVectorElementConversion(Sema &S, QualType FromType,
2071 QualType ToType,
2072 ImplicitConversionKind &ICK, Expr *From) {
2073 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2074 return true;
2075
2076 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2078 return true;
2079 }
2080
2081 if (IsFloatingPointConversion(S, FromType, ToType)) {
2083 return true;
2084 }
2085
2086 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2088 return true;
2089 }
2090
2091 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2093 ToType->isRealFloatingType())) {
2095 return true;
2096 }
2097
2098 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2100 return true;
2101 }
2102
2103 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2104 ToType->isIntegralType(S.Context)) {
2106 return true;
2107 }
2108
2109 return false;
2110}
2111
2112/// Determine whether the conversion from FromType to ToType is a valid
2113/// vector conversion.
2114///
2115/// \param ICK Will be set to the vector conversion kind, if this is a vector
2116/// conversion.
2117static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2119 ImplicitConversionKind &ElConv, Expr *From,
2120 bool InOverloadResolution, bool CStyle) {
2121 // We need at least one of these types to be a vector type to have a vector
2122 // conversion.
2123 if (!ToType->isVectorType() && !FromType->isVectorType())
2124 return false;
2125
2126 // Identical types require no conversions.
2127 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2128 return false;
2129
2130 // HLSL allows implicit truncation of vector types.
2131 if (S.getLangOpts().HLSL) {
2132 auto *ToExtType = ToType->getAs<ExtVectorType>();
2133 auto *FromExtType = FromType->getAs<ExtVectorType>();
2134
2135 // If both arguments are vectors, handle possible vector truncation and
2136 // element conversion.
2137 if (ToExtType && FromExtType) {
2138 unsigned FromElts = FromExtType->getNumElements();
2139 unsigned ToElts = ToExtType->getNumElements();
2140 if (FromElts < ToElts)
2141 return false;
2142 if (FromElts == ToElts)
2143 ElConv = ICK_Identity;
2144 else
2146
2147 QualType FromElTy = FromExtType->getElementType();
2148 QualType ToElTy = ToExtType->getElementType();
2149 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2150 return true;
2151 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2152 }
2153 if (FromExtType && !ToExtType) {
2155 QualType FromElTy = FromExtType->getElementType();
2156 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2157 return true;
2158 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2159 }
2160 // Fallthrough for the case where ToType is a vector and FromType is not.
2161 }
2162
2163 // There are no conversions between extended vector types, only identity.
2164 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2165 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2166 // Implicit conversions require the same number of elements.
2167 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2168 return false;
2169
2170 // Permit implicit conversions from integral values to boolean vectors.
2171 if (ToType->isExtVectorBoolType() &&
2172 FromExtType->getElementType()->isIntegerType()) {
2174 return true;
2175 }
2176 // There are no other conversions between extended vector types.
2177 return false;
2178 }
2179
2180 // Vector splat from any arithmetic type to a vector.
2181 if (FromType->isArithmeticType()) {
2182 if (S.getLangOpts().HLSL) {
2183 ElConv = ICK_HLSL_Vector_Splat;
2184 QualType ToElTy = ToExtType->getElementType();
2185 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2186 }
2187 ICK = ICK_Vector_Splat;
2188 return true;
2189 }
2190 }
2191
2192 if (ToType->isSVESizelessBuiltinType() ||
2193 FromType->isSVESizelessBuiltinType())
2194 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2195 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2197 return true;
2198 }
2199
2200 if (ToType->isRVVSizelessBuiltinType() ||
2201 FromType->isRVVSizelessBuiltinType())
2202 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2203 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2205 return true;
2206 }
2207
2208 // We can perform the conversion between vector types in the following cases:
2209 // 1)vector types are equivalent AltiVec and GCC vector types
2210 // 2)lax vector conversions are permitted and the vector types are of the
2211 // same size
2212 // 3)the destination type does not have the ARM MVE strict-polymorphism
2213 // attribute, which inhibits lax vector conversion for overload resolution
2214 // only
2215 if (ToType->isVectorType() && FromType->isVectorType()) {
2216 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2217 (S.isLaxVectorConversion(FromType, ToType) &&
2218 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2219 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2220 S.isLaxVectorConversion(FromType, ToType) &&
2221 S.anyAltivecTypes(FromType, ToType) &&
2222 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2223 !InOverloadResolution && !CStyle) {
2224 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2225 << FromType << ToType;
2226 }
2228 return true;
2229 }
2230 }
2231
2232 return false;
2233}
2234
2235static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2236 bool InOverloadResolution,
2237 StandardConversionSequence &SCS,
2238 bool CStyle);
2239
2240/// IsStandardConversion - Determines whether there is a standard
2241/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2242/// expression From to the type ToType. Standard conversion sequences
2243/// only consider non-class types; for conversions that involve class
2244/// types, use TryImplicitConversion. If a conversion exists, SCS will
2245/// contain the standard conversion sequence required to perform this
2246/// conversion and this routine will return true. Otherwise, this
2247/// routine will return false and the value of SCS is unspecified.
2248static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2249 bool InOverloadResolution,
2251 bool CStyle,
2252 bool AllowObjCWritebackConversion) {
2253 QualType FromType = From->getType();
2254
2255 // Standard conversions (C++ [conv])
2257 SCS.IncompatibleObjC = false;
2258 SCS.setFromType(FromType);
2259 SCS.CopyConstructor = nullptr;
2260
2261 // There are no standard conversions for class types in C++, so
2262 // abort early. When overloading in C, however, we do permit them.
2263 if (S.getLangOpts().CPlusPlus &&
2264 (FromType->isRecordType() || ToType->isRecordType()))
2265 return false;
2266
2267 // The first conversion can be an lvalue-to-rvalue conversion,
2268 // array-to-pointer conversion, or function-to-pointer conversion
2269 // (C++ 4p1).
2270
2271 if (FromType == S.Context.OverloadTy) {
2272 DeclAccessPair AccessPair;
2273 if (FunctionDecl *Fn
2274 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2275 AccessPair)) {
2276 // We were able to resolve the address of the overloaded function,
2277 // so we can convert to the type of that function.
2278 FromType = Fn->getType();
2279 SCS.setFromType(FromType);
2280
2281 // we can sometimes resolve &foo<int> regardless of ToType, so check
2282 // if the type matches (identity) or we are converting to bool
2284 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2285 // if the function type matches except for [[noreturn]], it's ok
2286 if (!S.IsFunctionConversion(FromType,
2288 // otherwise, only a boolean conversion is standard
2289 if (!ToType->isBooleanType())
2290 return false;
2291 }
2292
2293 // Check if the "from" expression is taking the address of an overloaded
2294 // function and recompute the FromType accordingly. Take advantage of the
2295 // fact that non-static member functions *must* have such an address-of
2296 // expression.
2297 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2298 if (Method && !Method->isStatic() &&
2299 !Method->isExplicitObjectMemberFunction()) {
2300 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2301 "Non-unary operator on non-static member address");
2302 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2303 == UO_AddrOf &&
2304 "Non-address-of operator on non-static member address");
2305 FromType = S.Context.getMemberPointerType(
2306 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2307 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2308 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2309 UO_AddrOf &&
2310 "Non-address-of operator for overloaded function expression");
2311 FromType = S.Context.getPointerType(FromType);
2312 }
2313 } else {
2314 return false;
2315 }
2316 }
2317
2318 bool argIsLValue = From->isGLValue();
2319 // To handle conversion from ArrayParameterType to ConstantArrayType
2320 // this block must be above the one below because Array parameters
2321 // do not decay and when handling HLSLOutArgExprs and
2322 // the From expression is an LValue.
2323 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2324 ToType->isConstantArrayType()) {
2325 // HLSL constant array parameters do not decay, so if the argument is a
2326 // constant array and the parameter is an ArrayParameterType we have special
2327 // handling here.
2328 if (ToType->isArrayParameterType()) {
2329 FromType = S.Context.getArrayParameterType(FromType);
2330 } else if (FromType->isArrayParameterType()) {
2331 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2332 FromType = APT->getConstantArrayType(S.Context);
2333 }
2334
2336
2337 // Don't consider qualifiers, which include things like address spaces
2338 if (FromType.getCanonicalType().getUnqualifiedType() !=
2340 return false;
2341
2342 SCS.setAllToTypes(ToType);
2343 return true;
2344 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2345 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2346 // Lvalue-to-rvalue conversion (C++11 4.1):
2347 // A glvalue (3.10) of a non-function, non-array type T can
2348 // be converted to a prvalue.
2349
2351
2352 // C11 6.3.2.1p2:
2353 // ... if the lvalue has atomic type, the value has the non-atomic version
2354 // of the type of the lvalue ...
2355 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2356 FromType = Atomic->getValueType();
2357
2358 // If T is a non-class type, the type of the rvalue is the
2359 // cv-unqualified version of T. Otherwise, the type of the rvalue
2360 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2361 // just strip the qualifiers because they don't matter.
2362 FromType = FromType.getUnqualifiedType();
2363 } else if (FromType->isArrayType()) {
2364 // Array-to-pointer conversion (C++ 4.2)
2366
2367 // An lvalue or rvalue of type "array of N T" or "array of unknown
2368 // bound of T" can be converted to an rvalue of type "pointer to
2369 // T" (C++ 4.2p1).
2370 FromType = S.Context.getArrayDecayedType(FromType);
2371
2372 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2373 // This conversion is deprecated in C++03 (D.4)
2375
2376 // For the purpose of ranking in overload resolution
2377 // (13.3.3.1.1), this conversion is considered an
2378 // array-to-pointer conversion followed by a qualification
2379 // conversion (4.4). (C++ 4.2p2)
2380 SCS.Second = ICK_Identity;
2383 SCS.setAllToTypes(FromType);
2384 return true;
2385 }
2386 } else if (FromType->isFunctionType() && argIsLValue) {
2387 // Function-to-pointer conversion (C++ 4.3).
2389
2390 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2391 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2393 return false;
2394
2395 // An lvalue of function type T can be converted to an rvalue of
2396 // type "pointer to T." The result is a pointer to the
2397 // function. (C++ 4.3p1).
2398 FromType = S.Context.getPointerType(FromType);
2399 } else {
2400 // We don't require any conversions for the first step.
2401 SCS.First = ICK_Identity;
2402 }
2403 SCS.setToType(0, FromType);
2404
2405 // The second conversion can be an integral promotion, floating
2406 // point promotion, integral conversion, floating point conversion,
2407 // floating-integral conversion, pointer conversion,
2408 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2409 // For overloading in C, this can also be a "compatible-type"
2410 // conversion.
2411 bool IncompatibleObjC = false;
2413 ImplicitConversionKind DimensionICK = ICK_Identity;
2414 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2415 // The unqualified versions of the types are the same: there's no
2416 // conversion to do.
2417 SCS.Second = ICK_Identity;
2418 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2419 // Integral promotion (C++ 4.5).
2421 FromType = ToType.getUnqualifiedType();
2422 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2423 // Floating point promotion (C++ 4.6).
2425 FromType = ToType.getUnqualifiedType();
2426 } else if (S.IsComplexPromotion(FromType, ToType)) {
2427 // Complex promotion (Clang extension)
2429 FromType = ToType.getUnqualifiedType();
2430 } else if (ToType->isBooleanType() &&
2431 (FromType->isArithmeticType() ||
2432 FromType->isAnyPointerType() ||
2433 FromType->isBlockPointerType() ||
2434 FromType->isMemberPointerType())) {
2435 // Boolean conversions (C++ 4.12).
2437 FromType = S.Context.BoolTy;
2438 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2439 ToType->isIntegralType(S.Context)) {
2440 // Integral conversions (C++ 4.7).
2442 FromType = ToType.getUnqualifiedType();
2443 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2444 // Complex conversions (C99 6.3.1.6)
2446 FromType = ToType.getUnqualifiedType();
2447 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2448 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2449 // Complex-real conversions (C99 6.3.1.7)
2451 FromType = ToType.getUnqualifiedType();
2452 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2453 // Floating point conversions (C++ 4.8).
2455 FromType = ToType.getUnqualifiedType();
2456 } else if ((FromType->isRealFloatingType() &&
2457 ToType->isIntegralType(S.Context)) ||
2459 ToType->isRealFloatingType())) {
2460
2461 // Floating-integral conversions (C++ 4.9).
2463 FromType = ToType.getUnqualifiedType();
2464 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2466 } else if (AllowObjCWritebackConversion &&
2467 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2469 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2470 FromType, IncompatibleObjC)) {
2471 // Pointer conversions (C++ 4.10).
2473 SCS.IncompatibleObjC = IncompatibleObjC;
2474 FromType = FromType.getUnqualifiedType();
2475 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2476 InOverloadResolution, FromType)) {
2477 // Pointer to member conversions (4.11).
2479 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2480 From, InOverloadResolution, CStyle)) {
2481 SCS.Second = SecondICK;
2482 SCS.Dimension = DimensionICK;
2483 FromType = ToType.getUnqualifiedType();
2484 } else if (!S.getLangOpts().CPlusPlus &&
2485 S.Context.typesAreCompatible(ToType, FromType)) {
2486 // Compatible conversions (Clang extension for C function overloading)
2488 FromType = ToType.getUnqualifiedType();
2490 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2492 FromType = ToType;
2493 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2494 CStyle)) {
2495 // tryAtomicConversion has updated the standard conversion sequence
2496 // appropriately.
2497 return true;
2498 } else if (ToType->isEventT() &&
2500 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2502 FromType = ToType;
2503 } else if (ToType->isQueueT() &&
2505 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2507 FromType = ToType;
2508 } else if (ToType->isSamplerT() &&
2511 FromType = ToType;
2512 } else if ((ToType->isFixedPointType() &&
2513 FromType->isConvertibleToFixedPointType()) ||
2514 (FromType->isFixedPointType() &&
2515 ToType->isConvertibleToFixedPointType())) {
2517 FromType = ToType;
2518 } else {
2519 // No second conversion required.
2520 SCS.Second = ICK_Identity;
2521 }
2522 SCS.setToType(1, FromType);
2523
2524 // The third conversion can be a function pointer conversion or a
2525 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2526 bool ObjCLifetimeConversion;
2527 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2528 // Function pointer conversions (removing 'noexcept') including removal of
2529 // 'noreturn' (Clang extension).
2531 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2532 ObjCLifetimeConversion)) {
2534 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2535 FromType = ToType;
2536 } else {
2537 // No conversion required
2538 SCS.Third = ICK_Identity;
2539 }
2540
2541 // C++ [over.best.ics]p6:
2542 // [...] Any difference in top-level cv-qualification is
2543 // subsumed by the initialization itself and does not constitute
2544 // a conversion. [...]
2545 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2546 QualType CanonTo = S.Context.getCanonicalType(ToType);
2547 if (CanonFrom.getLocalUnqualifiedType()
2548 == CanonTo.getLocalUnqualifiedType() &&
2549 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2550 FromType = ToType;
2551 CanonFrom = CanonTo;
2552 }
2553
2554 SCS.setToType(2, FromType);
2555
2556 // If we have not converted the argument type to the parameter type,
2557 // this is a bad conversion sequence, unless we're resolving an overload in C.
2558 //
2559 // Permit conversions from a function without `cfi_unchecked_callee` to a
2560 // function with `cfi_unchecked_callee`.
2561 if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(CanonFrom, CanonTo))
2562 return true;
2563
2564 if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2565 return false;
2566
2567 ExprResult ER = ExprResult{From};
2568 AssignConvertType Conv =
2570 /*Diagnose=*/false,
2571 /*DiagnoseCFAudited=*/false,
2572 /*ConvertRHS=*/false);
2573 ImplicitConversionKind SecondConv;
2574 switch (Conv) {
2576 case AssignConvertType::
2577 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2578 SecondConv = ICK_C_Only_Conversion;
2579 break;
2580 // For our purposes, discarding qualifiers is just as bad as using an
2581 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2582 // qualifiers, as well.
2587 break;
2588 default:
2589 return false;
2590 }
2591
2592 // First can only be an lvalue conversion, so we pretend that this was the
2593 // second conversion. First should already be valid from earlier in the
2594 // function.
2595 SCS.Second = SecondConv;
2596 SCS.setToType(1, ToType);
2597
2598 // Third is Identity, because Second should rank us worse than any other
2599 // conversion. This could also be ICK_Qualification, but it's simpler to just
2600 // lump everything in with the second conversion, and we don't gain anything
2601 // from making this ICK_Qualification.
2602 SCS.Third = ICK_Identity;
2603 SCS.setToType(2, ToType);
2604 return true;
2605}
2606
2607static bool
2609 QualType &ToType,
2610 bool InOverloadResolution,
2612 bool CStyle) {
2613
2614 const RecordType *UT = ToType->getAsUnionType();
2615 if (!UT)
2616 return false;
2617 // The field to initialize within the transparent union.
2618 const RecordDecl *UD = UT->getOriginalDecl()->getDefinitionOrSelf();
2619 if (!UD->hasAttr<TransparentUnionAttr>())
2620 return false;
2621 // It's compatible if the expression matches any of the fields.
2622 for (const auto *it : UD->fields()) {
2623 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2624 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2625 ToType = it->getType();
2626 return true;
2627 }
2628 }
2629 return false;
2630}
2631
2632bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2633 const BuiltinType *To = ToType->getAs<BuiltinType>();
2634 // All integers are built-in.
2635 if (!To) {
2636 return false;
2637 }
2638
2639 // An rvalue of type char, signed char, unsigned char, short int, or
2640 // unsigned short int can be converted to an rvalue of type int if
2641 // int can represent all the values of the source type; otherwise,
2642 // the source rvalue can be converted to an rvalue of type unsigned
2643 // int (C++ 4.5p1).
2644 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2645 !FromType->isEnumeralType()) {
2646 if ( // We can promote any signed, promotable integer type to an int
2647 (FromType->isSignedIntegerType() ||
2648 // We can promote any unsigned integer type whose size is
2649 // less than int to an int.
2650 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2651 return To->getKind() == BuiltinType::Int;
2652 }
2653
2654 return To->getKind() == BuiltinType::UInt;
2655 }
2656
2657 // C++11 [conv.prom]p3:
2658 // A prvalue of an unscoped enumeration type whose underlying type is not
2659 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2660 // following types that can represent all the values of the enumeration
2661 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2662 // unsigned int, long int, unsigned long int, long long int, or unsigned
2663 // long long int. If none of the types in that list can represent all the
2664 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2665 // type can be converted to an rvalue a prvalue of the extended integer type
2666 // with lowest integer conversion rank (4.13) greater than the rank of long
2667 // long in which all the values of the enumeration can be represented. If
2668 // there are two such extended types, the signed one is chosen.
2669 // C++11 [conv.prom]p4:
2670 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2671 // can be converted to a prvalue of its underlying type. Moreover, if
2672 // integral promotion can be applied to its underlying type, a prvalue of an
2673 // unscoped enumeration type whose underlying type is fixed can also be
2674 // converted to a prvalue of the promoted underlying type.
2675 if (const auto *FromED = FromType->getAsEnumDecl()) {
2676 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2677 // provided for a scoped enumeration.
2678 if (FromED->isScoped())
2679 return false;
2680
2681 // We can perform an integral promotion to the underlying type of the enum,
2682 // even if that's not the promoted type. Note that the check for promoting
2683 // the underlying type is based on the type alone, and does not consider
2684 // the bitfield-ness of the actual source expression.
2685 if (FromED->isFixed()) {
2686 QualType Underlying = FromED->getIntegerType();
2687 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2688 IsIntegralPromotion(nullptr, Underlying, ToType);
2689 }
2690
2691 // We have already pre-calculated the promotion type, so this is trivial.
2692 if (ToType->isIntegerType() &&
2693 isCompleteType(From->getBeginLoc(), FromType))
2694 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2695
2696 // C++ [conv.prom]p5:
2697 // If the bit-field has an enumerated type, it is treated as any other
2698 // value of that type for promotion purposes.
2699 //
2700 // ... so do not fall through into the bit-field checks below in C++.
2701 if (getLangOpts().CPlusPlus)
2702 return false;
2703 }
2704
2705 // C++0x [conv.prom]p2:
2706 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2707 // to an rvalue a prvalue of the first of the following types that can
2708 // represent all the values of its underlying type: int, unsigned int,
2709 // long int, unsigned long int, long long int, or unsigned long long int.
2710 // If none of the types in that list can represent all the values of its
2711 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2712 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2713 // type.
2714 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2715 ToType->isIntegerType()) {
2716 // Determine whether the type we're converting from is signed or
2717 // unsigned.
2718 bool FromIsSigned = FromType->isSignedIntegerType();
2719 uint64_t FromSize = Context.getTypeSize(FromType);
2720
2721 // The types we'll try to promote to, in the appropriate
2722 // order. Try each of these types.
2723 QualType PromoteTypes[6] = {
2724 Context.IntTy, Context.UnsignedIntTy,
2725 Context.LongTy, Context.UnsignedLongTy ,
2726 Context.LongLongTy, Context.UnsignedLongLongTy
2727 };
2728 for (int Idx = 0; Idx < 6; ++Idx) {
2729 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2730 if (FromSize < ToSize ||
2731 (FromSize == ToSize &&
2732 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2733 // We found the type that we can promote to. If this is the
2734 // type we wanted, we have a promotion. Otherwise, no
2735 // promotion.
2736 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2737 }
2738 }
2739 }
2740
2741 // An rvalue for an integral bit-field (9.6) can be converted to an
2742 // rvalue of type int if int can represent all the values of the
2743 // bit-field; otherwise, it can be converted to unsigned int if
2744 // unsigned int can represent all the values of the bit-field. If
2745 // the bit-field is larger yet, no integral promotion applies to
2746 // it. If the bit-field has an enumerated type, it is treated as any
2747 // other value of that type for promotion purposes (C++ 4.5p3).
2748 // FIXME: We should delay checking of bit-fields until we actually perform the
2749 // conversion.
2750 //
2751 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2752 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2753 // bit-fields and those whose underlying type is larger than int) for GCC
2754 // compatibility.
2755 if (From) {
2756 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2757 std::optional<llvm::APSInt> BitWidth;
2758 if (FromType->isIntegralType(Context) &&
2759 (BitWidth =
2760 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2761 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2762 ToSize = Context.getTypeSize(ToType);
2763
2764 // Are we promoting to an int from a bitfield that fits in an int?
2765 if (*BitWidth < ToSize ||
2766 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2767 return To->getKind() == BuiltinType::Int;
2768 }
2769
2770 // Are we promoting to an unsigned int from an unsigned bitfield
2771 // that fits into an unsigned int?
2772 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2773 return To->getKind() == BuiltinType::UInt;
2774 }
2775
2776 return false;
2777 }
2778 }
2779 }
2780
2781 // An rvalue of type bool can be converted to an rvalue of type int,
2782 // with false becoming zero and true becoming one (C++ 4.5p4).
2783 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2784 return true;
2785 }
2786
2787 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2788 // integral type.
2789 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2790 ToType->isIntegerType())
2791 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2792
2793 return false;
2794}
2795
2797 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2798 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2799 /// An rvalue of type float can be converted to an rvalue of type
2800 /// double. (C++ 4.6p1).
2801 if (FromBuiltin->getKind() == BuiltinType::Float &&
2802 ToBuiltin->getKind() == BuiltinType::Double)
2803 return true;
2804
2805 // C99 6.3.1.5p1:
2806 // When a float is promoted to double or long double, or a
2807 // double is promoted to long double [...].
2808 if (!getLangOpts().CPlusPlus &&
2809 (FromBuiltin->getKind() == BuiltinType::Float ||
2810 FromBuiltin->getKind() == BuiltinType::Double) &&
2811 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2812 ToBuiltin->getKind() == BuiltinType::Float128 ||
2813 ToBuiltin->getKind() == BuiltinType::Ibm128))
2814 return true;
2815
2816 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2817 // or not native half types are enabled.
2818 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2819 (ToBuiltin->getKind() == BuiltinType::Float ||
2820 ToBuiltin->getKind() == BuiltinType::Double))
2821 return true;
2822
2823 // Half can be promoted to float.
2824 if (!getLangOpts().NativeHalfType &&
2825 FromBuiltin->getKind() == BuiltinType::Half &&
2826 ToBuiltin->getKind() == BuiltinType::Float)
2827 return true;
2828 }
2829
2830 return false;
2831}
2832
2834 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2835 if (!FromComplex)
2836 return false;
2837
2838 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2839 if (!ToComplex)
2840 return false;
2841
2842 return IsFloatingPointPromotion(FromComplex->getElementType(),
2843 ToComplex->getElementType()) ||
2844 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2845 ToComplex->getElementType());
2846}
2847
2848/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2849/// the pointer type FromPtr to a pointer to type ToPointee, with the
2850/// same type qualifiers as FromPtr has on its pointee type. ToType,
2851/// if non-empty, will be a pointer to ToType that may or may not have
2852/// the right set of qualifiers on its pointee.
2853///
2854static QualType
2856 QualType ToPointee, QualType ToType,
2857 ASTContext &Context,
2858 bool StripObjCLifetime = false) {
2859 assert((FromPtr->getTypeClass() == Type::Pointer ||
2860 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2861 "Invalid similarly-qualified pointer type");
2862
2863 /// Conversions to 'id' subsume cv-qualifier conversions.
2864 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2865 return ToType.getUnqualifiedType();
2866
2867 QualType CanonFromPointee
2868 = Context.getCanonicalType(FromPtr->getPointeeType());
2869 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2870 Qualifiers Quals = CanonFromPointee.getQualifiers();
2871
2872 if (StripObjCLifetime)
2873 Quals.removeObjCLifetime();
2874
2875 // Exact qualifier match -> return the pointer type we're converting to.
2876 if (CanonToPointee.getLocalQualifiers() == Quals) {
2877 // ToType is exactly what we need. Return it.
2878 if (!ToType.isNull())
2879 return ToType.getUnqualifiedType();
2880
2881 // Build a pointer to ToPointee. It has the right qualifiers
2882 // already.
2883 if (isa<ObjCObjectPointerType>(ToType))
2884 return Context.getObjCObjectPointerType(ToPointee);
2885 return Context.getPointerType(ToPointee);
2886 }
2887
2888 // Just build a canonical type that has the right qualifiers.
2889 QualType QualifiedCanonToPointee
2890 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2891
2892 if (isa<ObjCObjectPointerType>(ToType))
2893 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2894 return Context.getPointerType(QualifiedCanonToPointee);
2895}
2896
2898 bool InOverloadResolution,
2899 ASTContext &Context) {
2900 // Handle value-dependent integral null pointer constants correctly.
2901 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2902 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2904 return !InOverloadResolution;
2905
2906 return Expr->isNullPointerConstant(Context,
2907 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2909}
2910
2912 bool InOverloadResolution,
2913 QualType& ConvertedType,
2914 bool &IncompatibleObjC) {
2915 IncompatibleObjC = false;
2916 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2917 IncompatibleObjC))
2918 return true;
2919
2920 // Conversion from a null pointer constant to any Objective-C pointer type.
2921 if (ToType->isObjCObjectPointerType() &&
2922 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2923 ConvertedType = ToType;
2924 return true;
2925 }
2926
2927 // Blocks: Block pointers can be converted to void*.
2928 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2929 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2930 ConvertedType = ToType;
2931 return true;
2932 }
2933 // Blocks: A null pointer constant can be converted to a block
2934 // pointer type.
2935 if (ToType->isBlockPointerType() &&
2936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2937 ConvertedType = ToType;
2938 return true;
2939 }
2940
2941 // If the left-hand-side is nullptr_t, the right side can be a null
2942 // pointer constant.
2943 if (ToType->isNullPtrType() &&
2944 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2945 ConvertedType = ToType;
2946 return true;
2947 }
2948
2949 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2950 if (!ToTypePtr)
2951 return false;
2952
2953 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2954 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2955 ConvertedType = ToType;
2956 return true;
2957 }
2958
2959 // Beyond this point, both types need to be pointers
2960 // , including objective-c pointers.
2961 QualType ToPointeeType = ToTypePtr->getPointeeType();
2962 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2963 !getLangOpts().ObjCAutoRefCount) {
2964 ConvertedType = BuildSimilarlyQualifiedPointerType(
2965 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2966 Context);
2967 return true;
2968 }
2969 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2970 if (!FromTypePtr)
2971 return false;
2972
2973 QualType FromPointeeType = FromTypePtr->getPointeeType();
2974
2975 // If the unqualified pointee types are the same, this can't be a
2976 // pointer conversion, so don't do all of the work below.
2977 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2978 return false;
2979
2980 // An rvalue of type "pointer to cv T," where T is an object type,
2981 // can be converted to an rvalue of type "pointer to cv void" (C++
2982 // 4.10p2).
2983 if (FromPointeeType->isIncompleteOrObjectType() &&
2984 ToPointeeType->isVoidType()) {
2985 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2986 ToPointeeType,
2987 ToType, Context,
2988 /*StripObjCLifetime=*/true);
2989 return true;
2990 }
2991
2992 // MSVC allows implicit function to void* type conversion.
2993 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2994 ToPointeeType->isVoidType()) {
2995 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2996 ToPointeeType,
2997 ToType, Context);
2998 return true;
2999 }
3000
3001 // When we're overloading in C, we allow a special kind of pointer
3002 // conversion for compatible-but-not-identical pointee types.
3003 if (!getLangOpts().CPlusPlus &&
3004 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3005 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3006 ToPointeeType,
3007 ToType, Context);
3008 return true;
3009 }
3010
3011 // C++ [conv.ptr]p3:
3012 //
3013 // An rvalue of type "pointer to cv D," where D is a class type,
3014 // can be converted to an rvalue of type "pointer to cv B," where
3015 // B is a base class (clause 10) of D. If B is an inaccessible
3016 // (clause 11) or ambiguous (10.2) base class of D, a program that
3017 // necessitates this conversion is ill-formed. The result of the
3018 // conversion is a pointer to the base class sub-object of the
3019 // derived class object. The null pointer value is converted to
3020 // the null pointer value of the destination type.
3021 //
3022 // Note that we do not check for ambiguity or inaccessibility
3023 // here. That is handled by CheckPointerConversion.
3024 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3025 ToPointeeType->isRecordType() &&
3026 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3027 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3028 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3029 ToPointeeType,
3030 ToType, Context);
3031 return true;
3032 }
3033
3034 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3035 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3036 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3037 ToPointeeType,
3038 ToType, Context);
3039 return true;
3040 }
3041
3042 return false;
3043}
3044
3045/// Adopt the given qualifiers for the given type.
3047 Qualifiers TQs = T.getQualifiers();
3048
3049 // Check whether qualifiers already match.
3050 if (TQs == Qs)
3051 return T;
3052
3053 if (Qs.compatiblyIncludes(TQs, Context))
3054 return Context.getQualifiedType(T, Qs);
3055
3056 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3057}
3058
3060 QualType& ConvertedType,
3061 bool &IncompatibleObjC) {
3062 if (!getLangOpts().ObjC)
3063 return false;
3064
3065 // The set of qualifiers on the type we're converting from.
3066 Qualifiers FromQualifiers = FromType.getQualifiers();
3067
3068 // First, we handle all conversions on ObjC object pointer types.
3069 const ObjCObjectPointerType* ToObjCPtr =
3070 ToType->getAs<ObjCObjectPointerType>();
3071 const ObjCObjectPointerType *FromObjCPtr =
3072 FromType->getAs<ObjCObjectPointerType>();
3073
3074 if (ToObjCPtr && FromObjCPtr) {
3075 // If the pointee types are the same (ignoring qualifications),
3076 // then this is not a pointer conversion.
3077 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3078 FromObjCPtr->getPointeeType()))
3079 return false;
3080
3081 // Conversion between Objective-C pointers.
3082 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3083 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3084 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3085 if (getLangOpts().CPlusPlus && LHS && RHS &&
3087 FromObjCPtr->getPointeeType(), getASTContext()))
3088 return false;
3089 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3090 ToObjCPtr->getPointeeType(),
3091 ToType, Context);
3092 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3093 return true;
3094 }
3095
3096 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3097 // Okay: this is some kind of implicit downcast of Objective-C
3098 // interfaces, which is permitted. However, we're going to
3099 // complain about it.
3100 IncompatibleObjC = true;
3101 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3102 ToObjCPtr->getPointeeType(),
3103 ToType, Context);
3104 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3105 return true;
3106 }
3107 }
3108 // Beyond this point, both types need to be C pointers or block pointers.
3109 QualType ToPointeeType;
3110 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3111 ToPointeeType = ToCPtr->getPointeeType();
3112 else if (const BlockPointerType *ToBlockPtr =
3113 ToType->getAs<BlockPointerType>()) {
3114 // Objective C++: We're able to convert from a pointer to any object
3115 // to a block pointer type.
3116 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3117 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3118 return true;
3119 }
3120 ToPointeeType = ToBlockPtr->getPointeeType();
3121 }
3122 else if (FromType->getAs<BlockPointerType>() &&
3123 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3124 // Objective C++: We're able to convert from a block pointer type to a
3125 // pointer to any object.
3126 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3127 return true;
3128 }
3129 else
3130 return false;
3131
3132 QualType FromPointeeType;
3133 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3134 FromPointeeType = FromCPtr->getPointeeType();
3135 else if (const BlockPointerType *FromBlockPtr =
3136 FromType->getAs<BlockPointerType>())
3137 FromPointeeType = FromBlockPtr->getPointeeType();
3138 else
3139 return false;
3140
3141 // If we have pointers to pointers, recursively check whether this
3142 // is an Objective-C conversion.
3143 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3144 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3145 IncompatibleObjC)) {
3146 // We always complain about this conversion.
3147 IncompatibleObjC = true;
3148 ConvertedType = Context.getPointerType(ConvertedType);
3149 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3150 return true;
3151 }
3152 // Allow conversion of pointee being objective-c pointer to another one;
3153 // as in I* to id.
3154 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3155 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3156 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3157 IncompatibleObjC)) {
3158
3159 ConvertedType = Context.getPointerType(ConvertedType);
3160 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3161 return true;
3162 }
3163
3164 // If we have pointers to functions or blocks, check whether the only
3165 // differences in the argument and result types are in Objective-C
3166 // pointer conversions. If so, we permit the conversion (but
3167 // complain about it).
3168 const FunctionProtoType *FromFunctionType
3169 = FromPointeeType->getAs<FunctionProtoType>();
3170 const FunctionProtoType *ToFunctionType
3171 = ToPointeeType->getAs<FunctionProtoType>();
3172 if (FromFunctionType && ToFunctionType) {
3173 // If the function types are exactly the same, this isn't an
3174 // Objective-C pointer conversion.
3175 if (Context.getCanonicalType(FromPointeeType)
3176 == Context.getCanonicalType(ToPointeeType))
3177 return false;
3178
3179 // Perform the quick checks that will tell us whether these
3180 // function types are obviously different.
3181 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3182 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3183 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3184 return false;
3185
3186 bool HasObjCConversion = false;
3187 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3188 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3189 // Okay, the types match exactly. Nothing to do.
3190 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3191 ToFunctionType->getReturnType(),
3192 ConvertedType, IncompatibleObjC)) {
3193 // Okay, we have an Objective-C pointer conversion.
3194 HasObjCConversion = true;
3195 } else {
3196 // Function types are too different. Abort.
3197 return false;
3198 }
3199
3200 // Check argument types.
3201 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3202 ArgIdx != NumArgs; ++ArgIdx) {
3203 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3204 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3205 if (Context.getCanonicalType(FromArgType)
3206 == Context.getCanonicalType(ToArgType)) {
3207 // Okay, the types match exactly. Nothing to do.
3208 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3209 ConvertedType, IncompatibleObjC)) {
3210 // Okay, we have an Objective-C pointer conversion.
3211 HasObjCConversion = true;
3212 } else {
3213 // Argument types are too different. Abort.
3214 return false;
3215 }
3216 }
3217
3218 if (HasObjCConversion) {
3219 // We had an Objective-C conversion. Allow this pointer
3220 // conversion, but complain about it.
3221 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3222 IncompatibleObjC = true;
3223 return true;
3224 }
3225 }
3226
3227 return false;
3228}
3229
3231 QualType& ConvertedType) {
3232 QualType ToPointeeType;
3233 if (const BlockPointerType *ToBlockPtr =
3234 ToType->getAs<BlockPointerType>())
3235 ToPointeeType = ToBlockPtr->getPointeeType();
3236 else
3237 return false;
3238
3239 QualType FromPointeeType;
3240 if (const BlockPointerType *FromBlockPtr =
3241 FromType->getAs<BlockPointerType>())
3242 FromPointeeType = FromBlockPtr->getPointeeType();
3243 else
3244 return false;
3245 // We have pointer to blocks, check whether the only
3246 // differences in the argument and result types are in Objective-C
3247 // pointer conversions. If so, we permit the conversion.
3248
3249 const FunctionProtoType *FromFunctionType
3250 = FromPointeeType->getAs<FunctionProtoType>();
3251 const FunctionProtoType *ToFunctionType
3252 = ToPointeeType->getAs<FunctionProtoType>();
3253
3254 if (!FromFunctionType || !ToFunctionType)
3255 return false;
3256
3257 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3258 return true;
3259
3260 // Perform the quick checks that will tell us whether these
3261 // function types are obviously different.
3262 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3263 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3264 return false;
3265
3266 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3267 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3268 if (FromEInfo != ToEInfo)
3269 return false;
3270
3271 bool IncompatibleObjC = false;
3272 if (Context.hasSameType(FromFunctionType->getReturnType(),
3273 ToFunctionType->getReturnType())) {
3274 // Okay, the types match exactly. Nothing to do.
3275 } else {
3276 QualType RHS = FromFunctionType->getReturnType();
3277 QualType LHS = ToFunctionType->getReturnType();
3278 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3279 !RHS.hasQualifiers() && LHS.hasQualifiers())
3280 LHS = LHS.getUnqualifiedType();
3281
3282 if (Context.hasSameType(RHS,LHS)) {
3283 // OK exact match.
3284 } else if (isObjCPointerConversion(RHS, LHS,
3285 ConvertedType, IncompatibleObjC)) {
3286 if (IncompatibleObjC)
3287 return false;
3288 // Okay, we have an Objective-C pointer conversion.
3289 }
3290 else
3291 return false;
3292 }
3293
3294 // Check argument types.
3295 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3296 ArgIdx != NumArgs; ++ArgIdx) {
3297 IncompatibleObjC = false;
3298 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3299 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3300 if (Context.hasSameType(FromArgType, ToArgType)) {
3301 // Okay, the types match exactly. Nothing to do.
3302 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3303 ConvertedType, IncompatibleObjC)) {
3304 if (IncompatibleObjC)
3305 return false;
3306 // Okay, we have an Objective-C pointer conversion.
3307 } else
3308 // Argument types are too different. Abort.
3309 return false;
3310 }
3311
3313 bool CanUseToFPT, CanUseFromFPT;
3314 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3315 CanUseToFPT, CanUseFromFPT,
3316 NewParamInfos))
3317 return false;
3318
3319 ConvertedType = ToType;
3320 return true;
3321}
3322
3323enum {
3331};
3332
3333/// Attempts to get the FunctionProtoType from a Type. Handles
3334/// MemberFunctionPointers properly.
3336 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3337 return FPT;
3338
3339 if (auto *MPT = FromType->getAs<MemberPointerType>())
3340 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3341
3342 return nullptr;
3343}
3344
3346 QualType FromType, QualType ToType) {
3347 // If either type is not valid, include no extra info.
3348 if (FromType.isNull() || ToType.isNull()) {
3349 PDiag << ft_default;
3350 return;
3351 }
3352
3353 // Get the function type from the pointers.
3354 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3355 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3356 *ToMember = ToType->castAs<MemberPointerType>();
3357 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3358 ToMember->getMostRecentCXXRecordDecl())) {
3360 if (ToMember->isSugared())
3361 PDiag << Context.getCanonicalTagType(
3362 ToMember->getMostRecentCXXRecordDecl());
3363 else
3364 PDiag << ToMember->getQualifier();
3365 if (FromMember->isSugared())
3366 PDiag << Context.getCanonicalTagType(
3367 FromMember->getMostRecentCXXRecordDecl());
3368 else
3369 PDiag << FromMember->getQualifier();
3370 return;
3371 }
3372 FromType = FromMember->getPointeeType();
3373 ToType = ToMember->getPointeeType();
3374 }
3375
3376 if (FromType->isPointerType())
3377 FromType = FromType->getPointeeType();
3378 if (ToType->isPointerType())
3379 ToType = ToType->getPointeeType();
3380
3381 // Remove references.
3382 FromType = FromType.getNonReferenceType();
3383 ToType = ToType.getNonReferenceType();
3384
3385 // Don't print extra info for non-specialized template functions.
3386 if (FromType->isInstantiationDependentType() &&
3387 !FromType->getAs<TemplateSpecializationType>()) {
3388 PDiag << ft_default;
3389 return;
3390 }
3391
3392 // No extra info for same types.
3393 if (Context.hasSameType(FromType, ToType)) {
3394 PDiag << ft_default;
3395 return;
3396 }
3397
3398 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3399 *ToFunction = tryGetFunctionProtoType(ToType);
3400
3401 // Both types need to be function types.
3402 if (!FromFunction || !ToFunction) {
3403 PDiag << ft_default;
3404 return;
3405 }
3406
3407 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3408 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3409 << FromFunction->getNumParams();
3410 return;
3411 }
3412
3413 // Handle different parameter types.
3414 unsigned ArgPos;
3415 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3416 PDiag << ft_parameter_mismatch << ArgPos + 1
3417 << ToFunction->getParamType(ArgPos)
3418 << FromFunction->getParamType(ArgPos);
3419 return;
3420 }
3421
3422 // Handle different return type.
3423 if (!Context.hasSameType(FromFunction->getReturnType(),
3424 ToFunction->getReturnType())) {
3425 PDiag << ft_return_type << ToFunction->getReturnType()
3426 << FromFunction->getReturnType();
3427 return;
3428 }
3429
3430 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3431 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3432 << FromFunction->getMethodQuals();
3433 return;
3434 }
3435
3436 // Handle exception specification differences on canonical type (in C++17
3437 // onwards).
3439 ->isNothrow() !=
3440 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3441 ->isNothrow()) {
3442 PDiag << ft_noexcept;
3443 return;
3444 }
3445
3446 // Unable to find a difference, so add no extra info.
3447 PDiag << ft_default;
3448}
3449
3451 ArrayRef<QualType> New, unsigned *ArgPos,
3452 bool Reversed) {
3453 assert(llvm::size(Old) == llvm::size(New) &&
3454 "Can't compare parameters of functions with different number of "
3455 "parameters!");
3456
3457 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3458 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3459 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3460
3461 // Ignore address spaces in pointee type. This is to disallow overloading
3462 // on __ptr32/__ptr64 address spaces.
3463 QualType OldType =
3464 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3465 QualType NewType =
3466 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3467
3468 if (!Context.hasSameType(OldType, NewType)) {
3469 if (ArgPos)
3470 *ArgPos = Idx;
3471 return false;
3472 }
3473 }
3474 return true;
3475}
3476
3478 const FunctionProtoType *NewType,
3479 unsigned *ArgPos, bool Reversed) {
3480 return FunctionParamTypesAreEqual(OldType->param_types(),
3481 NewType->param_types(), ArgPos, Reversed);
3482}
3483
3485 const FunctionDecl *NewFunction,
3486 unsigned *ArgPos,
3487 bool Reversed) {
3488
3489 if (OldFunction->getNumNonObjectParams() !=
3490 NewFunction->getNumNonObjectParams())
3491 return false;
3492
3493 unsigned OldIgnore =
3495 unsigned NewIgnore =
3497
3498 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3499 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3500
3501 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3502 NewPT->param_types().slice(NewIgnore),
3503 ArgPos, Reversed);
3504}
3505
3507 CastKind &Kind,
3508 CXXCastPath& BasePath,
3509 bool IgnoreBaseAccess,
3510 bool Diagnose) {
3511 QualType FromType = From->getType();
3512 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3513
3514 Kind = CK_BitCast;
3515
3516 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3519 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3520 DiagRuntimeBehavior(From->getExprLoc(), From,
3521 PDiag(diag::warn_impcast_bool_to_null_pointer)
3522 << ToType << From->getSourceRange());
3523 else if (!isUnevaluatedContext())
3524 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3525 << ToType << From->getSourceRange();
3526 }
3527 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3528 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3529 QualType FromPointeeType = FromPtrType->getPointeeType(),
3530 ToPointeeType = ToPtrType->getPointeeType();
3531
3532 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3533 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3534 // We must have a derived-to-base conversion. Check an
3535 // ambiguous or inaccessible conversion.
3536 unsigned InaccessibleID = 0;
3537 unsigned AmbiguousID = 0;
3538 if (Diagnose) {
3539 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3540 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3541 }
3543 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3544 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3545 &BasePath, IgnoreBaseAccess))
3546 return true;
3547
3548 // The conversion was successful.
3549 Kind = CK_DerivedToBase;
3550 }
3551
3552 if (Diagnose && !IsCStyleOrFunctionalCast &&
3553 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3554 assert(getLangOpts().MSVCCompat &&
3555 "this should only be possible with MSVCCompat!");
3556 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3557 << From->getSourceRange();
3558 }
3559 }
3560 } else if (const ObjCObjectPointerType *ToPtrType =
3561 ToType->getAs<ObjCObjectPointerType>()) {
3562 if (const ObjCObjectPointerType *FromPtrType =
3563 FromType->getAs<ObjCObjectPointerType>()) {
3564 // Objective-C++ conversions are always okay.
3565 // FIXME: We should have a different class of conversions for the
3566 // Objective-C++ implicit conversions.
3567 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3568 return false;
3569 } else if (FromType->isBlockPointerType()) {
3570 Kind = CK_BlockPointerToObjCPointerCast;
3571 } else {
3572 Kind = CK_CPointerToObjCPointerCast;
3573 }
3574 } else if (ToType->isBlockPointerType()) {
3575 if (!FromType->isBlockPointerType())
3576 Kind = CK_AnyPointerToBlockPointerCast;
3577 }
3578
3579 // We shouldn't fall into this case unless it's valid for other
3580 // reasons.
3582 Kind = CK_NullToPointer;
3583
3584 return false;
3585}
3586
3588 QualType ToType,
3589 bool InOverloadResolution,
3590 QualType &ConvertedType) {
3591 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3592 if (!ToTypePtr)
3593 return false;
3594
3595 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3597 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3599 ConvertedType = ToType;
3600 return true;
3601 }
3602
3603 // Otherwise, both types have to be member pointers.
3604 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3605 if (!FromTypePtr)
3606 return false;
3607
3608 // A pointer to member of B can be converted to a pointer to member of D,
3609 // where D is derived from B (C++ 4.11p2).
3610 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3611 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3612
3613 if (!declaresSameEntity(FromClass, ToClass) &&
3614 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3615 ConvertedType = Context.getMemberPointerType(
3616 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3617 return true;
3618 }
3619
3620 return false;
3621}
3622
3624 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3625 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3626 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3627 // Lock down the inheritance model right now in MS ABI, whether or not the
3628 // pointee types are the same.
3629 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3630 (void)isCompleteType(CheckLoc, FromType);
3631 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3632 }
3633
3634 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3635 if (!FromPtrType) {
3636 // This must be a null pointer to member pointer conversion
3637 Kind = CK_NullToMemberPointer;
3639 }
3640
3641 // T == T, modulo cv
3643 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3644 ToPtrType->getPointeeType()))
3646
3647 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3648 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3649
3650 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3651 const CXXRecordDecl *Cls) {
3652 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3653 PD << Qual;
3654 else
3655 PD << Context.getCanonicalTagType(Cls);
3656 };
3657 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3658 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3659 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3660 return PD;
3661 };
3662
3663 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3665 std::swap(Base, Derived);
3666
3667 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3668 /*DetectVirtual=*/true);
3669 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3671
3672 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3673 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3674 PD << int(Direction);
3675 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3676 Diag(CheckLoc, PD);
3678 }
3679
3680 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3681 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3682 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3683 Diag(CheckLoc, PD);
3685 }
3686
3687 // Must be a base to derived member conversion.
3688 BuildBasePathArray(Paths, BasePath);
3690 ? CK_DerivedToBaseMemberPointer
3691 : CK_BaseToDerivedMemberPointer;
3692
3693 if (!IgnoreBaseAccess)
3694 switch (CheckBaseClassAccess(
3695 CheckLoc, Base, Derived, Paths.front(),
3697 ? diag::err_upcast_to_inaccessible_base
3698 : diag::err_downcast_from_inaccessible_base,
3699 [&](PartialDiagnostic &PD) {
3700 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3701 DerivedQual = ToPtrType->getQualifier();
3702 if (Direction == MemberPointerConversionDirection::Upcast)
3703 std::swap(BaseQual, DerivedQual);
3704 DiagCls(PD, DerivedQual, Derived);
3705 DiagCls(PD, BaseQual, Base);
3706 })) {
3708 case Sema::AR_delayed:
3709 case Sema::AR_dependent:
3710 // Optimistically assume that the delayed and dependent cases
3711 // will work out.
3712 break;
3713
3716 }
3717
3719}
3720
3721/// Determine whether the lifetime conversion between the two given
3722/// qualifiers sets is nontrivial.
3724 Qualifiers ToQuals) {
3725 // Converting anything to const __unsafe_unretained is trivial.
3726 if (ToQuals.hasConst() &&
3728 return false;
3729
3730 return true;
3731}
3732
3733/// Perform a single iteration of the loop for checking if a qualification
3734/// conversion is valid.
3735///
3736/// Specifically, check whether any change between the qualifiers of \p
3737/// FromType and \p ToType is permissible, given knowledge about whether every
3738/// outer layer is const-qualified.
3740 bool CStyle, bool IsTopLevel,
3741 bool &PreviousToQualsIncludeConst,
3742 bool &ObjCLifetimeConversion,
3743 const ASTContext &Ctx) {
3744 Qualifiers FromQuals = FromType.getQualifiers();
3745 Qualifiers ToQuals = ToType.getQualifiers();
3746
3747 // Ignore __unaligned qualifier.
3748 FromQuals.removeUnaligned();
3749
3750 // Objective-C ARC:
3751 // Check Objective-C lifetime conversions.
3752 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3753 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3754 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3755 ObjCLifetimeConversion = true;
3756 FromQuals.removeObjCLifetime();
3757 ToQuals.removeObjCLifetime();
3758 } else {
3759 // Qualification conversions cannot cast between different
3760 // Objective-C lifetime qualifiers.
3761 return false;
3762 }
3763 }
3764
3765 // Allow addition/removal of GC attributes but not changing GC attributes.
3766 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3767 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3768 FromQuals.removeObjCGCAttr();
3769 ToQuals.removeObjCGCAttr();
3770 }
3771
3772 // __ptrauth qualifiers must match exactly.
3773 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3774 return false;
3775
3776 // -- for every j > 0, if const is in cv 1,j then const is in cv
3777 // 2,j, and similarly for volatile.
3778 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3779 return false;
3780
3781 // If address spaces mismatch:
3782 // - in top level it is only valid to convert to addr space that is a
3783 // superset in all cases apart from C-style casts where we allow
3784 // conversions between overlapping address spaces.
3785 // - in non-top levels it is not a valid conversion.
3786 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3787 (!IsTopLevel ||
3788 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3789 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3790 return false;
3791
3792 // -- if the cv 1,j and cv 2,j are different, then const is in
3793 // every cv for 0 < k < j.
3794 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3795 !PreviousToQualsIncludeConst)
3796 return false;
3797
3798 // The following wording is from C++20, where the result of the conversion
3799 // is T3, not T2.
3800 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3801 // "array of unknown bound of"
3802 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3803 return false;
3804
3805 // -- if the resulting P3,i is different from P1,i [...], then const is
3806 // added to every cv 3_k for 0 < k < i.
3807 if (!CStyle && FromType->isConstantArrayType() &&
3808 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3809 return false;
3810
3811 // Keep track of whether all prior cv-qualifiers in the "to" type
3812 // include const.
3813 PreviousToQualsIncludeConst =
3814 PreviousToQualsIncludeConst && ToQuals.hasConst();
3815 return true;
3816}
3817
3818bool
3820 bool CStyle, bool &ObjCLifetimeConversion) {
3821 FromType = Context.getCanonicalType(FromType);
3822 ToType = Context.getCanonicalType(ToType);
3823 ObjCLifetimeConversion = false;
3824
3825 // If FromType and ToType are the same type, this is not a
3826 // qualification conversion.
3827 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3828 return false;
3829
3830 // (C++ 4.4p4):
3831 // A conversion can add cv-qualifiers at levels other than the first
3832 // in multi-level pointers, subject to the following rules: [...]
3833 bool PreviousToQualsIncludeConst = true;
3834 bool UnwrappedAnyPointer = false;
3835 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3836 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3837 !UnwrappedAnyPointer,
3838 PreviousToQualsIncludeConst,
3839 ObjCLifetimeConversion, getASTContext()))
3840 return false;
3841 UnwrappedAnyPointer = true;
3842 }
3843
3844 // We are left with FromType and ToType being the pointee types
3845 // after unwrapping the original FromType and ToType the same number
3846 // of times. If we unwrapped any pointers, and if FromType and
3847 // ToType have the same unqualified type (since we checked
3848 // qualifiers above), then this is a qualification conversion.
3849 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3850}
3851
3852/// - Determine whether this is a conversion from a scalar type to an
3853/// atomic type.
3854///
3855/// If successful, updates \c SCS's second and third steps in the conversion
3856/// sequence to finish the conversion.
3857static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3858 bool InOverloadResolution,
3860 bool CStyle) {
3861 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3862 if (!ToAtomic)
3863 return false;
3864
3866 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3867 InOverloadResolution, InnerSCS,
3868 CStyle, /*AllowObjCWritebackConversion=*/false))
3869 return false;
3870
3871 SCS.Second = InnerSCS.Second;
3872 SCS.setToType(1, InnerSCS.getToType(1));
3873 SCS.Third = InnerSCS.Third;
3876 SCS.setToType(2, InnerSCS.getToType(2));
3877 return true;
3878}
3879
3882 QualType Type) {
3883 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3884 if (CtorType->getNumParams() > 0) {
3885 QualType FirstArg = CtorType->getParamType(0);
3886 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3887 return true;
3888 }
3889 return false;
3890}
3891
3892static OverloadingResult
3894 CXXRecordDecl *To,
3896 OverloadCandidateSet &CandidateSet,
3897 bool AllowExplicit) {
3899 for (auto *D : S.LookupConstructors(To)) {
3900 auto Info = getConstructorInfo(D);
3901 if (!Info)
3902 continue;
3903
3904 bool Usable = !Info.Constructor->isInvalidDecl() &&
3905 S.isInitListConstructor(Info.Constructor);
3906 if (Usable) {
3907 bool SuppressUserConversions = false;
3908 if (Info.ConstructorTmpl)
3909 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3910 /*ExplicitArgs*/ nullptr, From,
3911 CandidateSet, SuppressUserConversions,
3912 /*PartialOverloading*/ false,
3913 AllowExplicit);
3914 else
3915 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3916 CandidateSet, SuppressUserConversions,
3917 /*PartialOverloading*/ false, AllowExplicit);
3918 }
3919 }
3920
3921 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3922
3924 switch (auto Result =
3925 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3926 case OR_Deleted:
3927 case OR_Success: {
3928 // Record the standard conversion we used and the conversion function.
3930 QualType ThisType = Constructor->getFunctionObjectParameterType();
3931 // Initializer lists don't have conversions as such.
3933 User.HadMultipleCandidates = HadMultipleCandidates;
3935 User.FoundConversionFunction = Best->FoundDecl;
3937 User.After.setFromType(ThisType);
3938 User.After.setAllToTypes(ToType);
3939 return Result;
3940 }
3941
3943 return OR_No_Viable_Function;
3944 case OR_Ambiguous:
3945 return OR_Ambiguous;
3946 }
3947
3948 llvm_unreachable("Invalid OverloadResult!");
3949}
3950
3951/// Determines whether there is a user-defined conversion sequence
3952/// (C++ [over.ics.user]) that converts expression From to the type
3953/// ToType. If such a conversion exists, User will contain the
3954/// user-defined conversion sequence that performs such a conversion
3955/// and this routine will return true. Otherwise, this routine returns
3956/// false and User is unspecified.
3957///
3958/// \param AllowExplicit true if the conversion should consider C++0x
3959/// "explicit" conversion functions as well as non-explicit conversion
3960/// functions (C++0x [class.conv.fct]p2).
3961///
3962/// \param AllowObjCConversionOnExplicit true if the conversion should
3963/// allow an extra Objective-C pointer conversion on uses of explicit
3964/// constructors. Requires \c AllowExplicit to also be set.
3965static OverloadingResult
3968 OverloadCandidateSet &CandidateSet,
3969 AllowedExplicit AllowExplicit,
3970 bool AllowObjCConversionOnExplicit) {
3971 assert(AllowExplicit != AllowedExplicit::None ||
3972 !AllowObjCConversionOnExplicit);
3974
3975 // Whether we will only visit constructors.
3976 bool ConstructorsOnly = false;
3977
3978 // If the type we are conversion to is a class type, enumerate its
3979 // constructors.
3980 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
3981 // C++ [over.match.ctor]p1:
3982 // When objects of class type are direct-initialized (8.5), or
3983 // copy-initialized from an expression of the same or a
3984 // derived class type (8.5), overload resolution selects the
3985 // constructor. [...] For copy-initialization, the candidate
3986 // functions are all the converting constructors (12.3.1) of
3987 // that class. The argument list is the expression-list within
3988 // the parentheses of the initializer.
3989 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3990 (From->getType()->isRecordType() &&
3991 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3992 ConstructorsOnly = true;
3993
3994 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3995 // We're not going to find any constructors.
3996 } else if (auto *ToRecordDecl =
3997 dyn_cast<CXXRecordDecl>(ToRecordType->getOriginalDecl())) {
3998 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
3999
4000 Expr **Args = &From;
4001 unsigned NumArgs = 1;
4002 bool ListInitializing = false;
4003 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4004 // But first, see if there is an init-list-constructor that will work.
4006 S, From, ToType, ToRecordDecl, User, CandidateSet,
4007 AllowExplicit == AllowedExplicit::All);
4008 if (Result != OR_No_Viable_Function)
4009 return Result;
4010 // Never mind.
4011 CandidateSet.clear(
4013
4014 // If we're list-initializing, we pass the individual elements as
4015 // arguments, not the entire list.
4016 Args = InitList->getInits();
4017 NumArgs = InitList->getNumInits();
4018 ListInitializing = true;
4019 }
4020
4021 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4022 auto Info = getConstructorInfo(D);
4023 if (!Info)
4024 continue;
4025
4026 bool Usable = !Info.Constructor->isInvalidDecl();
4027 if (!ListInitializing)
4028 Usable = Usable && Info.Constructor->isConvertingConstructor(
4029 /*AllowExplicit*/ true);
4030 if (Usable) {
4031 bool SuppressUserConversions = !ConstructorsOnly;
4032 // C++20 [over.best.ics.general]/4.5:
4033 // if the target is the first parameter of a constructor [of class
4034 // X] and the constructor [...] is a candidate by [...] the second
4035 // phase of [over.match.list] when the initializer list has exactly
4036 // one element that is itself an initializer list, [...] and the
4037 // conversion is to X or reference to cv X, user-defined conversion
4038 // sequences are not considered.
4039 if (SuppressUserConversions && ListInitializing) {
4040 SuppressUserConversions =
4041 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4042 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4043 ToType);
4044 }
4045 if (Info.ConstructorTmpl)
4047 Info.ConstructorTmpl, Info.FoundDecl,
4048 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4049 CandidateSet, SuppressUserConversions,
4050 /*PartialOverloading*/ false,
4051 AllowExplicit == AllowedExplicit::All);
4052 else
4053 // Allow one user-defined conversion when user specifies a
4054 // From->ToType conversion via an static cast (c-style, etc).
4055 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4056 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4057 SuppressUserConversions,
4058 /*PartialOverloading*/ false,
4059 AllowExplicit == AllowedExplicit::All);
4060 }
4061 }
4062 }
4063 }
4064
4065 // Enumerate conversion functions, if we're allowed to.
4066 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4067 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4068 // No conversion functions from incomplete types.
4069 } else if (const RecordType *FromRecordType =
4070 From->getType()->getAsCanonical<RecordType>()) {
4071 if (auto *FromRecordDecl =
4072 dyn_cast<CXXRecordDecl>(FromRecordType->getOriginalDecl())) {
4073 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4074 // Add all of the conversion functions as candidates.
4075 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4076 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4077 DeclAccessPair FoundDecl = I.getPair();
4078 NamedDecl *D = FoundDecl.getDecl();
4079 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4080 if (isa<UsingShadowDecl>(D))
4081 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4082
4083 CXXConversionDecl *Conv;
4084 FunctionTemplateDecl *ConvTemplate;
4085 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4086 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4087 else
4088 Conv = cast<CXXConversionDecl>(D);
4089
4090 if (ConvTemplate)
4092 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4093 CandidateSet, AllowObjCConversionOnExplicit,
4094 AllowExplicit != AllowedExplicit::None);
4095 else
4096 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4097 CandidateSet, AllowObjCConversionOnExplicit,
4098 AllowExplicit != AllowedExplicit::None);
4099 }
4100 }
4101 }
4102
4103 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4104
4106 switch (auto Result =
4107 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4108 case OR_Success:
4109 case OR_Deleted:
4110 // Record the standard conversion we used and the conversion function.
4112 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4113 // C++ [over.ics.user]p1:
4114 // If the user-defined conversion is specified by a
4115 // constructor (12.3.1), the initial standard conversion
4116 // sequence converts the source type to the type required by
4117 // the argument of the constructor.
4118 //
4119 if (isa<InitListExpr>(From)) {
4120 // Initializer lists don't have conversions as such.
4122 User.Before.FromBracedInitList = true;
4123 } else {
4124 if (Best->Conversions[0].isEllipsis())
4125 User.EllipsisConversion = true;
4126 else {
4127 User.Before = Best->Conversions[0].Standard;
4128 User.EllipsisConversion = false;
4129 }
4130 }
4131 User.HadMultipleCandidates = HadMultipleCandidates;
4133 User.FoundConversionFunction = Best->FoundDecl;
4135 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4136 User.After.setAllToTypes(ToType);
4137 return Result;
4138 }
4139 if (CXXConversionDecl *Conversion
4140 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4141
4142 assert(Best->HasFinalConversion);
4143
4144 // C++ [over.ics.user]p1:
4145 //
4146 // [...] If the user-defined conversion is specified by a
4147 // conversion function (12.3.2), the initial standard
4148 // conversion sequence converts the source type to the
4149 // implicit object parameter of the conversion function.
4150 User.Before = Best->Conversions[0].Standard;
4151 User.HadMultipleCandidates = HadMultipleCandidates;
4152 User.ConversionFunction = Conversion;
4153 User.FoundConversionFunction = Best->FoundDecl;
4154 User.EllipsisConversion = false;
4155
4156 // C++ [over.ics.user]p2:
4157 // The second standard conversion sequence converts the
4158 // result of the user-defined conversion to the target type
4159 // for the sequence. Since an implicit conversion sequence
4160 // is an initialization, the special rules for
4161 // initialization by user-defined conversion apply when
4162 // selecting the best user-defined conversion for a
4163 // user-defined conversion sequence (see 13.3.3 and
4164 // 13.3.3.1).
4165 User.After = Best->FinalConversion;
4166 return Result;
4167 }
4168 llvm_unreachable("Not a constructor or conversion function?");
4169
4171 return OR_No_Viable_Function;
4172
4173 case OR_Ambiguous:
4174 return OR_Ambiguous;
4175 }
4176
4177 llvm_unreachable("Invalid OverloadResult!");
4178}
4179
4180bool
4183 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4185 OverloadingResult OvResult =
4186 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4187 CandidateSet, AllowedExplicit::None, false);
4188
4189 if (!(OvResult == OR_Ambiguous ||
4190 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4191 return false;
4192
4193 auto Cands = CandidateSet.CompleteCandidates(
4194 *this,
4196 From);
4197 if (OvResult == OR_Ambiguous)
4198 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4199 << From->getType() << ToType << From->getSourceRange();
4200 else { // OR_No_Viable_Function && !CandidateSet.empty()
4201 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4202 diag::err_typecheck_nonviable_condition_incomplete,
4203 From->getType(), From->getSourceRange()))
4204 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4205 << false << From->getType() << From->getSourceRange() << ToType;
4206 }
4207
4208 CandidateSet.NoteCandidates(
4209 *this, From, Cands);
4210 return true;
4211}
4212
4213// Helper for compareConversionFunctions that gets the FunctionType that the
4214// conversion-operator return value 'points' to, or nullptr.
4215static const FunctionType *
4217 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4218 const PointerType *RetPtrTy =
4219 ConvFuncTy->getReturnType()->getAs<PointerType>();
4220
4221 if (!RetPtrTy)
4222 return nullptr;
4223
4224 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4225}
4226
4227/// Compare the user-defined conversion functions or constructors
4228/// of two user-defined conversion sequences to determine whether any ordering
4229/// is possible.
4232 FunctionDecl *Function2) {
4233 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4234 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4235 if (!Conv1 || !Conv2)
4237
4238 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4240
4241 // Objective-C++:
4242 // If both conversion functions are implicitly-declared conversions from
4243 // a lambda closure type to a function pointer and a block pointer,
4244 // respectively, always prefer the conversion to a function pointer,
4245 // because the function pointer is more lightweight and is more likely
4246 // to keep code working.
4247 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4248 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4249 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4250 if (Block1 != Block2)
4251 return Block1 ? ImplicitConversionSequence::Worse
4253 }
4254
4255 // In order to support multiple calling conventions for the lambda conversion
4256 // operator (such as when the free and member function calling convention is
4257 // different), prefer the 'free' mechanism, followed by the calling-convention
4258 // of operator(). The latter is in place to support the MSVC-like solution of
4259 // defining ALL of the possible conversions in regards to calling-convention.
4260 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4261 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4262
4263 if (Conv1FuncRet && Conv2FuncRet &&
4264 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4265 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4266 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4267
4268 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4269 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4270
4271 CallingConv CallOpCC =
4272 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4274 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4276 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4277
4278 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4279 for (CallingConv CC : PrefOrder) {
4280 if (Conv1CC == CC)
4282 if (Conv2CC == CC)
4284 }
4285 }
4286
4288}
4289
4296
4297/// CompareImplicitConversionSequences - Compare two implicit
4298/// conversion sequences to determine whether one is better than the
4299/// other or if they are indistinguishable (C++ 13.3.3.2).
4302 const ImplicitConversionSequence& ICS1,
4303 const ImplicitConversionSequence& ICS2)
4304{
4305 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4306 // conversion sequences (as defined in 13.3.3.1)
4307 // -- a standard conversion sequence (13.3.3.1.1) is a better
4308 // conversion sequence than a user-defined conversion sequence or
4309 // an ellipsis conversion sequence, and
4310 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4311 // conversion sequence than an ellipsis conversion sequence
4312 // (13.3.3.1.3).
4313 //
4314 // C++0x [over.best.ics]p10:
4315 // For the purpose of ranking implicit conversion sequences as
4316 // described in 13.3.3.2, the ambiguous conversion sequence is
4317 // treated as a user-defined sequence that is indistinguishable
4318 // from any other user-defined conversion sequence.
4319
4320 // String literal to 'char *' conversion has been deprecated in C++03. It has
4321 // been removed from C++11. We still accept this conversion, if it happens at
4322 // the best viable function. Otherwise, this conversion is considered worse
4323 // than ellipsis conversion. Consider this as an extension; this is not in the
4324 // standard. For example:
4325 //
4326 // int &f(...); // #1
4327 // void f(char*); // #2
4328 // void g() { int &r = f("foo"); }
4329 //
4330 // In C++03, we pick #2 as the best viable function.
4331 // In C++11, we pick #1 as the best viable function, because ellipsis
4332 // conversion is better than string-literal to char* conversion (since there
4333 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4334 // convert arguments, #2 would be the best viable function in C++11.
4335 // If the best viable function has this conversion, a warning will be issued
4336 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4337
4338 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4341 // Ill-formedness must not differ
4342 ICS1.isBad() == ICS2.isBad())
4346
4347 if (ICS1.getKindRank() < ICS2.getKindRank())
4349 if (ICS2.getKindRank() < ICS1.getKindRank())
4351
4352 // The following checks require both conversion sequences to be of
4353 // the same kind.
4354 if (ICS1.getKind() != ICS2.getKind())
4356
4359
4360 // Two implicit conversion sequences of the same form are
4361 // indistinguishable conversion sequences unless one of the
4362 // following rules apply: (C++ 13.3.3.2p3):
4363
4364 // List-initialization sequence L1 is a better conversion sequence than
4365 // list-initialization sequence L2 if:
4366 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4367 // if not that,
4368 // — L1 and L2 convert to arrays of the same element type, and either the
4369 // number of elements n_1 initialized by L1 is less than the number of
4370 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4371 // an array of unknown bound and L1 does not,
4372 // even if one of the other rules in this paragraph would otherwise apply.
4373 if (!ICS1.isBad()) {
4374 bool StdInit1 = false, StdInit2 = false;
4377 nullptr);
4380 nullptr);
4381 if (StdInit1 != StdInit2)
4382 return StdInit1 ? ImplicitConversionSequence::Better
4384
4387 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4389 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4391 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4392 CAT2->getElementType())) {
4393 // Both to arrays of the same element type
4394 if (CAT1->getSize() != CAT2->getSize())
4395 // Different sized, the smaller wins
4396 return CAT1->getSize().ult(CAT2->getSize())
4401 // One is incomplete, it loses
4405 }
4406 }
4407 }
4408
4409 if (ICS1.isStandard())
4410 // Standard conversion sequence S1 is a better conversion sequence than
4411 // standard conversion sequence S2 if [...]
4412 Result = CompareStandardConversionSequences(S, Loc,
4413 ICS1.Standard, ICS2.Standard);
4414 else if (ICS1.isUserDefined()) {
4415 // User-defined conversion sequence U1 is a better conversion
4416 // sequence than another user-defined conversion sequence U2 if
4417 // they contain the same user-defined conversion function or
4418 // constructor and if the second standard conversion sequence of
4419 // U1 is better than the second standard conversion sequence of
4420 // U2 (C++ 13.3.3.2p3).
4423 Result = CompareStandardConversionSequences(S, Loc,
4424 ICS1.UserDefined.After,
4425 ICS2.UserDefined.After);
4426 else
4427 Result = compareConversionFunctions(S,
4430 }
4431
4432 return Result;
4433}
4434
4435// Per 13.3.3.2p3, compare the given standard conversion sequences to
4436// determine if one is a proper subset of the other.
4439 const StandardConversionSequence& SCS1,
4440 const StandardConversionSequence& SCS2) {
4443
4444 // the identity conversion sequence is considered to be a subsequence of
4445 // any non-identity conversion sequence
4446 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4448 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4450
4451 if (SCS1.Second != SCS2.Second) {
4452 if (SCS1.Second == ICK_Identity)
4454 else if (SCS2.Second == ICK_Identity)
4456 else
4458 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4460
4461 if (SCS1.Third == SCS2.Third) {
4462 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4464 }
4465
4466 if (SCS1.Third == ICK_Identity)
4467 return Result == ImplicitConversionSequence::Worse
4470
4471 if (SCS2.Third == ICK_Identity)
4472 return Result == ImplicitConversionSequence::Better
4475
4477}
4478
4479/// Determine whether one of the given reference bindings is better
4480/// than the other based on what kind of bindings they are.
4481static bool
4483 const StandardConversionSequence &SCS2) {
4484 // C++0x [over.ics.rank]p3b4:
4485 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4486 // implicit object parameter of a non-static member function declared
4487 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4488 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4489 // lvalue reference to a function lvalue and S2 binds an rvalue
4490 // reference*.
4491 //
4492 // FIXME: Rvalue references. We're going rogue with the above edits,
4493 // because the semantics in the current C++0x working paper (N3225 at the
4494 // time of this writing) break the standard definition of std::forward
4495 // and std::reference_wrapper when dealing with references to functions.
4496 // Proposed wording changes submitted to CWG for consideration.
4499 return false;
4500
4501 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4502 SCS2.IsLvalueReference) ||
4505}
4506
4512
4513/// Returns kind of fixed enum promotion the \a SCS uses.
4514static FixedEnumPromotion
4516
4517 if (SCS.Second != ICK_Integral_Promotion)
4519
4520 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4521 if (!Enum)
4523
4524 if (!Enum->isFixed())
4526
4527 QualType UnderlyingType = Enum->getIntegerType();
4528 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4530
4532}
4533
4534/// CompareStandardConversionSequences - Compare two standard
4535/// conversion sequences to determine whether one is better than the
4536/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4539 const StandardConversionSequence& SCS1,
4540 const StandardConversionSequence& SCS2)
4541{
4542 // Standard conversion sequence S1 is a better conversion sequence
4543 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4544
4545 // -- S1 is a proper subsequence of S2 (comparing the conversion
4546 // sequences in the canonical form defined by 13.3.3.1.1,
4547 // excluding any Lvalue Transformation; the identity conversion
4548 // sequence is considered to be a subsequence of any
4549 // non-identity conversion sequence) or, if not that,
4552 return CK;
4553
4554 // -- the rank of S1 is better than the rank of S2 (by the rules
4555 // defined below), or, if not that,
4556 ImplicitConversionRank Rank1 = SCS1.getRank();
4557 ImplicitConversionRank Rank2 = SCS2.getRank();
4558 if (Rank1 < Rank2)
4560 else if (Rank2 < Rank1)
4562
4563 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4564 // are indistinguishable unless one of the following rules
4565 // applies:
4566
4567 // A conversion that is not a conversion of a pointer, or
4568 // pointer to member, to bool is better than another conversion
4569 // that is such a conversion.
4571 return SCS2.isPointerConversionToBool()
4574
4575 // C++14 [over.ics.rank]p4b2:
4576 // This is retroactively applied to C++11 by CWG 1601.
4577 //
4578 // A conversion that promotes an enumeration whose underlying type is fixed
4579 // to its underlying type is better than one that promotes to the promoted
4580 // underlying type, if the two are different.
4583 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4584 FEP1 != FEP2)
4588
4589 // C++ [over.ics.rank]p4b2:
4590 //
4591 // If class B is derived directly or indirectly from class A,
4592 // conversion of B* to A* is better than conversion of B* to
4593 // void*, and conversion of A* to void* is better than conversion
4594 // of B* to void*.
4595 bool SCS1ConvertsToVoid
4597 bool SCS2ConvertsToVoid
4599 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4600 // Exactly one of the conversion sequences is a conversion to
4601 // a void pointer; it's the worse conversion.
4602 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4604 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4605 // Neither conversion sequence converts to a void pointer; compare
4606 // their derived-to-base conversions.
4608 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4609 return DerivedCK;
4610 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4611 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4612 // Both conversion sequences are conversions to void
4613 // pointers. Compare the source types to determine if there's an
4614 // inheritance relationship in their sources.
4615 QualType FromType1 = SCS1.getFromType();
4616 QualType FromType2 = SCS2.getFromType();
4617
4618 // Adjust the types we're converting from via the array-to-pointer
4619 // conversion, if we need to.
4620 if (SCS1.First == ICK_Array_To_Pointer)
4621 FromType1 = S.Context.getArrayDecayedType(FromType1);
4622 if (SCS2.First == ICK_Array_To_Pointer)
4623 FromType2 = S.Context.getArrayDecayedType(FromType2);
4624
4625 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4626 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4627
4628 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4630 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4632
4633 // Objective-C++: If one interface is more specific than the
4634 // other, it is the better one.
4635 const ObjCObjectPointerType* FromObjCPtr1
4636 = FromType1->getAs<ObjCObjectPointerType>();
4637 const ObjCObjectPointerType* FromObjCPtr2
4638 = FromType2->getAs<ObjCObjectPointerType>();
4639 if (FromObjCPtr1 && FromObjCPtr2) {
4640 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4641 FromObjCPtr2);
4642 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4643 FromObjCPtr1);
4644 if (AssignLeft != AssignRight) {
4645 return AssignLeft? ImplicitConversionSequence::Better
4647 }
4648 }
4649 }
4650
4651 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4652 // Check for a better reference binding based on the kind of bindings.
4653 if (isBetterReferenceBindingKind(SCS1, SCS2))
4655 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4657 }
4658
4659 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4660 // bullet 3).
4662 = CompareQualificationConversions(S, SCS1, SCS2))
4663 return QualCK;
4664
4665 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4666 // C++ [over.ics.rank]p3b4:
4667 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4668 // which the references refer are the same type except for
4669 // top-level cv-qualifiers, and the type to which the reference
4670 // initialized by S2 refers is more cv-qualified than the type
4671 // to which the reference initialized by S1 refers.
4672 QualType T1 = SCS1.getToType(2);
4673 QualType T2 = SCS2.getToType(2);
4674 T1 = S.Context.getCanonicalType(T1);
4675 T2 = S.Context.getCanonicalType(T2);
4676 Qualifiers T1Quals, T2Quals;
4677 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4678 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4679 if (UnqualT1 == UnqualT2) {
4680 // Objective-C++ ARC: If the references refer to objects with different
4681 // lifetimes, prefer bindings that don't change lifetime.
4687 }
4688
4689 // If the type is an array type, promote the element qualifiers to the
4690 // type for comparison.
4691 if (isa<ArrayType>(T1) && T1Quals)
4692 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4693 if (isa<ArrayType>(T2) && T2Quals)
4694 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4695 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4697 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4699 }
4700 }
4701
4702 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4703 // floating-to-integral conversion if the integral conversion
4704 // is between types of the same size.
4705 // For example:
4706 // void f(float);
4707 // void f(int);
4708 // int main {
4709 // long a;
4710 // f(a);
4711 // }
4712 // Here, MSVC will call f(int) instead of generating a compile error
4713 // as clang will do in standard mode.
4714 if (S.getLangOpts().MSVCCompat &&
4717 SCS2.Second == ICK_Floating_Integral &&
4718 S.Context.getTypeSize(SCS1.getFromType()) ==
4719 S.Context.getTypeSize(SCS1.getToType(2)))
4721
4722 // Prefer a compatible vector conversion over a lax vector conversion
4723 // For example:
4724 //
4725 // typedef float __v4sf __attribute__((__vector_size__(16)));
4726 // void f(vector float);
4727 // void f(vector signed int);
4728 // int main() {
4729 // __v4sf a;
4730 // f(a);
4731 // }
4732 // Here, we'd like to choose f(vector float) and not
4733 // report an ambiguous call error
4734 if (SCS1.Second == ICK_Vector_Conversion &&
4735 SCS2.Second == ICK_Vector_Conversion) {
4736 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4737 SCS1.getFromType(), SCS1.getToType(2));
4738 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4739 SCS2.getFromType(), SCS2.getToType(2));
4740
4741 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4742 return SCS1IsCompatibleVectorConversion
4745 }
4746
4747 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4749 bool SCS1IsCompatibleSVEVectorConversion =
4750 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4751 bool SCS2IsCompatibleSVEVectorConversion =
4752 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4753
4754 if (SCS1IsCompatibleSVEVectorConversion !=
4755 SCS2IsCompatibleSVEVectorConversion)
4756 return SCS1IsCompatibleSVEVectorConversion
4759 }
4760
4761 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4763 bool SCS1IsCompatibleRVVVectorConversion =
4765 bool SCS2IsCompatibleRVVVectorConversion =
4767
4768 if (SCS1IsCompatibleRVVVectorConversion !=
4769 SCS2IsCompatibleRVVVectorConversion)
4770 return SCS1IsCompatibleRVVVectorConversion
4773 }
4775}
4776
4777/// CompareQualificationConversions - Compares two standard conversion
4778/// sequences to determine whether they can be ranked based on their
4779/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4782 const StandardConversionSequence& SCS1,
4783 const StandardConversionSequence& SCS2) {
4784 // C++ [over.ics.rank]p3:
4785 // -- S1 and S2 differ only in their qualification conversion and
4786 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4787 // [C++98]
4788 // [...] and the cv-qualification signature of type T1 is a proper subset
4789 // of the cv-qualification signature of type T2, and S1 is not the
4790 // deprecated string literal array-to-pointer conversion (4.2).
4791 // [C++2a]
4792 // [...] where T1 can be converted to T2 by a qualification conversion.
4793 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4794 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4796
4797 // FIXME: the example in the standard doesn't use a qualification
4798 // conversion (!)
4799 QualType T1 = SCS1.getToType(2);
4800 QualType T2 = SCS2.getToType(2);
4801 T1 = S.Context.getCanonicalType(T1);
4802 T2 = S.Context.getCanonicalType(T2);
4803 assert(!T1->isReferenceType() && !T2->isReferenceType());
4804 Qualifiers T1Quals, T2Quals;
4805 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4806 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4807
4808 // If the types are the same, we won't learn anything by unwrapping
4809 // them.
4810 if (UnqualT1 == UnqualT2)
4812
4813 // Don't ever prefer a standard conversion sequence that uses the deprecated
4814 // string literal array to pointer conversion.
4815 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4816 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4817
4818 // Objective-C++ ARC:
4819 // Prefer qualification conversions not involving a change in lifetime
4820 // to qualification conversions that do change lifetime.
4823 CanPick1 = false;
4826 CanPick2 = false;
4827
4828 bool ObjCLifetimeConversion;
4829 if (CanPick1 &&
4830 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4831 CanPick1 = false;
4832 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4833 // directions, so we can't short-cut this second check in general.
4834 if (CanPick2 &&
4835 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4836 CanPick2 = false;
4837
4838 if (CanPick1 != CanPick2)
4839 return CanPick1 ? ImplicitConversionSequence::Better
4842}
4843
4844/// CompareDerivedToBaseConversions - Compares two standard conversion
4845/// sequences to determine whether they can be ranked based on their
4846/// various kinds of derived-to-base conversions (C++
4847/// [over.ics.rank]p4b3). As part of these checks, we also look at
4848/// conversions between Objective-C interface types.
4851 const StandardConversionSequence& SCS1,
4852 const StandardConversionSequence& SCS2) {
4853 QualType FromType1 = SCS1.getFromType();
4854 QualType ToType1 = SCS1.getToType(1);
4855 QualType FromType2 = SCS2.getFromType();
4856 QualType ToType2 = SCS2.getToType(1);
4857
4858 // Adjust the types we're converting from via the array-to-pointer
4859 // conversion, if we need to.
4860 if (SCS1.First == ICK_Array_To_Pointer)
4861 FromType1 = S.Context.getArrayDecayedType(FromType1);
4862 if (SCS2.First == ICK_Array_To_Pointer)
4863 FromType2 = S.Context.getArrayDecayedType(FromType2);
4864
4865 // Canonicalize all of the types.
4866 FromType1 = S.Context.getCanonicalType(FromType1);
4867 ToType1 = S.Context.getCanonicalType(ToType1);
4868 FromType2 = S.Context.getCanonicalType(FromType2);
4869 ToType2 = S.Context.getCanonicalType(ToType2);
4870
4871 // C++ [over.ics.rank]p4b3:
4872 //
4873 // If class B is derived directly or indirectly from class A and
4874 // class C is derived directly or indirectly from B,
4875 //
4876 // Compare based on pointer conversions.
4877 if (SCS1.Second == ICK_Pointer_Conversion &&
4879 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4880 FromType1->isPointerType() && FromType2->isPointerType() &&
4881 ToType1->isPointerType() && ToType2->isPointerType()) {
4882 QualType FromPointee1 =
4884 QualType ToPointee1 =
4886 QualType FromPointee2 =
4888 QualType ToPointee2 =
4890
4891 // -- conversion of C* to B* is better than conversion of C* to A*,
4892 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4893 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4895 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4897 }
4898
4899 // -- conversion of B* to A* is better than conversion of C* to A*,
4900 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4901 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4903 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4905 }
4906 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4908 const ObjCObjectPointerType *FromPtr1
4909 = FromType1->getAs<ObjCObjectPointerType>();
4910 const ObjCObjectPointerType *FromPtr2
4911 = FromType2->getAs<ObjCObjectPointerType>();
4912 const ObjCObjectPointerType *ToPtr1
4913 = ToType1->getAs<ObjCObjectPointerType>();
4914 const ObjCObjectPointerType *ToPtr2
4915 = ToType2->getAs<ObjCObjectPointerType>();
4916
4917 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4918 // Apply the same conversion ranking rules for Objective-C pointer types
4919 // that we do for C++ pointers to class types. However, we employ the
4920 // Objective-C pseudo-subtyping relationship used for assignment of
4921 // Objective-C pointer types.
4922 bool FromAssignLeft
4923 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4924 bool FromAssignRight
4925 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4926 bool ToAssignLeft
4927 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4928 bool ToAssignRight
4929 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4930
4931 // A conversion to an a non-id object pointer type or qualified 'id'
4932 // type is better than a conversion to 'id'.
4933 if (ToPtr1->isObjCIdType() &&
4934 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4936 if (ToPtr2->isObjCIdType() &&
4937 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4939
4940 // A conversion to a non-id object pointer type is better than a
4941 // conversion to a qualified 'id' type
4942 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4944 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4946
4947 // A conversion to an a non-Class object pointer type or qualified 'Class'
4948 // type is better than a conversion to 'Class'.
4949 if (ToPtr1->isObjCClassType() &&
4950 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4952 if (ToPtr2->isObjCClassType() &&
4953 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4955
4956 // A conversion to a non-Class object pointer type is better than a
4957 // conversion to a qualified 'Class' type.
4958 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4960 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4962
4963 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4964 if (S.Context.hasSameType(FromType1, FromType2) &&
4965 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4966 (ToAssignLeft != ToAssignRight)) {
4967 if (FromPtr1->isSpecialized()) {
4968 // "conversion of B<A> * to B * is better than conversion of B * to
4969 // C *.
4970 bool IsFirstSame =
4971 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4972 bool IsSecondSame =
4973 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4974 if (IsFirstSame) {
4975 if (!IsSecondSame)
4977 } else if (IsSecondSame)
4979 }
4980 return ToAssignLeft? ImplicitConversionSequence::Worse
4982 }
4983
4984 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4985 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4986 (FromAssignLeft != FromAssignRight))
4987 return FromAssignLeft? ImplicitConversionSequence::Better
4989 }
4990 }
4991
4992 // Ranking of member-pointer types.
4993 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4994 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4995 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4996 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4997 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4998 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4999 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5000 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5001 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5002 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5003 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5004 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5005 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5006 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5008 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5010 }
5011 // conversion of B::* to C::* is better than conversion of A::* to C::*
5012 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5013 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5015 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5017 }
5018 }
5019
5020 if (SCS1.Second == ICK_Derived_To_Base) {
5021 // -- conversion of C to B is better than conversion of C to A,
5022 // -- binding of an expression of type C to a reference of type
5023 // B& is better than binding an expression of type C to a
5024 // reference of type A&,
5025 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5026 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5027 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5029 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5031 }
5032
5033 // -- conversion of B to A is better than conversion of C to A.
5034 // -- binding of an expression of type B to a reference of type
5035 // A& is better than binding an expression of type C to a
5036 // reference of type A&,
5037 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5038 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5039 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5041 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5043 }
5044 }
5045
5047}
5048
5050 if (!T.getQualifiers().hasUnaligned())
5051 return T;
5052
5053 Qualifiers Q;
5054 T = Ctx.getUnqualifiedArrayType(T, Q);
5055 Q.removeUnaligned();
5056 return Ctx.getQualifiedType(T, Q);
5057}
5058
5061 QualType OrigT1, QualType OrigT2,
5062 ReferenceConversions *ConvOut) {
5063 assert(!OrigT1->isReferenceType() &&
5064 "T1 must be the pointee type of the reference type");
5065 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5066
5067 QualType T1 = Context.getCanonicalType(OrigT1);
5068 QualType T2 = Context.getCanonicalType(OrigT2);
5069 Qualifiers T1Quals, T2Quals;
5070 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5071 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5072
5073 ReferenceConversions ConvTmp;
5074 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5075 Conv = ReferenceConversions();
5076
5077 // C++2a [dcl.init.ref]p4:
5078 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5079 // reference-related to "cv2 T2" if T1 is similar to T2, or
5080 // T1 is a base class of T2.
5081 // "cv1 T1" is reference-compatible with "cv2 T2" if
5082 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5083 // "pointer to cv1 T1" via a standard conversion sequence.
5084
5085 // Check for standard conversions we can apply to pointers: derived-to-base
5086 // conversions, ObjC pointer conversions, and function pointer conversions.
5087 // (Qualification conversions are checked last.)
5088 if (UnqualT1 == UnqualT2) {
5089 // Nothing to do.
5090 } else if (isCompleteType(Loc, OrigT2) &&
5091 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5092 Conv |= ReferenceConversions::DerivedToBase;
5093 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5094 UnqualT2->isObjCObjectOrInterfaceType() &&
5095 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5096 Conv |= ReferenceConversions::ObjC;
5097 else if (UnqualT2->isFunctionType() &&
5098 IsFunctionConversion(UnqualT2, UnqualT1)) {
5099 Conv |= ReferenceConversions::Function;
5100 // No need to check qualifiers; function types don't have them.
5101 return Ref_Compatible;
5102 }
5103 bool ConvertedReferent = Conv != 0;
5104
5105 // We can have a qualification conversion. Compute whether the types are
5106 // similar at the same time.
5107 bool PreviousToQualsIncludeConst = true;
5108 bool TopLevel = true;
5109 do {
5110 if (T1 == T2)
5111 break;
5112
5113 // We will need a qualification conversion.
5114 Conv |= ReferenceConversions::Qualification;
5115
5116 // Track whether we performed a qualification conversion anywhere other
5117 // than the top level. This matters for ranking reference bindings in
5118 // overload resolution.
5119 if (!TopLevel)
5120 Conv |= ReferenceConversions::NestedQualification;
5121
5122 // MS compiler ignores __unaligned qualifier for references; do the same.
5123 T1 = withoutUnaligned(Context, T1);
5124 T2 = withoutUnaligned(Context, T2);
5125
5126 // If we find a qualifier mismatch, the types are not reference-compatible,
5127 // but are still be reference-related if they're similar.
5128 bool ObjCLifetimeConversion = false;
5129 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5130 PreviousToQualsIncludeConst,
5131 ObjCLifetimeConversion, getASTContext()))
5132 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5133 ? Ref_Related
5135
5136 // FIXME: Should we track this for any level other than the first?
5137 if (ObjCLifetimeConversion)
5138 Conv |= ReferenceConversions::ObjCLifetime;
5139
5140 TopLevel = false;
5141 } while (Context.UnwrapSimilarTypes(T1, T2));
5142
5143 // At this point, if the types are reference-related, we must either have the
5144 // same inner type (ignoring qualifiers), or must have already worked out how
5145 // to convert the referent.
5146 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5149}
5150
5151/// Look for a user-defined conversion to a value reference-compatible
5152/// with DeclType. Return true if something definite is found.
5153static bool
5155 QualType DeclType, SourceLocation DeclLoc,
5156 Expr *Init, QualType T2, bool AllowRvalues,
5157 bool AllowExplicit) {
5158 assert(T2->isRecordType() && "Can only find conversions of record types.");
5159 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5160 OverloadCandidateSet CandidateSet(
5162 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5163 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5164 NamedDecl *D = *I;
5166 if (isa<UsingShadowDecl>(D))
5167 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5168
5169 FunctionTemplateDecl *ConvTemplate
5170 = dyn_cast<FunctionTemplateDecl>(D);
5171 CXXConversionDecl *Conv;
5172 if (ConvTemplate)
5173 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5174 else
5175 Conv = cast<CXXConversionDecl>(D);
5176
5177 if (AllowRvalues) {
5178 // If we are initializing an rvalue reference, don't permit conversion
5179 // functions that return lvalues.
5180 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5181 const ReferenceType *RefType
5183 if (RefType && !RefType->getPointeeType()->isFunctionType())
5184 continue;
5185 }
5186
5187 if (!ConvTemplate &&
5189 DeclLoc,
5190 Conv->getConversionType()
5195 continue;
5196 } else {
5197 // If the conversion function doesn't return a reference type,
5198 // it can't be considered for this conversion. An rvalue reference
5199 // is only acceptable if its referencee is a function type.
5200
5201 const ReferenceType *RefType =
5203 if (!RefType ||
5204 (!RefType->isLValueReferenceType() &&
5205 !RefType->getPointeeType()->isFunctionType()))
5206 continue;
5207 }
5208
5209 if (ConvTemplate)
5211 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5212 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5213 else
5215 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5216 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5217 }
5218
5219 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5220
5222 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5223 case OR_Success:
5224
5225 assert(Best->HasFinalConversion);
5226
5227 // C++ [over.ics.ref]p1:
5228 //
5229 // [...] If the parameter binds directly to the result of
5230 // applying a conversion function to the argument
5231 // expression, the implicit conversion sequence is a
5232 // user-defined conversion sequence (13.3.3.1.2), with the
5233 // second standard conversion sequence either an identity
5234 // conversion or, if the conversion function returns an
5235 // entity of a type that is a derived class of the parameter
5236 // type, a derived-to-base Conversion.
5237 if (!Best->FinalConversion.DirectBinding)
5238 return false;
5239
5240 ICS.setUserDefined();
5241 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5242 ICS.UserDefined.After = Best->FinalConversion;
5243 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5244 ICS.UserDefined.ConversionFunction = Best->Function;
5245 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5246 ICS.UserDefined.EllipsisConversion = false;
5247 assert(ICS.UserDefined.After.ReferenceBinding &&
5249 "Expected a direct reference binding!");
5250 return true;
5251
5252 case OR_Ambiguous:
5253 ICS.setAmbiguous();
5254 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5255 Cand != CandidateSet.end(); ++Cand)
5256 if (Cand->Best)
5257 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5258 return true;
5259
5261 case OR_Deleted:
5262 // There was no suitable conversion, or we found a deleted
5263 // conversion; continue with other checks.
5264 return false;
5265 }
5266
5267 llvm_unreachable("Invalid OverloadResult!");
5268}
5269
5270/// Compute an implicit conversion sequence for reference
5271/// initialization.
5272static ImplicitConversionSequence
5274 SourceLocation DeclLoc,
5275 bool SuppressUserConversions,
5276 bool AllowExplicit) {
5277 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5278
5279 // Most paths end in a failed conversion.
5282
5283 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5284 QualType T2 = Init->getType();
5285
5286 // If the initializer is the address of an overloaded function, try
5287 // to resolve the overloaded function. If all goes well, T2 is the
5288 // type of the resulting function.
5289 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5292 false, Found))
5293 T2 = Fn->getType();
5294 }
5295
5296 // Compute some basic properties of the types and the initializer.
5297 bool isRValRef = DeclType->isRValueReferenceType();
5298 Expr::Classification InitCategory = Init->Classify(S.Context);
5299
5301 Sema::ReferenceCompareResult RefRelationship =
5302 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5303
5304 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5305 ICS.setStandard();
5307 // FIXME: A reference binding can be a function conversion too. We should
5308 // consider that when ordering reference-to-function bindings.
5309 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5311 : (RefConv & Sema::ReferenceConversions::ObjC)
5313 : ICK_Identity;
5315 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5316 // a reference binding that performs a non-top-level qualification
5317 // conversion as a qualification conversion, not as an identity conversion.
5318 ICS.Standard.Third = (RefConv &
5319 Sema::ReferenceConversions::NestedQualification)
5321 : ICK_Identity;
5322 ICS.Standard.setFromType(T2);
5323 ICS.Standard.setToType(0, T2);
5324 ICS.Standard.setToType(1, T1);
5325 ICS.Standard.setToType(2, T1);
5326 ICS.Standard.ReferenceBinding = true;
5327 ICS.Standard.DirectBinding = BindsDirectly;
5328 ICS.Standard.IsLvalueReference = !isRValRef;
5330 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5333 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5334 ICS.Standard.FromBracedInitList = false;
5335 ICS.Standard.CopyConstructor = nullptr;
5337 };
5338
5339 // C++0x [dcl.init.ref]p5:
5340 // A reference to type "cv1 T1" is initialized by an expression
5341 // of type "cv2 T2" as follows:
5342
5343 // -- If reference is an lvalue reference and the initializer expression
5344 if (!isRValRef) {
5345 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5346 // reference-compatible with "cv2 T2," or
5347 //
5348 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5349 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5350 // C++ [over.ics.ref]p1:
5351 // When a parameter of reference type binds directly (8.5.3)
5352 // to an argument expression, the implicit conversion sequence
5353 // is the identity conversion, unless the argument expression
5354 // has a type that is a derived class of the parameter type,
5355 // in which case the implicit conversion sequence is a
5356 // derived-to-base Conversion (13.3.3.1).
5357 SetAsReferenceBinding(/*BindsDirectly=*/true);
5358
5359 // Nothing more to do: the inaccessibility/ambiguity check for
5360 // derived-to-base conversions is suppressed when we're
5361 // computing the implicit conversion sequence (C++
5362 // [over.best.ics]p2).
5363 return ICS;
5364 }
5365
5366 // -- has a class type (i.e., T2 is a class type), where T1 is
5367 // not reference-related to T2, and can be implicitly
5368 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5369 // is reference-compatible with "cv3 T3" 92) (this
5370 // conversion is selected by enumerating the applicable
5371 // conversion functions (13.3.1.6) and choosing the best
5372 // one through overload resolution (13.3)),
5373 if (!SuppressUserConversions && T2->isRecordType() &&
5374 S.isCompleteType(DeclLoc, T2) &&
5375 RefRelationship == Sema::Ref_Incompatible) {
5376 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5377 Init, T2, /*AllowRvalues=*/false,
5378 AllowExplicit))
5379 return ICS;
5380 }
5381 }
5382
5383 // -- Otherwise, the reference shall be an lvalue reference to a
5384 // non-volatile const type (i.e., cv1 shall be const), or the reference
5385 // shall be an rvalue reference.
5386 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5387 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5389 return ICS;
5390 }
5391
5392 // -- If the initializer expression
5393 //
5394 // -- is an xvalue, class prvalue, array prvalue or function
5395 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5396 if (RefRelationship == Sema::Ref_Compatible &&
5397 (InitCategory.isXValue() ||
5398 (InitCategory.isPRValue() &&
5399 (T2->isRecordType() || T2->isArrayType())) ||
5400 (InitCategory.isLValue() && T2->isFunctionType()))) {
5401 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5402 // binding unless we're binding to a class prvalue.
5403 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5404 // allow the use of rvalue references in C++98/03 for the benefit of
5405 // standard library implementors; therefore, we need the xvalue check here.
5406 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5407 !(InitCategory.isPRValue() || T2->isRecordType()));
5408 return ICS;
5409 }
5410
5411 // -- has a class type (i.e., T2 is a class type), where T1 is not
5412 // reference-related to T2, and can be implicitly converted to
5413 // an xvalue, class prvalue, or function lvalue of type
5414 // "cv3 T3", where "cv1 T1" is reference-compatible with
5415 // "cv3 T3",
5416 //
5417 // then the reference is bound to the value of the initializer
5418 // expression in the first case and to the result of the conversion
5419 // in the second case (or, in either case, to an appropriate base
5420 // class subobject).
5421 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5422 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5423 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5424 Init, T2, /*AllowRvalues=*/true,
5425 AllowExplicit)) {
5426 // In the second case, if the reference is an rvalue reference
5427 // and the second standard conversion sequence of the
5428 // user-defined conversion sequence includes an lvalue-to-rvalue
5429 // conversion, the program is ill-formed.
5430 if (ICS.isUserDefined() && isRValRef &&
5433
5434 return ICS;
5435 }
5436
5437 // A temporary of function type cannot be created; don't even try.
5438 if (T1->isFunctionType())
5439 return ICS;
5440
5441 // -- Otherwise, a temporary of type "cv1 T1" is created and
5442 // initialized from the initializer expression using the
5443 // rules for a non-reference copy initialization (8.5). The
5444 // reference is then bound to the temporary. If T1 is
5445 // reference-related to T2, cv1 must be the same
5446 // cv-qualification as, or greater cv-qualification than,
5447 // cv2; otherwise, the program is ill-formed.
5448 if (RefRelationship == Sema::Ref_Related) {
5449 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5450 // we would be reference-compatible or reference-compatible with
5451 // added qualification. But that wasn't the case, so the reference
5452 // initialization fails.
5453 //
5454 // Note that we only want to check address spaces and cvr-qualifiers here.
5455 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5456 Qualifiers T1Quals = T1.getQualifiers();
5457 Qualifiers T2Quals = T2.getQualifiers();
5458 T1Quals.removeObjCGCAttr();
5459 T1Quals.removeObjCLifetime();
5460 T2Quals.removeObjCGCAttr();
5461 T2Quals.removeObjCLifetime();
5462 // MS compiler ignores __unaligned qualifier for references; do the same.
5463 T1Quals.removeUnaligned();
5464 T2Quals.removeUnaligned();
5465 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5466 return ICS;
5467 }
5468
5469 // If at least one of the types is a class type, the types are not
5470 // related, and we aren't allowed any user conversions, the
5471 // reference binding fails. This case is important for breaking
5472 // recursion, since TryImplicitConversion below will attempt to
5473 // create a temporary through the use of a copy constructor.
5474 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5475 (T1->isRecordType() || T2->isRecordType()))
5476 return ICS;
5477
5478 // If T1 is reference-related to T2 and the reference is an rvalue
5479 // reference, the initializer expression shall not be an lvalue.
5480 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5481 Init->Classify(S.Context).isLValue()) {
5483 return ICS;
5484 }
5485
5486 // C++ [over.ics.ref]p2:
5487 // When a parameter of reference type is not bound directly to
5488 // an argument expression, the conversion sequence is the one
5489 // required to convert the argument expression to the
5490 // underlying type of the reference according to
5491 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5492 // to copy-initializing a temporary of the underlying type with
5493 // the argument expression. Any difference in top-level
5494 // cv-qualification is subsumed by the initialization itself
5495 // and does not constitute a conversion.
5496 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5497 AllowedExplicit::None,
5498 /*InOverloadResolution=*/false,
5499 /*CStyle=*/false,
5500 /*AllowObjCWritebackConversion=*/false,
5501 /*AllowObjCConversionOnExplicit=*/false);
5502
5503 // Of course, that's still a reference binding.
5504 if (ICS.isStandard()) {
5505 ICS.Standard.ReferenceBinding = true;
5506 ICS.Standard.IsLvalueReference = !isRValRef;
5507 ICS.Standard.BindsToFunctionLvalue = false;
5508 ICS.Standard.BindsToRvalue = true;
5511 } else if (ICS.isUserDefined()) {
5512 const ReferenceType *LValRefType =
5515
5516 // C++ [over.ics.ref]p3:
5517 // Except for an implicit object parameter, for which see 13.3.1, a
5518 // standard conversion sequence cannot be formed if it requires [...]
5519 // binding an rvalue reference to an lvalue other than a function
5520 // lvalue.
5521 // Note that the function case is not possible here.
5522 if (isRValRef && LValRefType) {
5524 return ICS;
5525 }
5526
5528 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5530 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5534 }
5535
5536 return ICS;
5537}
5538
5539static ImplicitConversionSequence
5540TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5541 bool SuppressUserConversions,
5542 bool InOverloadResolution,
5543 bool AllowObjCWritebackConversion,
5544 bool AllowExplicit = false);
5545
5546/// TryListConversion - Try to copy-initialize a value of type ToType from the
5547/// initializer list From.
5548static ImplicitConversionSequence
5550 bool SuppressUserConversions,
5551 bool InOverloadResolution,
5552 bool AllowObjCWritebackConversion) {
5553 // C++11 [over.ics.list]p1:
5554 // When an argument is an initializer list, it is not an expression and
5555 // special rules apply for converting it to a parameter type.
5556
5558 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5559
5560 // We need a complete type for what follows. With one C++20 exception,
5561 // incomplete types can never be initialized from init lists.
5562 QualType InitTy = ToType;
5563 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5564 if (AT && S.getLangOpts().CPlusPlus20)
5565 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5566 // C++20 allows list initialization of an incomplete array type.
5567 InitTy = IAT->getElementType();
5568 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5569 return Result;
5570
5571 // C++20 [over.ics.list]/2:
5572 // If the initializer list is a designated-initializer-list, a conversion
5573 // is only possible if the parameter has an aggregate type
5574 //
5575 // FIXME: The exception for reference initialization here is not part of the
5576 // language rules, but follow other compilers in adding it as a tentative DR
5577 // resolution.
5578 bool IsDesignatedInit = From->hasDesignatedInit();
5579 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5580 IsDesignatedInit)
5581 return Result;
5582
5583 // Per DR1467 and DR2137:
5584 // If the parameter type is an aggregate class X and the initializer list
5585 // has a single element of type cv U, where U is X or a class derived from
5586 // X, the implicit conversion sequence is the one required to convert the
5587 // element to the parameter type.
5588 //
5589 // Otherwise, if the parameter type is a character array [... ]
5590 // and the initializer list has a single element that is an
5591 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5592 // implicit conversion sequence is the identity conversion.
5593 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5594 if (ToType->isRecordType() && ToType->isAggregateType()) {
5595 QualType InitType = From->getInit(0)->getType();
5596 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5597 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5598 return TryCopyInitialization(S, From->getInit(0), ToType,
5599 SuppressUserConversions,
5600 InOverloadResolution,
5601 AllowObjCWritebackConversion);
5602 }
5603
5604 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5605 InitializedEntity Entity =
5607 /*Consumed=*/false);
5608 if (S.CanPerformCopyInitialization(Entity, From)) {
5609 Result.setStandard();
5610 Result.Standard.setAsIdentityConversion();
5611 Result.Standard.setFromType(ToType);
5612 Result.Standard.setAllToTypes(ToType);
5613 return Result;
5614 }
5615 }
5616 }
5617
5618 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5619 // C++11 [over.ics.list]p2:
5620 // If the parameter type is std::initializer_list<X> or "array of X" and
5621 // all the elements can be implicitly converted to X, the implicit
5622 // conversion sequence is the worst conversion necessary to convert an
5623 // element of the list to X.
5624 //
5625 // C++14 [over.ics.list]p3:
5626 // Otherwise, if the parameter type is "array of N X", if the initializer
5627 // list has exactly N elements or if it has fewer than N elements and X is
5628 // default-constructible, and if all the elements of the initializer list
5629 // can be implicitly converted to X, the implicit conversion sequence is
5630 // the worst conversion necessary to convert an element of the list to X.
5631 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5632 unsigned e = From->getNumInits();
5635 QualType());
5636 QualType ContTy = ToType;
5637 bool IsUnbounded = false;
5638 if (AT) {
5639 InitTy = AT->getElementType();
5640 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5641 if (CT->getSize().ult(e)) {
5642 // Too many inits, fatally bad
5644 ToType);
5645 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5646 return Result;
5647 }
5648 if (CT->getSize().ugt(e)) {
5649 // Need an init from empty {}, is there one?
5650 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5651 From->getEndLoc());
5652 EmptyList.setType(S.Context.VoidTy);
5653 DfltElt = TryListConversion(
5654 S, &EmptyList, InitTy, SuppressUserConversions,
5655 InOverloadResolution, AllowObjCWritebackConversion);
5656 if (DfltElt.isBad()) {
5657 // No {} init, fatally bad
5659 ToType);
5660 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5661 return Result;
5662 }
5663 }
5664 } else {
5665 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5666 IsUnbounded = true;
5667 if (!e) {
5668 // Cannot convert to zero-sized.
5670 ToType);
5671 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5672 return Result;
5673 }
5674 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5675 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5677 }
5678 }
5679
5680 Result.setStandard();
5681 Result.Standard.setAsIdentityConversion();
5682 Result.Standard.setFromType(InitTy);
5683 Result.Standard.setAllToTypes(InitTy);
5684 for (unsigned i = 0; i < e; ++i) {
5685 Expr *Init = From->getInit(i);
5687 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5688 AllowObjCWritebackConversion);
5689
5690 // Keep the worse conversion seen so far.
5691 // FIXME: Sequences are not totally ordered, so 'worse' can be
5692 // ambiguous. CWG has been informed.
5694 Result) ==
5696 Result = ICS;
5697 // Bail as soon as we find something unconvertible.
5698 if (Result.isBad()) {
5699 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5700 return Result;
5701 }
5702 }
5703 }
5704
5705 // If we needed any implicit {} initialization, compare that now.
5706 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5707 // has been informed that this might not be the best thing.
5708 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5709 S, From->getEndLoc(), DfltElt, Result) ==
5711 Result = DfltElt;
5712 // Record the type being initialized so that we may compare sequences
5713 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5714 return Result;
5715 }
5716
5717 // C++14 [over.ics.list]p4:
5718 // C++11 [over.ics.list]p3:
5719 // Otherwise, if the parameter is a non-aggregate class X and overload
5720 // resolution chooses a single best constructor [...] the implicit
5721 // conversion sequence is a user-defined conversion sequence. If multiple
5722 // constructors are viable but none is better than the others, the
5723 // implicit conversion sequence is a user-defined conversion sequence.
5724 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5725 // This function can deal with initializer lists.
5726 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5727 AllowedExplicit::None,
5728 InOverloadResolution, /*CStyle=*/false,
5729 AllowObjCWritebackConversion,
5730 /*AllowObjCConversionOnExplicit=*/false);
5731 }
5732
5733 // C++14 [over.ics.list]p5:
5734 // C++11 [over.ics.list]p4:
5735 // Otherwise, if the parameter has an aggregate type which can be
5736 // initialized from the initializer list [...] the implicit conversion
5737 // sequence is a user-defined conversion sequence.
5738 if (ToType->isAggregateType()) {
5739 // Type is an aggregate, argument is an init list. At this point it comes
5740 // down to checking whether the initialization works.
5741 // FIXME: Find out whether this parameter is consumed or not.
5742 InitializedEntity Entity =
5744 /*Consumed=*/false);
5746 From)) {
5747 Result.setUserDefined();
5748 Result.UserDefined.Before.setAsIdentityConversion();
5749 // Initializer lists don't have a type.
5750 Result.UserDefined.Before.setFromType(QualType());
5751 Result.UserDefined.Before.setAllToTypes(QualType());
5752
5753 Result.UserDefined.After.setAsIdentityConversion();
5754 Result.UserDefined.After.setFromType(ToType);
5755 Result.UserDefined.After.setAllToTypes(ToType);
5756 Result.UserDefined.ConversionFunction = nullptr;
5757 }
5758 return Result;
5759 }
5760
5761 // C++14 [over.ics.list]p6:
5762 // C++11 [over.ics.list]p5:
5763 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5764 if (ToType->isReferenceType()) {
5765 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5766 // mention initializer lists in any way. So we go by what list-
5767 // initialization would do and try to extrapolate from that.
5768
5769 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5770
5771 // If the initializer list has a single element that is reference-related
5772 // to the parameter type, we initialize the reference from that.
5773 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5774 Expr *Init = From->getInit(0);
5775
5776 QualType T2 = Init->getType();
5777
5778 // If the initializer is the address of an overloaded function, try
5779 // to resolve the overloaded function. If all goes well, T2 is the
5780 // type of the resulting function.
5781 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5784 Init, ToType, false, Found))
5785 T2 = Fn->getType();
5786 }
5787
5788 // Compute some basic properties of the types and the initializer.
5789 Sema::ReferenceCompareResult RefRelationship =
5790 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5791
5792 if (RefRelationship >= Sema::Ref_Related) {
5793 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5794 SuppressUserConversions,
5795 /*AllowExplicit=*/false);
5796 }
5797 }
5798
5799 // Otherwise, we bind the reference to a temporary created from the
5800 // initializer list.
5801 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5802 InOverloadResolution,
5803 AllowObjCWritebackConversion);
5804 if (Result.isFailure())
5805 return Result;
5806 assert(!Result.isEllipsis() &&
5807 "Sub-initialization cannot result in ellipsis conversion.");
5808
5809 // Can we even bind to a temporary?
5810 if (ToType->isRValueReferenceType() ||
5811 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5812 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5813 Result.UserDefined.After;
5814 SCS.ReferenceBinding = true;
5816 SCS.BindsToRvalue = true;
5817 SCS.BindsToFunctionLvalue = false;
5820 SCS.FromBracedInitList = false;
5821
5822 } else
5824 From, ToType);
5825 return Result;
5826 }
5827
5828 // C++14 [over.ics.list]p7:
5829 // C++11 [over.ics.list]p6:
5830 // Otherwise, if the parameter type is not a class:
5831 if (!ToType->isRecordType()) {
5832 // - if the initializer list has one element that is not itself an
5833 // initializer list, the implicit conversion sequence is the one
5834 // required to convert the element to the parameter type.
5835 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5836 // single integer.
5837 unsigned NumInits = From->getNumInits();
5838 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5839 !isa<EmbedExpr>(From->getInit(0))) {
5840 Result = TryCopyInitialization(
5841 S, From->getInit(0), ToType, SuppressUserConversions,
5842 InOverloadResolution, AllowObjCWritebackConversion);
5843 if (Result.isStandard())
5844 Result.Standard.FromBracedInitList = true;
5845 }
5846 // - if the initializer list has no elements, the implicit conversion
5847 // sequence is the identity conversion.
5848 else if (NumInits == 0) {
5849 Result.setStandard();
5850 Result.Standard.setAsIdentityConversion();
5851 Result.Standard.setFromType(ToType);
5852 Result.Standard.setAllToTypes(ToType);
5853 }
5854 return Result;
5855 }
5856
5857 // C++14 [over.ics.list]p8:
5858 // C++11 [over.ics.list]p7:
5859 // In all cases other than those enumerated above, no conversion is possible
5860 return Result;
5861}
5862
5863/// TryCopyInitialization - Try to copy-initialize a value of type
5864/// ToType from the expression From. Return the implicit conversion
5865/// sequence required to pass this argument, which may be a bad
5866/// conversion sequence (meaning that the argument cannot be passed to
5867/// a parameter of this type). If @p SuppressUserConversions, then we
5868/// do not permit any user-defined conversion sequences.
5869static ImplicitConversionSequence
5871 bool SuppressUserConversions,
5872 bool InOverloadResolution,
5873 bool AllowObjCWritebackConversion,
5874 bool AllowExplicit) {
5875 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5876 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5877 InOverloadResolution,AllowObjCWritebackConversion);
5878
5879 if (ToType->isReferenceType())
5880 return TryReferenceInit(S, From, ToType,
5881 /*FIXME:*/ From->getBeginLoc(),
5882 SuppressUserConversions, AllowExplicit);
5883
5884 return TryImplicitConversion(S, From, ToType,
5885 SuppressUserConversions,
5886 AllowedExplicit::None,
5887 InOverloadResolution,
5888 /*CStyle=*/false,
5889 AllowObjCWritebackConversion,
5890 /*AllowObjCConversionOnExplicit=*/false);
5891}
5892
5893static bool TryCopyInitialization(const CanQualType FromQTy,
5894 const CanQualType ToQTy,
5895 Sema &S,
5896 SourceLocation Loc,
5897 ExprValueKind FromVK) {
5898 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5900 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5901
5902 return !ICS.isBad();
5903}
5904
5905/// TryObjectArgumentInitialization - Try to initialize the object
5906/// parameter of the given member function (@c Method) from the
5907/// expression @p From.
5909 Sema &S, SourceLocation Loc, QualType FromType,
5910 Expr::Classification FromClassification, CXXMethodDecl *Method,
5911 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5912 QualType ExplicitParameterType = QualType(),
5913 bool SuppressUserConversion = false) {
5914
5915 // We need to have an object of class type.
5916 if (const auto *PT = FromType->getAs<PointerType>()) {
5917 FromType = PT->getPointeeType();
5918
5919 // When we had a pointer, it's implicitly dereferenced, so we
5920 // better have an lvalue.
5921 assert(FromClassification.isLValue());
5922 }
5923
5924 auto ValueKindFromClassification = [](Expr::Classification C) {
5925 if (C.isPRValue())
5926 return clang::VK_PRValue;
5927 if (C.isXValue())
5928 return VK_XValue;
5929 return clang::VK_LValue;
5930 };
5931
5932 if (Method->isExplicitObjectMemberFunction()) {
5933 if (ExplicitParameterType.isNull())
5934 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5935 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5936 ValueKindFromClassification(FromClassification));
5938 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5939 /*InOverloadResolution=*/true, false);
5940 if (ICS.isBad())
5941 ICS.Bad.FromExpr = nullptr;
5942 return ICS;
5943 }
5944
5945 assert(FromType->isRecordType());
5946
5947 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
5948 // C++98 [class.dtor]p2:
5949 // A destructor can be invoked for a const, volatile or const volatile
5950 // object.
5951 // C++98 [over.match.funcs]p4:
5952 // For static member functions, the implicit object parameter is considered
5953 // to match any object (since if the function is selected, the object is
5954 // discarded).
5955 Qualifiers Quals = Method->getMethodQualifiers();
5956 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5957 Quals.addConst();
5958 Quals.addVolatile();
5959 }
5960
5961 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5962
5963 // Set up the conversion sequence as a "bad" conversion, to allow us
5964 // to exit early.
5966
5967 // C++0x [over.match.funcs]p4:
5968 // For non-static member functions, the type of the implicit object
5969 // parameter is
5970 //
5971 // - "lvalue reference to cv X" for functions declared without a
5972 // ref-qualifier or with the & ref-qualifier
5973 // - "rvalue reference to cv X" for functions declared with the &&
5974 // ref-qualifier
5975 //
5976 // where X is the class of which the function is a member and cv is the
5977 // cv-qualification on the member function declaration.
5978 //
5979 // However, when finding an implicit conversion sequence for the argument, we
5980 // are not allowed to perform user-defined conversions
5981 // (C++ [over.match.funcs]p5). We perform a simplified version of
5982 // reference binding here, that allows class rvalues to bind to
5983 // non-constant references.
5984
5985 // First check the qualifiers.
5986 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5987 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5988 if (ImplicitParamType.getCVRQualifiers() !=
5989 FromTypeCanon.getLocalCVRQualifiers() &&
5990 !ImplicitParamType.isAtLeastAsQualifiedAs(
5991 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5993 FromType, ImplicitParamType);
5994 return ICS;
5995 }
5996
5997 if (FromTypeCanon.hasAddressSpace()) {
5998 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5999 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6000 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6001 S.getASTContext())) {
6003 FromType, ImplicitParamType);
6004 return ICS;
6005 }
6006 }
6007
6008 // Check that we have either the same type or a derived type. It
6009 // affects the conversion rank.
6010 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6011 ImplicitConversionKind SecondKind;
6012 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6013 SecondKind = ICK_Identity;
6014 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6015 SecondKind = ICK_Derived_To_Base;
6016 } else if (!Method->isExplicitObjectMemberFunction()) {
6018 FromType, ImplicitParamType);
6019 return ICS;
6020 }
6021
6022 // Check the ref-qualifier.
6023 switch (Method->getRefQualifier()) {
6024 case RQ_None:
6025 // Do nothing; we don't care about lvalueness or rvalueness.
6026 break;
6027
6028 case RQ_LValue:
6029 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6030 // non-const lvalue reference cannot bind to an rvalue
6032 ImplicitParamType);
6033 return ICS;
6034 }
6035 break;
6036
6037 case RQ_RValue:
6038 if (!FromClassification.isRValue()) {
6039 // rvalue reference cannot bind to an lvalue
6041 ImplicitParamType);
6042 return ICS;
6043 }
6044 break;
6045 }
6046
6047 // Success. Mark this as a reference binding.
6048 ICS.setStandard();
6050 ICS.Standard.Second = SecondKind;
6051 ICS.Standard.setFromType(FromType);
6052 ICS.Standard.setAllToTypes(ImplicitParamType);
6053 ICS.Standard.ReferenceBinding = true;
6054 ICS.Standard.DirectBinding = true;
6055 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6056 ICS.Standard.BindsToFunctionLvalue = false;
6057 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6058 ICS.Standard.FromBracedInitList = false;
6060 = (Method->getRefQualifier() == RQ_None);
6061 return ICS;
6062}
6063
6064/// PerformObjectArgumentInitialization - Perform initialization of
6065/// the implicit object parameter for the given Method with the given
6066/// expression.
6068 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6070 QualType FromRecordType, DestType;
6071 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6072
6073 Expr::Classification FromClassification;
6074 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6075 FromRecordType = PT->getPointeeType();
6076 DestType = Method->getThisType();
6077 FromClassification = Expr::Classification::makeSimpleLValue();
6078 } else {
6079 FromRecordType = From->getType();
6080 DestType = ImplicitParamRecordType;
6081 FromClassification = From->Classify(Context);
6082
6083 // CWG2813 [expr.call]p6:
6084 // If the function is an implicit object member function, the object
6085 // expression of the class member access shall be a glvalue [...]
6086 if (From->isPRValue()) {
6087 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6088 Method->getRefQualifier() !=
6090 }
6091 }
6092
6093 // Note that we always use the true parent context when performing
6094 // the actual argument initialization.
6096 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6097 Method->getParent());
6098 if (ICS.isBad()) {
6099 switch (ICS.Bad.Kind) {
6101 Qualifiers FromQs = FromRecordType.getQualifiers();
6102 Qualifiers ToQs = DestType.getQualifiers();
6103 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6104 if (CVR) {
6105 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6106 << Method->getDeclName() << FromRecordType << (CVR - 1)
6107 << From->getSourceRange();
6108 Diag(Method->getLocation(), diag::note_previous_decl)
6109 << Method->getDeclName();
6110 return ExprError();
6111 }
6112 break;
6113 }
6114
6117 bool IsRValueQualified =
6118 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6119 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6120 << Method->getDeclName() << FromClassification.isRValue()
6121 << IsRValueQualified;
6122 Diag(Method->getLocation(), diag::note_previous_decl)
6123 << Method->getDeclName();
6124 return ExprError();
6125 }
6126
6129 break;
6130
6133 llvm_unreachable("Lists are not objects");
6134 }
6135
6136 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6137 << ImplicitParamRecordType << FromRecordType
6138 << From->getSourceRange();
6139 }
6140
6141 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6142 ExprResult FromRes =
6143 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6144 if (FromRes.isInvalid())
6145 return ExprError();
6146 From = FromRes.get();
6147 }
6148
6149 if (!Context.hasSameType(From->getType(), DestType)) {
6150 CastKind CK;
6151 QualType PteeTy = DestType->getPointeeType();
6152 LangAS DestAS =
6153 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6154 if (FromRecordType.getAddressSpace() != DestAS)
6155 CK = CK_AddressSpaceConversion;
6156 else
6157 CK = CK_NoOp;
6158 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6159 }
6160 return From;
6161}
6162
6163/// TryContextuallyConvertToBool - Attempt to contextually convert the
6164/// expression From to bool (C++0x [conv]p3).
6167 // C++ [dcl.init]/17.8:
6168 // - Otherwise, if the initialization is direct-initialization, the source
6169 // type is std::nullptr_t, and the destination type is bool, the initial
6170 // value of the object being initialized is false.
6171 if (From->getType()->isNullPtrType())
6173 S.Context.BoolTy,
6174 From->isGLValue());
6175
6176 // All other direct-initialization of bool is equivalent to an implicit
6177 // conversion to bool in which explicit conversions are permitted.
6178 return TryImplicitConversion(S, From, S.Context.BoolTy,
6179 /*SuppressUserConversions=*/false,
6180 AllowedExplicit::Conversions,
6181 /*InOverloadResolution=*/false,
6182 /*CStyle=*/false,
6183 /*AllowObjCWritebackConversion=*/false,
6184 /*AllowObjCConversionOnExplicit=*/false);
6185}
6186
6188 if (checkPlaceholderForOverload(*this, From))
6189 return ExprError();
6190
6192 if (!ICS.isBad())
6193 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6195
6197 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6198 << From->getType() << From->getSourceRange();
6199 return ExprError();
6200}
6201
6202/// Check that the specified conversion is permitted in a converted constant
6203/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6204/// is acceptable.
6207 // Since we know that the target type is an integral or unscoped enumeration
6208 // type, most conversion kinds are impossible. All possible First and Third
6209 // conversions are fine.
6210 switch (SCS.Second) {
6211 case ICK_Identity:
6213 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6215 return true;
6216
6218 // Conversion from an integral or unscoped enumeration type to bool is
6219 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6220 // conversion, so we allow it in a converted constant expression.
6221 //
6222 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6223 // a lot of popular code. We should at least add a warning for this
6224 // (non-conforming) extension.
6226 SCS.getToType(2)->isBooleanType();
6227
6229 case ICK_Pointer_Member:
6230 // C++1z: null pointer conversions and null member pointer conversions are
6231 // only permitted if the source type is std::nullptr_t.
6232 return SCS.getFromType()->isNullPtrType();
6233
6245 case ICK_Vector_Splat:
6246 case ICK_Complex_Real:
6255 return false;
6256
6261 llvm_unreachable("found a first conversion kind in Second");
6262
6264 case ICK_Qualification:
6265 llvm_unreachable("found a third conversion kind in Second");
6266
6268 break;
6269 }
6270
6271 llvm_unreachable("unknown conversion kind");
6272}
6273
6274/// BuildConvertedConstantExpression - Check that the expression From is a
6275/// converted constant expression of type T, perform the conversion but
6276/// does not evaluate the expression
6278 QualType T, CCEKind CCE,
6279 NamedDecl *Dest,
6280 APValue &PreNarrowingValue) {
6281 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6283 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6284 "converted constant expression outside C++11 or TTP matching");
6285
6286 if (checkPlaceholderForOverload(S, From))
6287 return ExprError();
6288
6289 // C++1z [expr.const]p3:
6290 // A converted constant expression of type T is an expression,
6291 // implicitly converted to type T, where the converted
6292 // expression is a constant expression and the implicit conversion
6293 // sequence contains only [... list of conversions ...].
6295 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6297 : TryCopyInitialization(S, From, T,
6298 /*SuppressUserConversions=*/false,
6299 /*InOverloadResolution=*/false,
6300 /*AllowObjCWritebackConversion=*/false,
6301 /*AllowExplicit=*/false);
6302 StandardConversionSequence *SCS = nullptr;
6303 switch (ICS.getKind()) {
6305 SCS = &ICS.Standard;
6306 break;
6308 if (T->isRecordType())
6309 SCS = &ICS.UserDefined.Before;
6310 else
6311 SCS = &ICS.UserDefined.After;
6312 break;
6316 return S.Diag(From->getBeginLoc(),
6317 diag::err_typecheck_converted_constant_expression)
6318 << From->getType() << From->getSourceRange() << T;
6319 return ExprError();
6320
6323 llvm_unreachable("bad conversion in converted constant expression");
6324 }
6325
6326 // Check that we would only use permitted conversions.
6327 if (!CheckConvertedConstantConversions(S, *SCS)) {
6328 return S.Diag(From->getBeginLoc(),
6329 diag::err_typecheck_converted_constant_expression_disallowed)
6330 << From->getType() << From->getSourceRange() << T;
6331 }
6332 // [...] and where the reference binding (if any) binds directly.
6333 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6334 return S.Diag(From->getBeginLoc(),
6335 diag::err_typecheck_converted_constant_expression_indirect)
6336 << From->getType() << From->getSourceRange() << T;
6337 }
6338 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6339 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6340 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6341 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6342 // case explicitly.
6343 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6344 return S.Diag(From->getBeginLoc(),
6345 diag::err_reference_bind_to_bitfield_in_cce)
6346 << From->getSourceRange();
6347 }
6348
6349 // Usually we can simply apply the ImplicitConversionSequence we formed
6350 // earlier, but that's not guaranteed to work when initializing an object of
6351 // class type.
6352 ExprResult Result;
6353 bool IsTemplateArgument =
6355 if (T->isRecordType()) {
6356 assert(IsTemplateArgument &&
6357 "unexpected class type converted constant expr");
6358 Result = S.PerformCopyInitialization(
6361 SourceLocation(), From);
6362 } else {
6363 Result =
6365 }
6366 if (Result.isInvalid())
6367 return Result;
6368
6369 // C++2a [intro.execution]p5:
6370 // A full-expression is [...] a constant-expression [...]
6371 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6372 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6373 IsTemplateArgument);
6374 if (Result.isInvalid())
6375 return Result;
6376
6377 // Check for a narrowing implicit conversion.
6378 bool ReturnPreNarrowingValue = false;
6379 QualType PreNarrowingType;
6380 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6381 PreNarrowingType)) {
6383 // Implicit conversion to a narrower type, and the value is not a constant
6384 // expression. We'll diagnose this in a moment.
6385 case NK_Not_Narrowing:
6386 break;
6387
6389 if (CCE == CCEKind::ArrayBound &&
6390 PreNarrowingType->isIntegralOrEnumerationType() &&
6391 PreNarrowingValue.isInt()) {
6392 // Don't diagnose array bound narrowing here; we produce more precise
6393 // errors by allowing the un-narrowed value through.
6394 ReturnPreNarrowingValue = true;
6395 break;
6396 }
6397 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6398 << CCE << /*Constant*/ 1
6399 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6400 break;
6401
6403 // Implicit conversion to a narrower type, but the expression is
6404 // value-dependent so we can't tell whether it's actually narrowing.
6405 // For matching the parameters of a TTP, the conversion is ill-formed
6406 // if it may narrow.
6407 if (CCE != CCEKind::TempArgStrict)
6408 break;
6409 [[fallthrough]];
6410 case NK_Type_Narrowing:
6411 // FIXME: It would be better to diagnose that the expression is not a
6412 // constant expression.
6413 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6414 << CCE << /*Constant*/ 0 << From->getType() << T;
6415 break;
6416 }
6417 if (!ReturnPreNarrowingValue)
6418 PreNarrowingValue = {};
6419
6420 return Result;
6421}
6422
6423/// CheckConvertedConstantExpression - Check that the expression From is a
6424/// converted constant expression of type T, perform the conversion and produce
6425/// the converted expression, per C++11 [expr.const]p3.
6428 CCEKind CCE, bool RequireInt,
6429 NamedDecl *Dest) {
6430
6431 APValue PreNarrowingValue;
6432 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6433 PreNarrowingValue);
6434 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6435 Value = APValue();
6436 return Result;
6437 }
6438 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6439 RequireInt, PreNarrowingValue);
6440}
6441
6443 CCEKind CCE,
6444 NamedDecl *Dest) {
6445 APValue PreNarrowingValue;
6446 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6447 PreNarrowingValue);
6448}
6449
6451 APValue &Value, CCEKind CCE,
6452 NamedDecl *Dest) {
6453 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6454 Dest);
6455}
6456
6458 llvm::APSInt &Value,
6459 CCEKind CCE) {
6460 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6461
6462 APValue V;
6463 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6464 /*Dest=*/nullptr);
6465 if (!R.isInvalid() && !R.get()->isValueDependent())
6466 Value = V.getInt();
6467 return R;
6468}
6469
6472 CCEKind CCE, bool RequireInt,
6473 const APValue &PreNarrowingValue) {
6474
6475 ExprResult Result = E;
6476 // Check the expression is a constant expression.
6478 Expr::EvalResult Eval;
6479 Eval.Diag = &Notes;
6480
6481 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6482
6483 ConstantExprKind Kind;
6484 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6485 Kind = ConstantExprKind::ClassTemplateArgument;
6486 else if (CCE == CCEKind::TemplateArg)
6487 Kind = ConstantExprKind::NonClassTemplateArgument;
6488 else
6489 Kind = ConstantExprKind::Normal;
6490
6491 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6492 (RequireInt && !Eval.Val.isInt())) {
6493 // The expression can't be folded, so we can't keep it at this position in
6494 // the AST.
6495 Result = ExprError();
6496 } else {
6497 Value = Eval.Val;
6498
6499 if (Notes.empty()) {
6500 // It's a constant expression.
6501 Expr *E = Result.get();
6502 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6503 // We expect a ConstantExpr to have a value associated with it
6504 // by this point.
6505 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6506 "ConstantExpr has no value associated with it");
6507 (void)CE;
6508 } else {
6510 }
6511 if (!PreNarrowingValue.isAbsent())
6512 Value = std::move(PreNarrowingValue);
6513 return E;
6514 }
6515 }
6516
6517 // It's not a constant expression. Produce an appropriate diagnostic.
6518 if (Notes.size() == 1 &&
6519 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6520 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6521 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6522 diag::note_constexpr_invalid_template_arg) {
6523 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6524 for (unsigned I = 0; I < Notes.size(); ++I)
6525 Diag(Notes[I].first, Notes[I].second);
6526 } else {
6527 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6528 << CCE << E->getSourceRange();
6529 for (unsigned I = 0; I < Notes.size(); ++I)
6530 Diag(Notes[I].first, Notes[I].second);
6531 }
6532 return ExprError();
6533}
6534
6535/// dropPointerConversions - If the given standard conversion sequence
6536/// involves any pointer conversions, remove them. This may change
6537/// the result type of the conversion sequence.
6539 if (SCS.Second == ICK_Pointer_Conversion) {
6540 SCS.Second = ICK_Identity;
6541 SCS.Dimension = ICK_Identity;
6542 SCS.Third = ICK_Identity;
6543 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6544 }
6545}
6546
6547/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6548/// convert the expression From to an Objective-C pointer type.
6549static ImplicitConversionSequence
6551 // Do an implicit conversion to 'id'.
6554 = TryImplicitConversion(S, From, Ty,
6555 // FIXME: Are these flags correct?
6556 /*SuppressUserConversions=*/false,
6557 AllowedExplicit::Conversions,
6558 /*InOverloadResolution=*/false,
6559 /*CStyle=*/false,
6560 /*AllowObjCWritebackConversion=*/false,
6561 /*AllowObjCConversionOnExplicit=*/true);
6562
6563 // Strip off any final conversions to 'id'.
6564 switch (ICS.getKind()) {
6569 break;
6570
6573 break;
6574
6577 break;
6578 }
6579
6580 return ICS;
6581}
6582
6584 if (checkPlaceholderForOverload(*this, From))
6585 return ExprError();
6586
6587 QualType Ty = Context.getObjCIdType();
6590 if (!ICS.isBad())
6591 return PerformImplicitConversion(From, Ty, ICS,
6593 return ExprResult();
6594}
6595
6596static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6597 const Expr *Base = nullptr;
6598 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6599 "expected a member expression");
6600
6601 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6602 M && !M->isImplicitAccess())
6603 Base = M->getBase();
6604 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6605 M && !M->isImplicitAccess())
6606 Base = M->getBase();
6607
6608 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6609
6610 if (T->isPointerType())
6611 T = T->getPointeeType();
6612
6613 return T;
6614}
6615
6617 const FunctionDecl *Fun) {
6618 QualType ObjType = Obj->getType();
6619 if (ObjType->isPointerType()) {
6620 ObjType = ObjType->getPointeeType();
6621 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6623 /*CanOverflow=*/false, FPOptionsOverride());
6624 }
6625 return Obj;
6626}
6627
6635
6637 Expr *Object, MultiExprArg &Args,
6638 SmallVectorImpl<Expr *> &NewArgs) {
6639 assert(Method->isExplicitObjectMemberFunction() &&
6640 "Method is not an explicit member function");
6641 assert(NewArgs.empty() && "NewArgs should be empty");
6642
6643 NewArgs.reserve(Args.size() + 1);
6644 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6645 NewArgs.push_back(This);
6646 NewArgs.append(Args.begin(), Args.end());
6647 Args = NewArgs;
6649 Method, Object->getBeginLoc());
6650}
6651
6652/// Determine whether the provided type is an integral type, or an enumeration
6653/// type of a permitted flavor.
6655 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6656 : T->isIntegralOrUnscopedEnumerationType();
6657}
6658
6659static ExprResult
6662 QualType T, UnresolvedSetImpl &ViableConversions) {
6663
6664 if (Converter.Suppress)
6665 return ExprError();
6666
6667 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6668 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6669 CXXConversionDecl *Conv =
6670 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6672 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6673 }
6674 return From;
6675}
6676
6677static bool
6680 QualType T, bool HadMultipleCandidates,
6681 UnresolvedSetImpl &ExplicitConversions) {
6682 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6683 DeclAccessPair Found = ExplicitConversions[0];
6684 CXXConversionDecl *Conversion =
6685 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6686
6687 // The user probably meant to invoke the given explicit
6688 // conversion; use it.
6689 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6690 std::string TypeStr;
6691 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6692
6693 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6695 "static_cast<" + TypeStr + ">(")
6697 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6698 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6699
6700 // If we aren't in a SFINAE context, build a call to the
6701 // explicit conversion function.
6702 if (SemaRef.isSFINAEContext())
6703 return true;
6704
6705 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6706 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6707 HadMultipleCandidates);
6708 if (Result.isInvalid())
6709 return true;
6710
6711 // Replace the conversion with a RecoveryExpr, so we don't try to
6712 // instantiate it later, but can further diagnose here.
6713 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6714 From, Result.get()->getType());
6715 if (Result.isInvalid())
6716 return true;
6717 From = Result.get();
6718 }
6719 return false;
6720}
6721
6722static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6724 QualType T, bool HadMultipleCandidates,
6726 CXXConversionDecl *Conversion =
6727 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6728 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6729
6730 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6731 if (!Converter.SuppressConversion) {
6732 if (SemaRef.isSFINAEContext())
6733 return true;
6734
6735 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6736 << From->getSourceRange();
6737 }
6738
6739 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6740 HadMultipleCandidates);
6741 if (Result.isInvalid())
6742 return true;
6743 // Record usage of conversion in an implicit cast.
6744 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6745 CK_UserDefinedConversion, Result.get(),
6746 nullptr, Result.get()->getValueKind(),
6747 SemaRef.CurFPFeatureOverrides());
6748 return false;
6749}
6750
6752 Sema &SemaRef, SourceLocation Loc, Expr *From,
6754 if (!Converter.match(From->getType()) && !Converter.Suppress)
6755 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6756 << From->getSourceRange();
6757
6758 return SemaRef.DefaultLvalueConversion(From);
6759}
6760
6761static void
6763 UnresolvedSetImpl &ViableConversions,
6764 OverloadCandidateSet &CandidateSet) {
6765 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6766 NamedDecl *D = FoundDecl.getDecl();
6767 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6768 if (isa<UsingShadowDecl>(D))
6769 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6770
6771 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6773 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6774 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6775 continue;
6776 }
6778 SemaRef.AddConversionCandidate(
6779 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6780 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6781 }
6782}
6783
6784/// Attempt to convert the given expression to a type which is accepted
6785/// by the given converter.
6786///
6787/// This routine will attempt to convert an expression of class type to a
6788/// type accepted by the specified converter. In C++11 and before, the class
6789/// must have a single non-explicit conversion function converting to a matching
6790/// type. In C++1y, there can be multiple such conversion functions, but only
6791/// one target type.
6792///
6793/// \param Loc The source location of the construct that requires the
6794/// conversion.
6795///
6796/// \param From The expression we're converting from.
6797///
6798/// \param Converter Used to control and diagnose the conversion process.
6799///
6800/// \returns The expression, converted to an integral or enumeration type if
6801/// successful.
6803 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6804 // We can't perform any more checking for type-dependent expressions.
6805 if (From->isTypeDependent())
6806 return From;
6807
6808 // Process placeholders immediately.
6809 if (From->hasPlaceholderType()) {
6810 ExprResult result = CheckPlaceholderExpr(From);
6811 if (result.isInvalid())
6812 return result;
6813 From = result.get();
6814 }
6815
6816 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6817 ExprResult Converted = DefaultLvalueConversion(From);
6818 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6819 // If the expression already has a matching type, we're golden.
6820 if (Converter.match(T))
6821 return Converted;
6822
6823 // FIXME: Check for missing '()' if T is a function type?
6824
6825 // We can only perform contextual implicit conversions on objects of class
6826 // type.
6827 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6828 if (!RecordTy || !getLangOpts().CPlusPlus) {
6829 if (!Converter.Suppress)
6830 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6831 return From;
6832 }
6833
6834 // We must have a complete class type.
6835 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6836 ContextualImplicitConverter &Converter;
6837 Expr *From;
6838
6839 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6840 : Converter(Converter), From(From) {}
6841
6842 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6843 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6844 }
6845 } IncompleteDiagnoser(Converter, From);
6846
6847 if (Converter.Suppress ? !isCompleteType(Loc, T)
6848 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6849 return From;
6850
6851 // Look for a conversion to an integral or enumeration type.
6853 ViableConversions; // These are *potentially* viable in C++1y.
6854 UnresolvedSet<4> ExplicitConversions;
6855 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getOriginalDecl())
6856 ->getDefinitionOrSelf()
6857 ->getVisibleConversionFunctions();
6858
6859 bool HadMultipleCandidates =
6860 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6861
6862 // To check that there is only one target type, in C++1y:
6863 QualType ToType;
6864 bool HasUniqueTargetType = true;
6865
6866 // Collect explicit or viable (potentially in C++1y) conversions.
6867 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6868 NamedDecl *D = (*I)->getUnderlyingDecl();
6869 CXXConversionDecl *Conversion;
6870 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6871 if (ConvTemplate) {
6873 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6874 else
6875 continue; // C++11 does not consider conversion operator templates(?).
6876 } else
6877 Conversion = cast<CXXConversionDecl>(D);
6878
6879 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6880 "Conversion operator templates are considered potentially "
6881 "viable in C++1y");
6882
6883 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6884 if (Converter.match(CurToType) || ConvTemplate) {
6885
6886 if (Conversion->isExplicit()) {
6887 // FIXME: For C++1y, do we need this restriction?
6888 // cf. diagnoseNoViableConversion()
6889 if (!ConvTemplate)
6890 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6891 } else {
6892 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6893 if (ToType.isNull())
6894 ToType = CurToType.getUnqualifiedType();
6895 else if (HasUniqueTargetType &&
6896 (CurToType.getUnqualifiedType() != ToType))
6897 HasUniqueTargetType = false;
6898 }
6899 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6900 }
6901 }
6902 }
6903
6904 if (getLangOpts().CPlusPlus14) {
6905 // C++1y [conv]p6:
6906 // ... An expression e of class type E appearing in such a context
6907 // is said to be contextually implicitly converted to a specified
6908 // type T and is well-formed if and only if e can be implicitly
6909 // converted to a type T that is determined as follows: E is searched
6910 // for conversion functions whose return type is cv T or reference to
6911 // cv T such that T is allowed by the context. There shall be
6912 // exactly one such T.
6913
6914 // If no unique T is found:
6915 if (ToType.isNull()) {
6916 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6917 HadMultipleCandidates,
6918 ExplicitConversions))
6919 return ExprError();
6920 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6921 }
6922
6923 // If more than one unique Ts are found:
6924 if (!HasUniqueTargetType)
6925 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6926 ViableConversions);
6927
6928 // If one unique T is found:
6929 // First, build a candidate set from the previously recorded
6930 // potentially viable conversions.
6932 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6933 CandidateSet);
6934
6935 // Then, perform overload resolution over the candidate set.
6937 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6938 case OR_Success: {
6939 // Apply this conversion.
6941 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6942 if (recordConversion(*this, Loc, From, Converter, T,
6943 HadMultipleCandidates, Found))
6944 return ExprError();
6945 break;
6946 }
6947 case OR_Ambiguous:
6948 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6949 ViableConversions);
6951 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6952 HadMultipleCandidates,
6953 ExplicitConversions))
6954 return ExprError();
6955 [[fallthrough]];
6956 case OR_Deleted:
6957 // We'll complain below about a non-integral condition type.
6958 break;
6959 }
6960 } else {
6961 switch (ViableConversions.size()) {
6962 case 0: {
6963 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6964 HadMultipleCandidates,
6965 ExplicitConversions))
6966 return ExprError();
6967
6968 // We'll complain below about a non-integral condition type.
6969 break;
6970 }
6971 case 1: {
6972 // Apply this conversion.
6973 DeclAccessPair Found = ViableConversions[0];
6974 if (recordConversion(*this, Loc, From, Converter, T,
6975 HadMultipleCandidates, Found))
6976 return ExprError();
6977 break;
6978 }
6979 default:
6980 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6981 ViableConversions);
6982 }
6983 }
6984
6985 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6986}
6987
6988/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6989/// an acceptable non-member overloaded operator for a call whose
6990/// arguments have types T1 (and, if non-empty, T2). This routine
6991/// implements the check in C++ [over.match.oper]p3b2 concerning
6992/// enumeration types.
6994 FunctionDecl *Fn,
6995 ArrayRef<Expr *> Args) {
6996 QualType T1 = Args[0]->getType();
6997 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6998
6999 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7000 return true;
7001
7002 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7003 return true;
7004
7005 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7006 if (Proto->getNumParams() < 1)
7007 return false;
7008
7009 if (T1->isEnumeralType()) {
7010 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7011 if (Context.hasSameUnqualifiedType(T1, ArgType))
7012 return true;
7013 }
7014
7015 if (Proto->getNumParams() < 2)
7016 return false;
7017
7018 if (!T2.isNull() && T2->isEnumeralType()) {
7019 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7020 if (Context.hasSameUnqualifiedType(T2, ArgType))
7021 return true;
7022 }
7023
7024 return false;
7025}
7026
7029 return false;
7030
7031 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7032 return FD->isTargetMultiVersion();
7033
7034 if (!FD->isMultiVersion())
7035 return false;
7036
7037 // Among multiple target versions consider either the default,
7038 // or the first non-default in the absence of default version.
7039 unsigned SeenAt = 0;
7040 unsigned I = 0;
7041 bool HasDefault = false;
7043 FD, [&](const FunctionDecl *CurFD) {
7044 if (FD == CurFD)
7045 SeenAt = I;
7046 else if (CurFD->isTargetMultiVersionDefault())
7047 HasDefault = true;
7048 ++I;
7049 });
7050 return HasDefault || SeenAt != 0;
7051}
7052
7055 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7056 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7057 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7058 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7059 bool StrictPackMatch) {
7060 const FunctionProtoType *Proto
7061 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7062 assert(Proto && "Functions without a prototype cannot be overloaded");
7063 assert(!Function->getDescribedFunctionTemplate() &&
7064 "Use AddTemplateOverloadCandidate for function templates");
7065
7066 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7068 // If we get here, it's because we're calling a member function
7069 // that is named without a member access expression (e.g.,
7070 // "this->f") that was either written explicitly or created
7071 // implicitly. This can happen with a qualified call to a member
7072 // function, e.g., X::f(). We use an empty type for the implied
7073 // object argument (C++ [over.call.func]p3), and the acting context
7074 // is irrelevant.
7075 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7077 CandidateSet, SuppressUserConversions,
7078 PartialOverloading, EarlyConversions, PO,
7079 StrictPackMatch);
7080 return;
7081 }
7082 // We treat a constructor like a non-member function, since its object
7083 // argument doesn't participate in overload resolution.
7084 }
7085
7086 if (!CandidateSet.isNewCandidate(Function, PO))
7087 return;
7088
7089 // C++11 [class.copy]p11: [DR1402]
7090 // A defaulted move constructor that is defined as deleted is ignored by
7091 // overload resolution.
7092 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7093 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7094 Constructor->isMoveConstructor())
7095 return;
7096
7097 // Overload resolution is always an unevaluated context.
7100
7101 // C++ [over.match.oper]p3:
7102 // if no operand has a class type, only those non-member functions in the
7103 // lookup set that have a first parameter of type T1 or "reference to
7104 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7105 // is a right operand) a second parameter of type T2 or "reference to
7106 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7107 // candidate functions.
7108 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7110 return;
7111
7112 // Add this candidate
7113 OverloadCandidate &Candidate =
7114 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7115 Candidate.FoundDecl = FoundDecl;
7116 Candidate.Function = Function;
7117 Candidate.Viable = true;
7118 Candidate.RewriteKind =
7119 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7120 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7121 Candidate.ExplicitCallArguments = Args.size();
7122 Candidate.StrictPackMatch = StrictPackMatch;
7123
7124 // Explicit functions are not actually candidates at all if we're not
7125 // allowing them in this context, but keep them around so we can point
7126 // to them in diagnostics.
7127 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7128 Candidate.Viable = false;
7129 Candidate.FailureKind = ovl_fail_explicit;
7130 return;
7131 }
7132
7133 // Functions with internal linkage are only viable in the same module unit.
7134 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7135 /// FIXME: Currently, the semantics of linkage in clang is slightly
7136 /// different from the semantics in C++ spec. In C++ spec, only names
7137 /// have linkage. So that all entities of the same should share one
7138 /// linkage. But in clang, different entities of the same could have
7139 /// different linkage.
7140 const NamedDecl *ND = Function;
7141 bool IsImplicitlyInstantiated = false;
7142 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7143 ND = SpecInfo->getTemplate();
7144 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7146 }
7147
7148 /// Don't remove inline functions with internal linkage from the overload
7149 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7150 /// However:
7151 /// - Inline functions with internal linkage are a common pattern in
7152 /// headers to avoid ODR issues.
7153 /// - The global module is meant to be a transition mechanism for C and C++
7154 /// headers, and the current rules as written work against that goal.
7155 const bool IsInlineFunctionInGMF =
7156 Function->isFromGlobalModule() &&
7157 (IsImplicitlyInstantiated || Function->isInlined());
7158
7159 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7160 Candidate.Viable = false;
7162 return;
7163 }
7164 }
7165
7167 Candidate.Viable = false;
7169 return;
7170 }
7171
7172 if (Constructor) {
7173 // C++ [class.copy]p3:
7174 // A member function template is never instantiated to perform the copy
7175 // of a class object to an object of its class type.
7176 CanQualType ClassType =
7177 Context.getCanonicalTagType(Constructor->getParent());
7178 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7179 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7180 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7181 ClassType))) {
7182 Candidate.Viable = false;
7184 return;
7185 }
7186
7187 // C++ [over.match.funcs]p8: (proposed DR resolution)
7188 // A constructor inherited from class type C that has a first parameter
7189 // of type "reference to P" (including such a constructor instantiated
7190 // from a template) is excluded from the set of candidate functions when
7191 // constructing an object of type cv D if the argument list has exactly
7192 // one argument and D is reference-related to P and P is reference-related
7193 // to C.
7194 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7195 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7196 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7197 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7198 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7199 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7200 SourceLocation Loc = Args.front()->getExprLoc();
7201 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7202 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7203 Candidate.Viable = false;
7205 return;
7206 }
7207 }
7208
7209 // Check that the constructor is capable of constructing an object in the
7210 // destination address space.
7212 Constructor->getMethodQualifiers().getAddressSpace(),
7213 CandidateSet.getDestAS(), getASTContext())) {
7214 Candidate.Viable = false;
7216 }
7217 }
7218
7219 unsigned NumParams = Proto->getNumParams();
7220
7221 // (C++ 13.3.2p2): A candidate function having fewer than m
7222 // parameters is viable only if it has an ellipsis in its parameter
7223 // list (8.3.5).
7224 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7225 !Proto->isVariadic() &&
7226 shouldEnforceArgLimit(PartialOverloading, Function)) {
7227 Candidate.Viable = false;
7229 return;
7230 }
7231
7232 // (C++ 13.3.2p2): A candidate function having more than m parameters
7233 // is viable only if the (m+1)st parameter has a default argument
7234 // (8.3.6). For the purposes of overload resolution, the
7235 // parameter list is truncated on the right, so that there are
7236 // exactly m parameters.
7237 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7238 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7239 !PartialOverloading) {
7240 // Not enough arguments.
7241 Candidate.Viable = false;
7243 return;
7244 }
7245
7246 // (CUDA B.1): Check for invalid calls between targets.
7247 if (getLangOpts().CUDA) {
7248 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7249 // Skip the check for callers that are implicit members, because in this
7250 // case we may not yet know what the member's target is; the target is
7251 // inferred for the member automatically, based on the bases and fields of
7252 // the class.
7253 if (!(Caller && Caller->isImplicit()) &&
7254 !CUDA().IsAllowedCall(Caller, Function)) {
7255 Candidate.Viable = false;
7256 Candidate.FailureKind = ovl_fail_bad_target;
7257 return;
7258 }
7259 }
7260
7261 if (Function->getTrailingRequiresClause()) {
7262 ConstraintSatisfaction Satisfaction;
7263 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7264 /*ForOverloadResolution*/ true) ||
7265 !Satisfaction.IsSatisfied) {
7266 Candidate.Viable = false;
7268 return;
7269 }
7270 }
7271
7272 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7273 // Determine the implicit conversion sequences for each of the
7274 // arguments.
7275 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7276 unsigned ConvIdx =
7277 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7278 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7279 // We already formed a conversion sequence for this parameter during
7280 // template argument deduction.
7281 } else if (ArgIdx < NumParams) {
7282 // (C++ 13.3.2p3): for F to be a viable function, there shall
7283 // exist for each argument an implicit conversion sequence
7284 // (13.3.3.1) that converts that argument to the corresponding
7285 // parameter of F.
7286 QualType ParamType = Proto->getParamType(ArgIdx);
7287 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7288 if (ParamABI == ParameterABI::HLSLOut ||
7289 ParamABI == ParameterABI::HLSLInOut)
7290 ParamType = ParamType.getNonReferenceType();
7291 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7292 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7293 /*InOverloadResolution=*/true,
7294 /*AllowObjCWritebackConversion=*/
7295 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7296 if (Candidate.Conversions[ConvIdx].isBad()) {
7297 Candidate.Viable = false;
7299 return;
7300 }
7301 } else {
7302 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7303 // argument for which there is no corresponding parameter is
7304 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7305 Candidate.Conversions[ConvIdx].setEllipsis();
7306 }
7307 }
7308
7309 if (EnableIfAttr *FailedAttr =
7310 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7311 Candidate.Viable = false;
7312 Candidate.FailureKind = ovl_fail_enable_if;
7313 Candidate.DeductionFailure.Data = FailedAttr;
7314 return;
7315 }
7316}
7317
7321 if (Methods.size() <= 1)
7322 return nullptr;
7323
7324 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7325 bool Match = true;
7326 ObjCMethodDecl *Method = Methods[b];
7327 unsigned NumNamedArgs = Sel.getNumArgs();
7328 // Method might have more arguments than selector indicates. This is due
7329 // to addition of c-style arguments in method.
7330 if (Method->param_size() > NumNamedArgs)
7331 NumNamedArgs = Method->param_size();
7332 if (Args.size() < NumNamedArgs)
7333 continue;
7334
7335 for (unsigned i = 0; i < NumNamedArgs; i++) {
7336 // We can't do any type-checking on a type-dependent argument.
7337 if (Args[i]->isTypeDependent()) {
7338 Match = false;
7339 break;
7340 }
7341
7342 ParmVarDecl *param = Method->parameters()[i];
7343 Expr *argExpr = Args[i];
7344 assert(argExpr && "SelectBestMethod(): missing expression");
7345
7346 // Strip the unbridged-cast placeholder expression off unless it's
7347 // a consumed argument.
7348 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7349 !param->hasAttr<CFConsumedAttr>())
7350 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7351
7352 // If the parameter is __unknown_anytype, move on to the next method.
7353 if (param->getType() == Context.UnknownAnyTy) {
7354 Match = false;
7355 break;
7356 }
7357
7358 ImplicitConversionSequence ConversionState
7359 = TryCopyInitialization(*this, argExpr, param->getType(),
7360 /*SuppressUserConversions*/false,
7361 /*InOverloadResolution=*/true,
7362 /*AllowObjCWritebackConversion=*/
7363 getLangOpts().ObjCAutoRefCount,
7364 /*AllowExplicit*/false);
7365 // This function looks for a reasonably-exact match, so we consider
7366 // incompatible pointer conversions to be a failure here.
7367 if (ConversionState.isBad() ||
7368 (ConversionState.isStandard() &&
7369 ConversionState.Standard.Second ==
7371 Match = false;
7372 break;
7373 }
7374 }
7375 // Promote additional arguments to variadic methods.
7376 if (Match && Method->isVariadic()) {
7377 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7378 if (Args[i]->isTypeDependent()) {
7379 Match = false;
7380 break;
7381 }
7383 Args[i], VariadicCallType::Method, nullptr);
7384 if (Arg.isInvalid()) {
7385 Match = false;
7386 break;
7387 }
7388 }
7389 } else {
7390 // Check for extra arguments to non-variadic methods.
7391 if (Args.size() != NumNamedArgs)
7392 Match = false;
7393 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7394 // Special case when selectors have no argument. In this case, select
7395 // one with the most general result type of 'id'.
7396 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7397 QualType ReturnT = Methods[b]->getReturnType();
7398 if (ReturnT->isObjCIdType())
7399 return Methods[b];
7400 }
7401 }
7402 }
7403
7404 if (Match)
7405 return Method;
7406 }
7407 return nullptr;
7408}
7409
7411 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7412 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7413 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7414 if (ThisArg) {
7415 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7416 assert(!isa<CXXConstructorDecl>(Method) &&
7417 "Shouldn't have `this` for ctors!");
7418 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7420 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7421 if (R.isInvalid())
7422 return false;
7423 ConvertedThis = R.get();
7424 } else {
7425 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7426 (void)MD;
7427 assert((MissingImplicitThis || MD->isStatic() ||
7429 "Expected `this` for non-ctor instance methods");
7430 }
7431 ConvertedThis = nullptr;
7432 }
7433
7434 // Ignore any variadic arguments. Converting them is pointless, since the
7435 // user can't refer to them in the function condition.
7436 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7437
7438 // Convert the arguments.
7439 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7440 ExprResult R;
7442 S.Context, Function->getParamDecl(I)),
7443 SourceLocation(), Args[I]);
7444
7445 if (R.isInvalid())
7446 return false;
7447
7448 ConvertedArgs.push_back(R.get());
7449 }
7450
7451 if (Trap.hasErrorOccurred())
7452 return false;
7453
7454 // Push default arguments if needed.
7455 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7456 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7457 ParmVarDecl *P = Function->getParamDecl(i);
7458 if (!P->hasDefaultArg())
7459 return false;
7460 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7461 if (R.isInvalid())
7462 return false;
7463 ConvertedArgs.push_back(R.get());
7464 }
7465
7466 if (Trap.hasErrorOccurred())
7467 return false;
7468 }
7469 return true;
7470}
7471
7473 SourceLocation CallLoc,
7474 ArrayRef<Expr *> Args,
7475 bool MissingImplicitThis) {
7476 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7477 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7478 return nullptr;
7479
7480 SFINAETrap Trap(*this);
7481 SmallVector<Expr *, 16> ConvertedArgs;
7482 // FIXME: We should look into making enable_if late-parsed.
7483 Expr *DiscardedThis;
7485 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7486 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7487 return *EnableIfAttrs.begin();
7488
7489 for (auto *EIA : EnableIfAttrs) {
7491 // FIXME: This doesn't consider value-dependent cases, because doing so is
7492 // very difficult. Ideally, we should handle them more gracefully.
7493 if (EIA->getCond()->isValueDependent() ||
7494 !EIA->getCond()->EvaluateWithSubstitution(
7495 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7496 return EIA;
7497
7498 if (!Result.isInt() || !Result.getInt().getBoolValue())
7499 return EIA;
7500 }
7501 return nullptr;
7502}
7503
7504template <typename CheckFn>
7506 bool ArgDependent, SourceLocation Loc,
7507 CheckFn &&IsSuccessful) {
7509 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7510 if (ArgDependent == DIA->getArgDependent())
7511 Attrs.push_back(DIA);
7512 }
7513
7514 // Common case: No diagnose_if attributes, so we can quit early.
7515 if (Attrs.empty())
7516 return false;
7517
7518 auto WarningBegin = std::stable_partition(
7519 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7520 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7521 DIA->getWarningGroup().empty();
7522 });
7523
7524 // Note that diagnose_if attributes are late-parsed, so they appear in the
7525 // correct order (unlike enable_if attributes).
7526 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7527 IsSuccessful);
7528 if (ErrAttr != WarningBegin) {
7529 const DiagnoseIfAttr *DIA = *ErrAttr;
7530 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7531 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7532 << DIA->getParent() << DIA->getCond()->getSourceRange();
7533 return true;
7534 }
7535
7536 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7537 switch (Sev) {
7538 case DiagnoseIfAttr::DS_warning:
7540 case DiagnoseIfAttr::DS_error:
7541 return diag::Severity::Error;
7542 }
7543 llvm_unreachable("Fully covered switch above!");
7544 };
7545
7546 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7547 if (IsSuccessful(DIA)) {
7548 if (DIA->getWarningGroup().empty() &&
7549 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7550 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7551 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7552 << DIA->getParent() << DIA->getCond()->getSourceRange();
7553 } else {
7554 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7555 DIA->getWarningGroup());
7556 assert(DiagGroup);
7557 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7558 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7559 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7560 S.Diag(Loc, DiagID) << DIA->getMessage();
7561 }
7562 }
7563
7564 return false;
7565}
7566
7568 const Expr *ThisArg,
7570 SourceLocation Loc) {
7572 *this, Function, /*ArgDependent=*/true, Loc,
7573 [&](const DiagnoseIfAttr *DIA) {
7575 // It's sane to use the same Args for any redecl of this function, since
7576 // EvaluateWithSubstitution only cares about the position of each
7577 // argument in the arg list, not the ParmVarDecl* it maps to.
7578 if (!DIA->getCond()->EvaluateWithSubstitution(
7579 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7580 return false;
7581 return Result.isInt() && Result.getInt().getBoolValue();
7582 });
7583}
7584
7586 SourceLocation Loc) {
7588 *this, ND, /*ArgDependent=*/false, Loc,
7589 [&](const DiagnoseIfAttr *DIA) {
7590 bool Result;
7591 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7592 Result;
7593 });
7594}
7595
7597 ArrayRef<Expr *> Args,
7598 OverloadCandidateSet &CandidateSet,
7599 TemplateArgumentListInfo *ExplicitTemplateArgs,
7600 bool SuppressUserConversions,
7601 bool PartialOverloading,
7602 bool FirstArgumentIsBase) {
7603 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7604 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7605 ArrayRef<Expr *> FunctionArgs = Args;
7606
7607 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7608 FunctionDecl *FD =
7609 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7610
7611 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7612 QualType ObjectType;
7613 Expr::Classification ObjectClassification;
7614 if (Args.size() > 0) {
7615 if (Expr *E = Args[0]) {
7616 // Use the explicit base to restrict the lookup:
7617 ObjectType = E->getType();
7618 // Pointers in the object arguments are implicitly dereferenced, so we
7619 // always classify them as l-values.
7620 if (!ObjectType.isNull() && ObjectType->isPointerType())
7621 ObjectClassification = Expr::Classification::makeSimpleLValue();
7622 else
7623 ObjectClassification = E->Classify(Context);
7624 } // .. else there is an implicit base.
7625 FunctionArgs = Args.slice(1);
7626 }
7627 if (FunTmpl) {
7629 FunTmpl, F.getPair(),
7631 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7632 FunctionArgs, CandidateSet, SuppressUserConversions,
7633 PartialOverloading);
7634 } else {
7635 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7636 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7637 ObjectClassification, FunctionArgs, CandidateSet,
7638 SuppressUserConversions, PartialOverloading);
7639 }
7640 } else {
7641 // This branch handles both standalone functions and static methods.
7642
7643 // Slice the first argument (which is the base) when we access
7644 // static method as non-static.
7645 if (Args.size() > 0 &&
7646 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7647 !isa<CXXConstructorDecl>(FD)))) {
7648 assert(cast<CXXMethodDecl>(FD)->isStatic());
7649 FunctionArgs = Args.slice(1);
7650 }
7651 if (FunTmpl) {
7652 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7653 ExplicitTemplateArgs, FunctionArgs,
7654 CandidateSet, SuppressUserConversions,
7655 PartialOverloading);
7656 } else {
7657 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7658 SuppressUserConversions, PartialOverloading);
7659 }
7660 }
7661 }
7662}
7663
7665 Expr::Classification ObjectClassification,
7666 ArrayRef<Expr *> Args,
7667 OverloadCandidateSet &CandidateSet,
7668 bool SuppressUserConversions,
7670 NamedDecl *Decl = FoundDecl.getDecl();
7672
7674 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7675
7676 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7677 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7678 "Expected a member function template");
7679 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7680 /*ExplicitArgs*/ nullptr, ObjectType,
7681 ObjectClassification, Args, CandidateSet,
7682 SuppressUserConversions, false, PO);
7683 } else {
7684 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7685 ObjectType, ObjectClassification, Args, CandidateSet,
7686 SuppressUserConversions, false, {}, PO);
7687 }
7688}
7689
7692 CXXRecordDecl *ActingContext, QualType ObjectType,
7693 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7694 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7695 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7696 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7697 const FunctionProtoType *Proto
7698 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7699 assert(Proto && "Methods without a prototype cannot be overloaded");
7701 "Use AddOverloadCandidate for constructors");
7702
7703 if (!CandidateSet.isNewCandidate(Method, PO))
7704 return;
7705
7706 // C++11 [class.copy]p23: [DR1402]
7707 // A defaulted move assignment operator that is defined as deleted is
7708 // ignored by overload resolution.
7709 if (Method->isDefaulted() && Method->isDeleted() &&
7710 Method->isMoveAssignmentOperator())
7711 return;
7712
7713 // Overload resolution is always an unevaluated context.
7716
7717 bool IgnoreExplicitObject =
7718 (Method->isExplicitObjectMemberFunction() &&
7719 CandidateSet.getKind() ==
7721 bool ImplicitObjectMethodTreatedAsStatic =
7722 CandidateSet.getKind() ==
7724 Method->isImplicitObjectMemberFunction();
7725
7726 unsigned ExplicitOffset =
7727 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7728
7729 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7730 int(ImplicitObjectMethodTreatedAsStatic);
7731
7732 unsigned ExtraArgs =
7734 ? 0
7735 : 1;
7736
7737 // Add this candidate
7738 OverloadCandidate &Candidate =
7739 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7740 Candidate.FoundDecl = FoundDecl;
7741 Candidate.Function = Method;
7742 Candidate.RewriteKind =
7743 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7744 Candidate.TookAddressOfOverload =
7746 Candidate.ExplicitCallArguments = Args.size();
7747 Candidate.StrictPackMatch = StrictPackMatch;
7748
7749 // (C++ 13.3.2p2): A candidate function having fewer than m
7750 // parameters is viable only if it has an ellipsis in its parameter
7751 // list (8.3.5).
7752 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7753 !Proto->isVariadic() &&
7754 shouldEnforceArgLimit(PartialOverloading, Method)) {
7755 Candidate.Viable = false;
7757 return;
7758 }
7759
7760 // (C++ 13.3.2p2): A candidate function having more than m parameters
7761 // is viable only if the (m+1)st parameter has a default argument
7762 // (8.3.6). For the purposes of overload resolution, the
7763 // parameter list is truncated on the right, so that there are
7764 // exactly m parameters.
7765 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7766 ExplicitOffset +
7767 int(ImplicitObjectMethodTreatedAsStatic);
7768
7769 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7770 // Not enough arguments.
7771 Candidate.Viable = false;
7773 return;
7774 }
7775
7776 Candidate.Viable = true;
7777
7778 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7779 if (!IgnoreExplicitObject) {
7780 if (ObjectType.isNull())
7781 Candidate.IgnoreObjectArgument = true;
7782 else if (Method->isStatic()) {
7783 // [over.best.ics.general]p8
7784 // When the parameter is the implicit object parameter of a static member
7785 // function, the implicit conversion sequence is a standard conversion
7786 // sequence that is neither better nor worse than any other standard
7787 // conversion sequence.
7788 //
7789 // This is a rule that was introduced in C++23 to support static lambdas.
7790 // We apply it retroactively because we want to support static lambdas as
7791 // an extension and it doesn't hurt previous code.
7792 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7793 } else {
7794 // Determine the implicit conversion sequence for the object
7795 // parameter.
7796 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7797 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7798 Method, ActingContext, /*InOverloadResolution=*/true);
7799 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7800 Candidate.Viable = false;
7802 return;
7803 }
7804 }
7805 }
7806
7807 // (CUDA B.1): Check for invalid calls between targets.
7808 if (getLangOpts().CUDA)
7809 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7810 Method)) {
7811 Candidate.Viable = false;
7812 Candidate.FailureKind = ovl_fail_bad_target;
7813 return;
7814 }
7815
7816 if (Method->getTrailingRequiresClause()) {
7817 ConstraintSatisfaction Satisfaction;
7818 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7819 /*ForOverloadResolution*/ true) ||
7820 !Satisfaction.IsSatisfied) {
7821 Candidate.Viable = false;
7823 return;
7824 }
7825 }
7826
7827 // Determine the implicit conversion sequences for each of the
7828 // arguments.
7829 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7830 unsigned ConvIdx =
7831 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7832 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7833 // We already formed a conversion sequence for this parameter during
7834 // template argument deduction.
7835 } else if (ArgIdx < NumParams) {
7836 // (C++ 13.3.2p3): for F to be a viable function, there shall
7837 // exist for each argument an implicit conversion sequence
7838 // (13.3.3.1) that converts that argument to the corresponding
7839 // parameter of F.
7840 QualType ParamType;
7841 if (ImplicitObjectMethodTreatedAsStatic) {
7842 ParamType = ArgIdx == 0
7843 ? Method->getFunctionObjectParameterReferenceType()
7844 : Proto->getParamType(ArgIdx - 1);
7845 } else {
7846 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7847 }
7848 Candidate.Conversions[ConvIdx]
7849 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7850 SuppressUserConversions,
7851 /*InOverloadResolution=*/true,
7852 /*AllowObjCWritebackConversion=*/
7853 getLangOpts().ObjCAutoRefCount);
7854 if (Candidate.Conversions[ConvIdx].isBad()) {
7855 Candidate.Viable = false;
7857 return;
7858 }
7859 } else {
7860 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7861 // argument for which there is no corresponding parameter is
7862 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7863 Candidate.Conversions[ConvIdx].setEllipsis();
7864 }
7865 }
7866
7867 if (EnableIfAttr *FailedAttr =
7868 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7869 Candidate.Viable = false;
7870 Candidate.FailureKind = ovl_fail_enable_if;
7871 Candidate.DeductionFailure.Data = FailedAttr;
7872 return;
7873 }
7874
7876 Candidate.Viable = false;
7878 }
7879}
7880
7882 Sema &S, OverloadCandidateSet &CandidateSet,
7883 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7884 CXXRecordDecl *ActingContext,
7885 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7886 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7887 bool SuppressUserConversions, bool PartialOverloading,
7889
7890 // C++ [over.match.funcs]p7:
7891 // In each case where a candidate is a function template, candidate
7892 // function template specializations are generated using template argument
7893 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7894 // candidate functions in the usual way.113) A given name can refer to one
7895 // or more function templates and also to a set of overloaded non-template
7896 // functions. In such a case, the candidate functions generated from each
7897 // function template are combined with the set of non-template candidate
7898 // functions.
7899 TemplateDeductionInfo Info(CandidateSet.getLocation());
7900 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7901 FunctionDecl *Specialization = nullptr;
7902 ConversionSequenceList Conversions;
7904 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7905 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7906 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7907 CandidateSet.getKind() ==
7909 [&](ArrayRef<QualType> ParamTypes,
7910 bool OnlyInitializeNonUserDefinedConversions) {
7911 return S.CheckNonDependentConversions(
7912 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7913 Sema::CheckNonDependentConversionsFlag(
7914 SuppressUserConversions,
7915 OnlyInitializeNonUserDefinedConversions),
7916 ActingContext, ObjectType, ObjectClassification, PO);
7917 });
7919 OverloadCandidate &Candidate =
7920 CandidateSet.addCandidate(Conversions.size(), Conversions);
7921 Candidate.FoundDecl = FoundDecl;
7922 Candidate.Function = Method;
7923 Candidate.Viable = false;
7924 Candidate.RewriteKind =
7925 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7926 Candidate.IsSurrogate = false;
7927 Candidate.TookAddressOfOverload =
7928 CandidateSet.getKind() ==
7930
7931 Candidate.IgnoreObjectArgument =
7932 Method->isStatic() ||
7933 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7934 Candidate.ExplicitCallArguments = Args.size();
7937 else {
7939 Candidate.DeductionFailure =
7940 MakeDeductionFailureInfo(S.Context, Result, Info);
7941 }
7942 return;
7943 }
7944
7945 // Add the function template specialization produced by template argument
7946 // deduction as a candidate.
7947 assert(Specialization && "Missing member function template specialization?");
7949 "Specialization is not a member function?");
7951 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7952 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7953 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7954}
7955
7957 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7958 CXXRecordDecl *ActingContext,
7959 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7960 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7961 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7962 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7963 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7964 return;
7965
7966 if (ExplicitTemplateArgs ||
7969 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7970 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7971 SuppressUserConversions, PartialOverloading, PO);
7972 return;
7973 }
7974
7976 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7977 Args, SuppressUserConversions, PartialOverloading, PO);
7978}
7979
7980/// Determine whether a given function template has a simple explicit specifier
7981/// or a non-value-dependent explicit-specification that evaluates to true.
7985
7990
7992 Sema &S, OverloadCandidateSet &CandidateSet,
7994 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7995 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7997 bool AggregateCandidateDeduction) {
7998
7999 // If the function template has a non-dependent explicit specification,
8000 // exclude it now if appropriate; we are not permitted to perform deduction
8001 // and substitution in this case.
8002 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8003 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8004 Candidate.FoundDecl = FoundDecl;
8005 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8006 Candidate.Viable = false;
8007 Candidate.FailureKind = ovl_fail_explicit;
8008 return;
8009 }
8010
8011 // C++ [over.match.funcs]p7:
8012 // In each case where a candidate is a function template, candidate
8013 // function template specializations are generated using template argument
8014 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8015 // candidate functions in the usual way.113) A given name can refer to one
8016 // or more function templates and also to a set of overloaded non-template
8017 // functions. In such a case, the candidate functions generated from each
8018 // function template are combined with the set of non-template candidate
8019 // functions.
8020 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8021 FunctionTemplate->getTemplateDepth());
8022 FunctionDecl *Specialization = nullptr;
8023 ConversionSequenceList Conversions;
8025 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8026 PartialOverloading, AggregateCandidateDeduction,
8027 /*PartialOrdering=*/false,
8028 /*ObjectType=*/QualType(),
8029 /*ObjectClassification=*/Expr::Classification(),
8030 CandidateSet.getKind() ==
8032 [&](ArrayRef<QualType> ParamTypes,
8033 bool OnlyInitializeNonUserDefinedConversions) {
8034 return S.CheckNonDependentConversions(
8035 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8036 Sema::CheckNonDependentConversionsFlag(
8037 SuppressUserConversions,
8038 OnlyInitializeNonUserDefinedConversions),
8039 nullptr, QualType(), {}, PO);
8040 });
8042 OverloadCandidate &Candidate =
8043 CandidateSet.addCandidate(Conversions.size(), Conversions);
8044 Candidate.FoundDecl = FoundDecl;
8045 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8046 Candidate.Viable = false;
8047 Candidate.RewriteKind =
8048 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8049 Candidate.IsSurrogate = false;
8050 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8051 // Ignore the object argument if there is one, since we don't have an object
8052 // type.
8053 Candidate.TookAddressOfOverload =
8054 CandidateSet.getKind() ==
8056
8057 Candidate.IgnoreObjectArgument =
8058 isa<CXXMethodDecl>(Candidate.Function) &&
8059 !cast<CXXMethodDecl>(Candidate.Function)
8060 ->isExplicitObjectMemberFunction() &&
8062
8063 Candidate.ExplicitCallArguments = Args.size();
8066 else {
8068 Candidate.DeductionFailure =
8070 }
8071 return;
8072 }
8073
8074 // Add the function template specialization produced by template argument
8075 // deduction as a candidate.
8076 assert(Specialization && "Missing function template specialization?");
8078 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8079 PartialOverloading, AllowExplicit,
8080 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8081 Info.AggregateDeductionCandidateHasMismatchedArity,
8082 Info.hasStrictPackMatch());
8083}
8084
8087 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8088 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8089 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8090 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8091 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8092 return;
8093
8094 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8095
8096 if (ExplicitTemplateArgs ||
8098 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8099 DependentExplicitSpecifier)) {
8100
8102 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8103 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8104 IsADLCandidate, PO, AggregateCandidateDeduction);
8105
8106 if (DependentExplicitSpecifier)
8108 return;
8109 }
8110
8111 CandidateSet.AddDeferredTemplateCandidate(
8112 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8113 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8114 AggregateCandidateDeduction);
8115}
8116
8119 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8121 CheckNonDependentConversionsFlag UserConversionFlag,
8122 CXXRecordDecl *ActingContext, QualType ObjectType,
8123 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8124 // FIXME: The cases in which we allow explicit conversions for constructor
8125 // arguments never consider calling a constructor template. It's not clear
8126 // that is correct.
8127 const bool AllowExplicit = false;
8128
8129 bool ForOverloadSetAddressResolution =
8131 auto *FD = FunctionTemplate->getTemplatedDecl();
8132 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8133 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8135 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8136
8137 if (Conversions.empty())
8138 Conversions =
8139 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8140
8141 // Overload resolution is always an unevaluated context.
8144
8145 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8146 // require that, but this check should never result in a hard error, and
8147 // overload resolution is permitted to sidestep instantiations.
8148 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8149 !ObjectType.isNull()) {
8150 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8151 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8152 !ParamTypes[0]->isDependentType()) {
8154 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8155 Method, ActingContext, /*InOverloadResolution=*/true,
8156 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8157 : QualType());
8158 if (Conversions[ConvIdx].isBad())
8159 return true;
8160 }
8161 }
8162
8163 // A speculative workaround for self-dependent constraint bugs that manifest
8164 // after CWG2369.
8165 // FIXME: Add references to the standard once P3606 is adopted.
8166 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8167 QualType ArgType) {
8168 ParamType = ParamType.getNonReferenceType();
8169 ArgType = ArgType.getNonReferenceType();
8170 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8171 if (PointerConv) {
8172 ParamType = ParamType->getPointeeType();
8173 ArgType = ArgType->getPointeeType();
8174 }
8175
8176 if (auto *RD = ParamType->getAsCXXRecordDecl();
8177 RD && RD->hasDefinition() &&
8178 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8179 auto Info = getConstructorInfo(ND);
8180 if (!Info)
8181 return false;
8182 CXXConstructorDecl *Ctor = Info.Constructor;
8183 /// isConvertingConstructor takes copy/move constructors into
8184 /// account!
8185 return !Ctor->isCopyOrMoveConstructor() &&
8187 /*AllowExplicit=*/true);
8188 }))
8189 return true;
8190 if (auto *RD = ArgType->getAsCXXRecordDecl();
8191 RD && RD->hasDefinition() &&
8192 !RD->getVisibleConversionFunctions().empty())
8193 return true;
8194
8195 return false;
8196 };
8197
8198 unsigned Offset =
8199 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8200 : 0;
8201
8202 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8203 I != N; ++I) {
8204 QualType ParamType = ParamTypes[I + Offset];
8205 if (!ParamType->isDependentType()) {
8206 unsigned ConvIdx;
8208 ConvIdx = Args.size() - 1 - I;
8209 assert(Args.size() + ThisConversions == 2 &&
8210 "number of args (including 'this') must be exactly 2 for "
8211 "reversed order");
8212 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8213 // would also be 0. 'this' got ConvIdx = 1 previously.
8214 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8215 } else {
8216 // For members, 'this' got ConvIdx = 0 previously.
8217 ConvIdx = ThisConversions + I;
8218 }
8219 if (Conversions[ConvIdx].isInitialized())
8220 continue;
8221 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8222 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8223 continue;
8225 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8226 /*InOverloadResolution=*/true,
8227 /*AllowObjCWritebackConversion=*/
8228 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8229 if (Conversions[ConvIdx].isBad())
8230 return true;
8231 }
8232 }
8233
8234 return false;
8235}
8236
8237/// Determine whether this is an allowable conversion from the result
8238/// of an explicit conversion operator to the expected type, per C++
8239/// [over.match.conv]p1 and [over.match.ref]p1.
8240///
8241/// \param ConvType The return type of the conversion function.
8242///
8243/// \param ToType The type we are converting to.
8244///
8245/// \param AllowObjCPointerConversion Allow a conversion from one
8246/// Objective-C pointer to another.
8247///
8248/// \returns true if the conversion is allowable, false otherwise.
8250 QualType ConvType, QualType ToType,
8251 bool AllowObjCPointerConversion) {
8252 QualType ToNonRefType = ToType.getNonReferenceType();
8253
8254 // Easy case: the types are the same.
8255 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8256 return true;
8257
8258 // Allow qualification conversions.
8259 bool ObjCLifetimeConversion;
8260 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8261 ObjCLifetimeConversion))
8262 return true;
8263
8264 // If we're not allowed to consider Objective-C pointer conversions,
8265 // we're done.
8266 if (!AllowObjCPointerConversion)
8267 return false;
8268
8269 // Is this an Objective-C pointer conversion?
8270 bool IncompatibleObjC = false;
8271 QualType ConvertedType;
8272 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8273 IncompatibleObjC);
8274}
8275
8277 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8278 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8279 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8280 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8281 assert(!Conversion->getDescribedFunctionTemplate() &&
8282 "Conversion function templates use AddTemplateConversionCandidate");
8283 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8284 if (!CandidateSet.isNewCandidate(Conversion))
8285 return;
8286
8287 // If the conversion function has an undeduced return type, trigger its
8288 // deduction now.
8289 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8290 if (DeduceReturnType(Conversion, From->getExprLoc()))
8291 return;
8292 ConvType = Conversion->getConversionType().getNonReferenceType();
8293 }
8294
8295 // If we don't allow any conversion of the result type, ignore conversion
8296 // functions that don't convert to exactly (possibly cv-qualified) T.
8297 if (!AllowResultConversion &&
8298 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8299 return;
8300
8301 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8302 // operator is only a candidate if its return type is the target type or
8303 // can be converted to the target type with a qualification conversion.
8304 //
8305 // FIXME: Include such functions in the candidate list and explain why we
8306 // can't select them.
8307 if (Conversion->isExplicit() &&
8308 !isAllowableExplicitConversion(*this, ConvType, ToType,
8309 AllowObjCConversionOnExplicit))
8310 return;
8311
8312 // Overload resolution is always an unevaluated context.
8315
8316 // Add this candidate
8317 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8318 Candidate.FoundDecl = FoundDecl;
8319 Candidate.Function = Conversion;
8321 Candidate.FinalConversion.setFromType(ConvType);
8322 Candidate.FinalConversion.setAllToTypes(ToType);
8323 Candidate.HasFinalConversion = true;
8324 Candidate.Viable = true;
8325 Candidate.ExplicitCallArguments = 1;
8326 Candidate.StrictPackMatch = StrictPackMatch;
8327
8328 // Explicit functions are not actually candidates at all if we're not
8329 // allowing them in this context, but keep them around so we can point
8330 // to them in diagnostics.
8331 if (!AllowExplicit && Conversion->isExplicit()) {
8332 Candidate.Viable = false;
8333 Candidate.FailureKind = ovl_fail_explicit;
8334 return;
8335 }
8336
8337 // C++ [over.match.funcs]p4:
8338 // For conversion functions, the function is considered to be a member of
8339 // the class of the implicit implied object argument for the purpose of
8340 // defining the type of the implicit object parameter.
8341 //
8342 // Determine the implicit conversion sequence for the implicit
8343 // object parameter.
8344 QualType ObjectType = From->getType();
8345 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8346 ObjectType = FromPtrType->getPointeeType();
8347 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8348 // C++23 [over.best.ics.general]
8349 // However, if the target is [...]
8350 // - the object parameter of a user-defined conversion function
8351 // [...] user-defined conversion sequences are not considered.
8353 *this, CandidateSet.getLocation(), From->getType(),
8354 From->Classify(Context), Conversion, ConversionContext,
8355 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8356 /*SuppressUserConversion*/ true);
8357
8358 if (Candidate.Conversions[0].isBad()) {
8359 Candidate.Viable = false;
8361 return;
8362 }
8363
8364 if (Conversion->getTrailingRequiresClause()) {
8365 ConstraintSatisfaction Satisfaction;
8366 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8367 !Satisfaction.IsSatisfied) {
8368 Candidate.Viable = false;
8370 return;
8371 }
8372 }
8373
8374 // We won't go through a user-defined type conversion function to convert a
8375 // derived to base as such conversions are given Conversion Rank. They only
8376 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8377 QualType FromCanon
8378 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8379 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8380 if (FromCanon == ToCanon ||
8381 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8382 Candidate.Viable = false;
8384 return;
8385 }
8386
8387 // To determine what the conversion from the result of calling the
8388 // conversion function to the type we're eventually trying to
8389 // convert to (ToType), we need to synthesize a call to the
8390 // conversion function and attempt copy initialization from it. This
8391 // makes sure that we get the right semantics with respect to
8392 // lvalues/rvalues and the type. Fortunately, we can allocate this
8393 // call on the stack and we don't need its arguments to be
8394 // well-formed.
8395 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8396 VK_LValue, From->getBeginLoc());
8398 Context.getPointerType(Conversion->getType()),
8399 CK_FunctionToPointerDecay, &ConversionRef,
8401
8402 QualType ConversionType = Conversion->getConversionType();
8403 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8404 Candidate.Viable = false;
8406 return;
8407 }
8408
8409 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8410
8411 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8412
8413 // Introduce a temporary expression with the right type and value category
8414 // that we can use for deduction purposes.
8415 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8416
8418 TryCopyInitialization(*this, &FakeCall, ToType,
8419 /*SuppressUserConversions=*/true,
8420 /*InOverloadResolution=*/false,
8421 /*AllowObjCWritebackConversion=*/false);
8422
8423 switch (ICS.getKind()) {
8425 Candidate.FinalConversion = ICS.Standard;
8426 Candidate.HasFinalConversion = true;
8427
8428 // C++ [over.ics.user]p3:
8429 // If the user-defined conversion is specified by a specialization of a
8430 // conversion function template, the second standard conversion sequence
8431 // shall have exact match rank.
8432 if (Conversion->getPrimaryTemplate() &&
8434 Candidate.Viable = false;
8436 return;
8437 }
8438
8439 // C++0x [dcl.init.ref]p5:
8440 // In the second case, if the reference is an rvalue reference and
8441 // the second standard conversion sequence of the user-defined
8442 // conversion sequence includes an lvalue-to-rvalue conversion, the
8443 // program is ill-formed.
8444 if (ToType->isRValueReferenceType() &&
8446 Candidate.Viable = false;
8448 return;
8449 }
8450 break;
8451
8453 Candidate.Viable = false;
8455 return;
8456
8457 default:
8458 llvm_unreachable(
8459 "Can only end up with a standard conversion sequence or failure");
8460 }
8461
8462 if (EnableIfAttr *FailedAttr =
8463 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8464 Candidate.Viable = false;
8465 Candidate.FailureKind = ovl_fail_enable_if;
8466 Candidate.DeductionFailure.Data = FailedAttr;
8467 return;
8468 }
8469
8470 if (isNonViableMultiVersionOverload(Conversion)) {
8471 Candidate.Viable = false;
8473 }
8474}
8475
8477 Sema &S, OverloadCandidateSet &CandidateSet,
8479 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8480 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8481 bool AllowResultConversion) {
8482
8483 // If the function template has a non-dependent explicit specification,
8484 // exclude it now if appropriate; we are not permitted to perform deduction
8485 // and substitution in this case.
8486 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8487 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8488 Candidate.FoundDecl = FoundDecl;
8489 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8490 Candidate.Viable = false;
8491 Candidate.FailureKind = ovl_fail_explicit;
8492 return;
8493 }
8494
8495 QualType ObjectType = From->getType();
8496 Expr::Classification ObjectClassification = From->Classify(S.Context);
8497
8498 TemplateDeductionInfo Info(CandidateSet.getLocation());
8501 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8502 Specialization, Info);
8504 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8505 Candidate.FoundDecl = FoundDecl;
8506 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8507 Candidate.Viable = false;
8509 Candidate.ExplicitCallArguments = 1;
8510 Candidate.DeductionFailure =
8511 MakeDeductionFailureInfo(S.Context, Result, Info);
8512 return;
8513 }
8514
8515 // Add the conversion function template specialization produced by
8516 // template argument deduction as a candidate.
8517 assert(Specialization && "Missing function template specialization?");
8518 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8519 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8520 AllowExplicit, AllowResultConversion,
8521 Info.hasStrictPackMatch());
8522}
8523
8526 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8527 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8528 bool AllowExplicit, bool AllowResultConversion) {
8529 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8530 "Only conversion function templates permitted here");
8531
8532 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8533 return;
8534
8536 CandidateSet.getKind() ==
8540 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8541 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8542 AllowResultConversion);
8543
8545 return;
8546 }
8547
8549 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8550 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8551}
8552
8554 DeclAccessPair FoundDecl,
8555 CXXRecordDecl *ActingContext,
8556 const FunctionProtoType *Proto,
8557 Expr *Object,
8558 ArrayRef<Expr *> Args,
8559 OverloadCandidateSet& CandidateSet) {
8560 if (!CandidateSet.isNewCandidate(Conversion))
8561 return;
8562
8563 // Overload resolution is always an unevaluated context.
8566
8567 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8568 Candidate.FoundDecl = FoundDecl;
8569 Candidate.Function = nullptr;
8570 Candidate.Surrogate = Conversion;
8571 Candidate.IsSurrogate = true;
8572 Candidate.Viable = true;
8573 Candidate.ExplicitCallArguments = Args.size();
8574
8575 // Determine the implicit conversion sequence for the implicit
8576 // object parameter.
8577 ImplicitConversionSequence ObjectInit;
8578 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8579 ObjectInit = TryCopyInitialization(*this, Object,
8580 Conversion->getParamDecl(0)->getType(),
8581 /*SuppressUserConversions=*/false,
8582 /*InOverloadResolution=*/true, false);
8583 } else {
8585 *this, CandidateSet.getLocation(), Object->getType(),
8586 Object->Classify(Context), Conversion, ActingContext);
8587 }
8588
8589 if (ObjectInit.isBad()) {
8590 Candidate.Viable = false;
8592 Candidate.Conversions[0] = ObjectInit;
8593 return;
8594 }
8595
8596 // The first conversion is actually a user-defined conversion whose
8597 // first conversion is ObjectInit's standard conversion (which is
8598 // effectively a reference binding). Record it as such.
8599 Candidate.Conversions[0].setUserDefined();
8600 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8601 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8602 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8603 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8604 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8605 Candidate.Conversions[0].UserDefined.After
8606 = Candidate.Conversions[0].UserDefined.Before;
8607 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8608
8609 // Find the
8610 unsigned NumParams = Proto->getNumParams();
8611
8612 // (C++ 13.3.2p2): A candidate function having fewer than m
8613 // parameters is viable only if it has an ellipsis in its parameter
8614 // list (8.3.5).
8615 if (Args.size() > NumParams && !Proto->isVariadic()) {
8616 Candidate.Viable = false;
8618 return;
8619 }
8620
8621 // Function types don't have any default arguments, so just check if
8622 // we have enough arguments.
8623 if (Args.size() < NumParams) {
8624 // Not enough arguments.
8625 Candidate.Viable = false;
8627 return;
8628 }
8629
8630 // Determine the implicit conversion sequences for each of the
8631 // arguments.
8632 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8633 if (ArgIdx < NumParams) {
8634 // (C++ 13.3.2p3): for F to be a viable function, there shall
8635 // exist for each argument an implicit conversion sequence
8636 // (13.3.3.1) that converts that argument to the corresponding
8637 // parameter of F.
8638 QualType ParamType = Proto->getParamType(ArgIdx);
8639 Candidate.Conversions[ArgIdx + 1]
8640 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8641 /*SuppressUserConversions=*/false,
8642 /*InOverloadResolution=*/false,
8643 /*AllowObjCWritebackConversion=*/
8644 getLangOpts().ObjCAutoRefCount);
8645 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8646 Candidate.Viable = false;
8648 return;
8649 }
8650 } else {
8651 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8652 // argument for which there is no corresponding parameter is
8653 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8654 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8655 }
8656 }
8657
8658 if (Conversion->getTrailingRequiresClause()) {
8659 ConstraintSatisfaction Satisfaction;
8660 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8661 /*ForOverloadResolution*/ true) ||
8662 !Satisfaction.IsSatisfied) {
8663 Candidate.Viable = false;
8665 return;
8666 }
8667 }
8668
8669 if (EnableIfAttr *FailedAttr =
8670 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8671 Candidate.Viable = false;
8672 Candidate.FailureKind = ovl_fail_enable_if;
8673 Candidate.DeductionFailure.Data = FailedAttr;
8674 return;
8675 }
8676}
8677
8679 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8680 OverloadCandidateSet &CandidateSet,
8681 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8682 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8683 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8684 ArrayRef<Expr *> FunctionArgs = Args;
8685
8686 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8687 FunctionDecl *FD =
8688 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8689
8690 // Don't consider rewritten functions if we're not rewriting.
8691 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8692 continue;
8693
8694 assert(!isa<CXXMethodDecl>(FD) &&
8695 "unqualified operator lookup found a member function");
8696
8697 if (FunTmpl) {
8698 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8699 FunctionArgs, CandidateSet);
8700 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8701
8702 // As template candidates are not deduced immediately,
8703 // persist the array in the overload set.
8705 FunctionArgs[1], FunctionArgs[0]);
8706 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8707 Reversed, CandidateSet, false, false, true,
8708 ADLCallKind::NotADL,
8710 }
8711 } else {
8712 if (ExplicitTemplateArgs)
8713 continue;
8714 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8715 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8716 AddOverloadCandidate(FD, F.getPair(),
8717 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8718 false, false, true, false, ADLCallKind::NotADL, {},
8720 }
8721 }
8722}
8723
8725 SourceLocation OpLoc,
8726 ArrayRef<Expr *> Args,
8727 OverloadCandidateSet &CandidateSet,
8729 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8730
8731 // C++ [over.match.oper]p3:
8732 // For a unary operator @ with an operand of a type whose
8733 // cv-unqualified version is T1, and for a binary operator @ with
8734 // a left operand of a type whose cv-unqualified version is T1 and
8735 // a right operand of a type whose cv-unqualified version is T2,
8736 // three sets of candidate functions, designated member
8737 // candidates, non-member candidates and built-in candidates, are
8738 // constructed as follows:
8739 QualType T1 = Args[0]->getType();
8740
8741 // -- If T1 is a complete class type or a class currently being
8742 // defined, the set of member candidates is the result of the
8743 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8744 // the set of member candidates is empty.
8745 if (T1->isRecordType()) {
8746 bool IsComplete = isCompleteType(OpLoc, T1);
8747 auto *T1RD = T1->getAsCXXRecordDecl();
8748 // Complete the type if it can be completed.
8749 // If the type is neither complete nor being defined, bail out now.
8750 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8751 return;
8752
8753 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8754 LookupQualifiedName(Operators, T1RD);
8755 Operators.suppressAccessDiagnostics();
8756
8757 for (LookupResult::iterator Oper = Operators.begin(),
8758 OperEnd = Operators.end();
8759 Oper != OperEnd; ++Oper) {
8760 if (Oper->getAsFunction() &&
8762 !CandidateSet.getRewriteInfo().shouldAddReversed(
8763 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8764 continue;
8765 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8766 Args[0]->Classify(Context), Args.slice(1),
8767 CandidateSet, /*SuppressUserConversion=*/false, PO);
8768 }
8769 }
8770}
8771
8773 OverloadCandidateSet& CandidateSet,
8774 bool IsAssignmentOperator,
8775 unsigned NumContextualBoolArguments) {
8776 // Overload resolution is always an unevaluated context.
8779
8780 // Add this candidate
8781 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8782 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8783 Candidate.Function = nullptr;
8784 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8785
8786 // Determine the implicit conversion sequences for each of the
8787 // arguments.
8788 Candidate.Viable = true;
8789 Candidate.ExplicitCallArguments = Args.size();
8790 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8791 // C++ [over.match.oper]p4:
8792 // For the built-in assignment operators, conversions of the
8793 // left operand are restricted as follows:
8794 // -- no temporaries are introduced to hold the left operand, and
8795 // -- no user-defined conversions are applied to the left
8796 // operand to achieve a type match with the left-most
8797 // parameter of a built-in candidate.
8798 //
8799 // We block these conversions by turning off user-defined
8800 // conversions, since that is the only way that initialization of
8801 // a reference to a non-class type can occur from something that
8802 // is not of the same type.
8803 if (ArgIdx < NumContextualBoolArguments) {
8804 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8805 "Contextual conversion to bool requires bool type");
8806 Candidate.Conversions[ArgIdx]
8807 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8808 } else {
8809 Candidate.Conversions[ArgIdx]
8810 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8811 ArgIdx == 0 && IsAssignmentOperator,
8812 /*InOverloadResolution=*/false,
8813 /*AllowObjCWritebackConversion=*/
8814 getLangOpts().ObjCAutoRefCount);
8815 }
8816 if (Candidate.Conversions[ArgIdx].isBad()) {
8817 Candidate.Viable = false;
8819 break;
8820 }
8821 }
8822}
8823
8824namespace {
8825
8826/// BuiltinCandidateTypeSet - A set of types that will be used for the
8827/// candidate operator functions for built-in operators (C++
8828/// [over.built]). The types are separated into pointer types and
8829/// enumeration types.
8830class BuiltinCandidateTypeSet {
8831 /// TypeSet - A set of types.
8832 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8833
8834 /// PointerTypes - The set of pointer types that will be used in the
8835 /// built-in candidates.
8836 TypeSet PointerTypes;
8837
8838 /// MemberPointerTypes - The set of member pointer types that will be
8839 /// used in the built-in candidates.
8840 TypeSet MemberPointerTypes;
8841
8842 /// EnumerationTypes - The set of enumeration types that will be
8843 /// used in the built-in candidates.
8844 TypeSet EnumerationTypes;
8845
8846 /// The set of vector types that will be used in the built-in
8847 /// candidates.
8848 TypeSet VectorTypes;
8849
8850 /// The set of matrix types that will be used in the built-in
8851 /// candidates.
8852 TypeSet MatrixTypes;
8853
8854 /// The set of _BitInt types that will be used in the built-in candidates.
8855 TypeSet BitIntTypes;
8856
8857 /// A flag indicating non-record types are viable candidates
8858 bool HasNonRecordTypes;
8859
8860 /// A flag indicating whether either arithmetic or enumeration types
8861 /// were present in the candidate set.
8862 bool HasArithmeticOrEnumeralTypes;
8863
8864 /// A flag indicating whether the nullptr type was present in the
8865 /// candidate set.
8866 bool HasNullPtrType;
8867
8868 /// Sema - The semantic analysis instance where we are building the
8869 /// candidate type set.
8870 Sema &SemaRef;
8871
8872 /// Context - The AST context in which we will build the type sets.
8873 ASTContext &Context;
8874
8875 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8876 const Qualifiers &VisibleQuals);
8877 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8878
8879public:
8880 /// iterator - Iterates through the types that are part of the set.
8881 typedef TypeSet::iterator iterator;
8882
8883 BuiltinCandidateTypeSet(Sema &SemaRef)
8884 : HasNonRecordTypes(false),
8885 HasArithmeticOrEnumeralTypes(false),
8886 HasNullPtrType(false),
8887 SemaRef(SemaRef),
8888 Context(SemaRef.Context) { }
8889
8890 void AddTypesConvertedFrom(QualType Ty,
8891 SourceLocation Loc,
8892 bool AllowUserConversions,
8893 bool AllowExplicitConversions,
8894 const Qualifiers &VisibleTypeConversionsQuals);
8895
8896 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8897 llvm::iterator_range<iterator> member_pointer_types() {
8898 return MemberPointerTypes;
8899 }
8900 llvm::iterator_range<iterator> enumeration_types() {
8901 return EnumerationTypes;
8902 }
8903 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8904 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8905 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8906
8907 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8908 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8909 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8910 bool hasNullPtrType() const { return HasNullPtrType; }
8911};
8912
8913} // end anonymous namespace
8914
8915/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8916/// the set of pointer types along with any more-qualified variants of
8917/// that type. For example, if @p Ty is "int const *", this routine
8918/// will add "int const *", "int const volatile *", "int const
8919/// restrict *", and "int const volatile restrict *" to the set of
8920/// pointer types. Returns true if the add of @p Ty itself succeeded,
8921/// false otherwise.
8922///
8923/// FIXME: what to do about extended qualifiers?
8924bool
8925BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8926 const Qualifiers &VisibleQuals) {
8927
8928 // Insert this type.
8929 if (!PointerTypes.insert(Ty))
8930 return false;
8931
8932 QualType PointeeTy;
8933 const PointerType *PointerTy = Ty->getAs<PointerType>();
8934 bool buildObjCPtr = false;
8935 if (!PointerTy) {
8936 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8937 PointeeTy = PTy->getPointeeType();
8938 buildObjCPtr = true;
8939 } else {
8940 PointeeTy = PointerTy->getPointeeType();
8941 }
8942
8943 // Don't add qualified variants of arrays. For one, they're not allowed
8944 // (the qualifier would sink to the element type), and for another, the
8945 // only overload situation where it matters is subscript or pointer +- int,
8946 // and those shouldn't have qualifier variants anyway.
8947 if (PointeeTy->isArrayType())
8948 return true;
8949
8950 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8951 bool hasVolatile = VisibleQuals.hasVolatile();
8952 bool hasRestrict = VisibleQuals.hasRestrict();
8953
8954 // Iterate through all strict supersets of BaseCVR.
8955 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8956 if ((CVR | BaseCVR) != CVR) continue;
8957 // Skip over volatile if no volatile found anywhere in the types.
8958 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8959
8960 // Skip over restrict if no restrict found anywhere in the types, or if
8961 // the type cannot be restrict-qualified.
8962 if ((CVR & Qualifiers::Restrict) &&
8963 (!hasRestrict ||
8964 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8965 continue;
8966
8967 // Build qualified pointee type.
8968 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8969
8970 // Build qualified pointer type.
8971 QualType QPointerTy;
8972 if (!buildObjCPtr)
8973 QPointerTy = Context.getPointerType(QPointeeTy);
8974 else
8975 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8976
8977 // Insert qualified pointer type.
8978 PointerTypes.insert(QPointerTy);
8979 }
8980
8981 return true;
8982}
8983
8984/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8985/// to the set of pointer types along with any more-qualified variants of
8986/// that type. For example, if @p Ty is "int const *", this routine
8987/// will add "int const *", "int const volatile *", "int const
8988/// restrict *", and "int const volatile restrict *" to the set of
8989/// pointer types. Returns true if the add of @p Ty itself succeeded,
8990/// false otherwise.
8991///
8992/// FIXME: what to do about extended qualifiers?
8993bool
8994BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8995 QualType Ty) {
8996 // Insert this type.
8997 if (!MemberPointerTypes.insert(Ty))
8998 return false;
8999
9000 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9001 assert(PointerTy && "type was not a member pointer type!");
9002
9003 QualType PointeeTy = PointerTy->getPointeeType();
9004 // Don't add qualified variants of arrays. For one, they're not allowed
9005 // (the qualifier would sink to the element type), and for another, the
9006 // only overload situation where it matters is subscript or pointer +- int,
9007 // and those shouldn't have qualifier variants anyway.
9008 if (PointeeTy->isArrayType())
9009 return true;
9010 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9011
9012 // Iterate through all strict supersets of the pointee type's CVR
9013 // qualifiers.
9014 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9015 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9016 if ((CVR | BaseCVR) != CVR) continue;
9017
9018 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9019 MemberPointerTypes.insert(Context.getMemberPointerType(
9020 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9021 }
9022
9023 return true;
9024}
9025
9026/// AddTypesConvertedFrom - Add each of the types to which the type @p
9027/// Ty can be implicit converted to the given set of @p Types. We're
9028/// primarily interested in pointer types and enumeration types. We also
9029/// take member pointer types, for the conditional operator.
9030/// AllowUserConversions is true if we should look at the conversion
9031/// functions of a class type, and AllowExplicitConversions if we
9032/// should also include the explicit conversion functions of a class
9033/// type.
9034void
9035BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9036 SourceLocation Loc,
9037 bool AllowUserConversions,
9038 bool AllowExplicitConversions,
9039 const Qualifiers &VisibleQuals) {
9040 // Only deal with canonical types.
9041 Ty = Context.getCanonicalType(Ty);
9042
9043 // Look through reference types; they aren't part of the type of an
9044 // expression for the purposes of conversions.
9045 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9046 Ty = RefTy->getPointeeType();
9047
9048 // If we're dealing with an array type, decay to the pointer.
9049 if (Ty->isArrayType())
9050 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9051
9052 // Otherwise, we don't care about qualifiers on the type.
9053 Ty = Ty.getLocalUnqualifiedType();
9054
9055 // Flag if we ever add a non-record type.
9056 bool TyIsRec = Ty->isRecordType();
9057 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9058
9059 // Flag if we encounter an arithmetic type.
9060 HasArithmeticOrEnumeralTypes =
9061 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9062
9063 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9064 PointerTypes.insert(Ty);
9065 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9066 // Insert our type, and its more-qualified variants, into the set
9067 // of types.
9068 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9069 return;
9070 } else if (Ty->isMemberPointerType()) {
9071 // Member pointers are far easier, since the pointee can't be converted.
9072 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9073 return;
9074 } else if (Ty->isEnumeralType()) {
9075 HasArithmeticOrEnumeralTypes = true;
9076 EnumerationTypes.insert(Ty);
9077 } else if (Ty->isBitIntType()) {
9078 HasArithmeticOrEnumeralTypes = true;
9079 BitIntTypes.insert(Ty);
9080 } else if (Ty->isVectorType()) {
9081 // We treat vector types as arithmetic types in many contexts as an
9082 // extension.
9083 HasArithmeticOrEnumeralTypes = true;
9084 VectorTypes.insert(Ty);
9085 } else if (Ty->isMatrixType()) {
9086 // Similar to vector types, we treat vector types as arithmetic types in
9087 // many contexts as an extension.
9088 HasArithmeticOrEnumeralTypes = true;
9089 MatrixTypes.insert(Ty);
9090 } else if (Ty->isNullPtrType()) {
9091 HasNullPtrType = true;
9092 } else if (AllowUserConversions && TyIsRec) {
9093 // No conversion functions in incomplete types.
9094 if (!SemaRef.isCompleteType(Loc, Ty))
9095 return;
9096
9097 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9098 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9099 if (isa<UsingShadowDecl>(D))
9100 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9101
9102 // Skip conversion function templates; they don't tell us anything
9103 // about which builtin types we can convert to.
9105 continue;
9106
9107 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9108 if (AllowExplicitConversions || !Conv->isExplicit()) {
9109 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9110 VisibleQuals);
9111 }
9112 }
9113 }
9114}
9115/// Helper function for adjusting address spaces for the pointer or reference
9116/// operands of builtin operators depending on the argument.
9121
9122/// Helper function for AddBuiltinOperatorCandidates() that adds
9123/// the volatile- and non-volatile-qualified assignment operators for the
9124/// given type to the candidate set.
9126 QualType T,
9127 ArrayRef<Expr *> Args,
9128 OverloadCandidateSet &CandidateSet) {
9129 QualType ParamTypes[2];
9130
9131 // T& operator=(T&, T)
9132 ParamTypes[0] = S.Context.getLValueReferenceType(
9134 ParamTypes[1] = T;
9135 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9136 /*IsAssignmentOperator=*/true);
9137
9139 // volatile T& operator=(volatile T&, T)
9140 ParamTypes[0] = S.Context.getLValueReferenceType(
9142 Args[0]));
9143 ParamTypes[1] = T;
9144 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9145 /*IsAssignmentOperator=*/true);
9146 }
9147}
9148
9149/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9150/// if any, found in visible type conversion functions found in ArgExpr's type.
9151static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9152 Qualifiers VRQuals;
9153 CXXRecordDecl *ClassDecl;
9154 if (const MemberPointerType *RHSMPType =
9155 ArgExpr->getType()->getAs<MemberPointerType>())
9156 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9157 else
9158 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9159 if (!ClassDecl) {
9160 // Just to be safe, assume the worst case.
9161 VRQuals.addVolatile();
9162 VRQuals.addRestrict();
9163 return VRQuals;
9164 }
9165 if (!ClassDecl->hasDefinition())
9166 return VRQuals;
9167
9168 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9169 if (isa<UsingShadowDecl>(D))
9170 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9171 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9172 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9173 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9174 CanTy = ResTypeRef->getPointeeType();
9175 // Need to go down the pointer/mempointer chain and add qualifiers
9176 // as see them.
9177 bool done = false;
9178 while (!done) {
9179 if (CanTy.isRestrictQualified())
9180 VRQuals.addRestrict();
9181 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9182 CanTy = ResTypePtr->getPointeeType();
9183 else if (const MemberPointerType *ResTypeMPtr =
9184 CanTy->getAs<MemberPointerType>())
9185 CanTy = ResTypeMPtr->getPointeeType();
9186 else
9187 done = true;
9188 if (CanTy.isVolatileQualified())
9189 VRQuals.addVolatile();
9190 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9191 return VRQuals;
9192 }
9193 }
9194 }
9195 return VRQuals;
9196}
9197
9198// Note: We're currently only handling qualifiers that are meaningful for the
9199// LHS of compound assignment overloading.
9201 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9202 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9203 // _Atomic
9204 if (Available.hasAtomic()) {
9205 Available.removeAtomic();
9206 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9207 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9208 return;
9209 }
9210
9211 // volatile
9212 if (Available.hasVolatile()) {
9213 Available.removeVolatile();
9214 assert(!Applied.hasVolatile());
9215 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9216 Callback);
9217 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9218 return;
9219 }
9220
9221 Callback(Applied);
9222}
9223
9225 QualifiersAndAtomic Quals,
9226 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9228 Callback);
9229}
9230
9232 QualifiersAndAtomic Quals,
9233 Sema &S) {
9234 if (Quals.hasAtomic())
9236 if (Quals.hasVolatile())
9239}
9240
9241namespace {
9242
9243/// Helper class to manage the addition of builtin operator overload
9244/// candidates. It provides shared state and utility methods used throughout
9245/// the process, as well as a helper method to add each group of builtin
9246/// operator overloads from the standard to a candidate set.
9247class BuiltinOperatorOverloadBuilder {
9248 // Common instance state available to all overload candidate addition methods.
9249 Sema &S;
9250 ArrayRef<Expr *> Args;
9251 QualifiersAndAtomic VisibleTypeConversionsQuals;
9252 bool HasArithmeticOrEnumeralCandidateType;
9253 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9254 OverloadCandidateSet &CandidateSet;
9255
9256 static constexpr int ArithmeticTypesCap = 26;
9257 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9258
9259 // Define some indices used to iterate over the arithmetic types in
9260 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9261 // types are that preserved by promotion (C++ [over.built]p2).
9262 unsigned FirstIntegralType,
9263 LastIntegralType;
9264 unsigned FirstPromotedIntegralType,
9265 LastPromotedIntegralType;
9266 unsigned FirstPromotedArithmeticType,
9267 LastPromotedArithmeticType;
9268 unsigned NumArithmeticTypes;
9269
9270 void InitArithmeticTypes() {
9271 // Start of promoted types.
9272 FirstPromotedArithmeticType = 0;
9273 ArithmeticTypes.push_back(S.Context.FloatTy);
9274 ArithmeticTypes.push_back(S.Context.DoubleTy);
9275 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9277 ArithmeticTypes.push_back(S.Context.Float128Ty);
9279 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9280
9281 // Start of integral types.
9282 FirstIntegralType = ArithmeticTypes.size();
9283 FirstPromotedIntegralType = ArithmeticTypes.size();
9284 ArithmeticTypes.push_back(S.Context.IntTy);
9285 ArithmeticTypes.push_back(S.Context.LongTy);
9286 ArithmeticTypes.push_back(S.Context.LongLongTy);
9290 ArithmeticTypes.push_back(S.Context.Int128Ty);
9291 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9292 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9293 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9297 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9298
9299 /// We add candidates for the unique, unqualified _BitInt types present in
9300 /// the candidate type set. The candidate set already handled ensuring the
9301 /// type is unqualified and canonical, but because we're adding from N
9302 /// different sets, we need to do some extra work to unique things. Insert
9303 /// the candidates into a unique set, then move from that set into the list
9304 /// of arithmetic types.
9305 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9306 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9307 for (QualType BitTy : Candidate.bitint_types())
9308 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9309 }
9310 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9311 LastPromotedIntegralType = ArithmeticTypes.size();
9312 LastPromotedArithmeticType = ArithmeticTypes.size();
9313 // End of promoted types.
9314
9315 ArithmeticTypes.push_back(S.Context.BoolTy);
9316 ArithmeticTypes.push_back(S.Context.CharTy);
9317 ArithmeticTypes.push_back(S.Context.WCharTy);
9318 if (S.Context.getLangOpts().Char8)
9319 ArithmeticTypes.push_back(S.Context.Char8Ty);
9320 ArithmeticTypes.push_back(S.Context.Char16Ty);
9321 ArithmeticTypes.push_back(S.Context.Char32Ty);
9322 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9323 ArithmeticTypes.push_back(S.Context.ShortTy);
9324 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9325 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9326 LastIntegralType = ArithmeticTypes.size();
9327 NumArithmeticTypes = ArithmeticTypes.size();
9328 // End of integral types.
9329 // FIXME: What about complex? What about half?
9330
9331 // We don't know for sure how many bit-precise candidates were involved, so
9332 // we subtract those from the total when testing whether we're under the
9333 // cap or not.
9334 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9335 ArithmeticTypesCap &&
9336 "Enough inline storage for all arithmetic types.");
9337 }
9338
9339 /// Helper method to factor out the common pattern of adding overloads
9340 /// for '++' and '--' builtin operators.
9341 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9342 bool HasVolatile,
9343 bool HasRestrict) {
9344 QualType ParamTypes[2] = {
9345 S.Context.getLValueReferenceType(CandidateTy),
9346 S.Context.IntTy
9347 };
9348
9349 // Non-volatile version.
9350 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9351
9352 // Use a heuristic to reduce number of builtin candidates in the set:
9353 // add volatile version only if there are conversions to a volatile type.
9354 if (HasVolatile) {
9355 ParamTypes[0] =
9357 S.Context.getVolatileType(CandidateTy));
9358 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9359 }
9360
9361 // Add restrict version only if there are conversions to a restrict type
9362 // and our candidate type is a non-restrict-qualified pointer.
9363 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9364 !CandidateTy.isRestrictQualified()) {
9365 ParamTypes[0]
9368 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9369
9370 if (HasVolatile) {
9371 ParamTypes[0]
9373 S.Context.getCVRQualifiedType(CandidateTy,
9376 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9377 }
9378 }
9379
9380 }
9381
9382 /// Helper to add an overload candidate for a binary builtin with types \p L
9383 /// and \p R.
9384 void AddCandidate(QualType L, QualType R) {
9385 QualType LandR[2] = {L, R};
9386 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9387 }
9388
9389public:
9390 BuiltinOperatorOverloadBuilder(
9391 Sema &S, ArrayRef<Expr *> Args,
9392 QualifiersAndAtomic VisibleTypeConversionsQuals,
9393 bool HasArithmeticOrEnumeralCandidateType,
9394 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9395 OverloadCandidateSet &CandidateSet)
9396 : S(S), Args(Args),
9397 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9398 HasArithmeticOrEnumeralCandidateType(
9399 HasArithmeticOrEnumeralCandidateType),
9400 CandidateTypes(CandidateTypes),
9401 CandidateSet(CandidateSet) {
9402
9403 InitArithmeticTypes();
9404 }
9405
9406 // Increment is deprecated for bool since C++17.
9407 //
9408 // C++ [over.built]p3:
9409 //
9410 // For every pair (T, VQ), where T is an arithmetic type other
9411 // than bool, and VQ is either volatile or empty, there exist
9412 // candidate operator functions of the form
9413 //
9414 // VQ T& operator++(VQ T&);
9415 // T operator++(VQ T&, int);
9416 //
9417 // C++ [over.built]p4:
9418 //
9419 // For every pair (T, VQ), where T is an arithmetic type other
9420 // than bool, and VQ is either volatile or empty, there exist
9421 // candidate operator functions of the form
9422 //
9423 // VQ T& operator--(VQ T&);
9424 // T operator--(VQ T&, int);
9425 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9426 if (!HasArithmeticOrEnumeralCandidateType)
9427 return;
9428
9429 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9430 const auto TypeOfT = ArithmeticTypes[Arith];
9431 if (TypeOfT == S.Context.BoolTy) {
9432 if (Op == OO_MinusMinus)
9433 continue;
9434 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9435 continue;
9436 }
9437 addPlusPlusMinusMinusStyleOverloads(
9438 TypeOfT,
9439 VisibleTypeConversionsQuals.hasVolatile(),
9440 VisibleTypeConversionsQuals.hasRestrict());
9441 }
9442 }
9443
9444 // C++ [over.built]p5:
9445 //
9446 // For every pair (T, VQ), where T is a cv-qualified or
9447 // cv-unqualified object type, and VQ is either volatile or
9448 // empty, there exist candidate operator functions of the form
9449 //
9450 // T*VQ& operator++(T*VQ&);
9451 // T*VQ& operator--(T*VQ&);
9452 // T* operator++(T*VQ&, int);
9453 // T* operator--(T*VQ&, int);
9454 void addPlusPlusMinusMinusPointerOverloads() {
9455 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9456 // Skip pointer types that aren't pointers to object types.
9457 if (!PtrTy->getPointeeType()->isObjectType())
9458 continue;
9459
9460 addPlusPlusMinusMinusStyleOverloads(
9461 PtrTy,
9462 (!PtrTy.isVolatileQualified() &&
9463 VisibleTypeConversionsQuals.hasVolatile()),
9464 (!PtrTy.isRestrictQualified() &&
9465 VisibleTypeConversionsQuals.hasRestrict()));
9466 }
9467 }
9468
9469 // C++ [over.built]p6:
9470 // For every cv-qualified or cv-unqualified object type T, there
9471 // exist candidate operator functions of the form
9472 //
9473 // T& operator*(T*);
9474 //
9475 // C++ [over.built]p7:
9476 // For every function type T that does not have cv-qualifiers or a
9477 // ref-qualifier, there exist candidate operator functions of the form
9478 // T& operator*(T*);
9479 void addUnaryStarPointerOverloads() {
9480 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9481 QualType PointeeTy = ParamTy->getPointeeType();
9482 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9483 continue;
9484
9485 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9486 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9487 continue;
9488
9489 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9490 }
9491 }
9492
9493 // C++ [over.built]p9:
9494 // For every promoted arithmetic type T, there exist candidate
9495 // operator functions of the form
9496 //
9497 // T operator+(T);
9498 // T operator-(T);
9499 void addUnaryPlusOrMinusArithmeticOverloads() {
9500 if (!HasArithmeticOrEnumeralCandidateType)
9501 return;
9502
9503 for (unsigned Arith = FirstPromotedArithmeticType;
9504 Arith < LastPromotedArithmeticType; ++Arith) {
9505 QualType ArithTy = ArithmeticTypes[Arith];
9506 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9507 }
9508
9509 // Extension: We also add these operators for vector types.
9510 for (QualType VecTy : CandidateTypes[0].vector_types())
9511 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9512 }
9513
9514 // C++ [over.built]p8:
9515 // For every type T, there exist candidate operator functions of
9516 // the form
9517 //
9518 // T* operator+(T*);
9519 void addUnaryPlusPointerOverloads() {
9520 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9521 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9522 }
9523
9524 // C++ [over.built]p10:
9525 // For every promoted integral type T, there exist candidate
9526 // operator functions of the form
9527 //
9528 // T operator~(T);
9529 void addUnaryTildePromotedIntegralOverloads() {
9530 if (!HasArithmeticOrEnumeralCandidateType)
9531 return;
9532
9533 for (unsigned Int = FirstPromotedIntegralType;
9534 Int < LastPromotedIntegralType; ++Int) {
9535 QualType IntTy = ArithmeticTypes[Int];
9536 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9537 }
9538
9539 // Extension: We also add this operator for vector types.
9540 for (QualType VecTy : CandidateTypes[0].vector_types())
9541 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9542 }
9543
9544 // C++ [over.match.oper]p16:
9545 // For every pointer to member type T or type std::nullptr_t, there
9546 // exist candidate operator functions of the form
9547 //
9548 // bool operator==(T,T);
9549 // bool operator!=(T,T);
9550 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9551 /// Set of (canonical) types that we've already handled.
9552 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9553
9554 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9555 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9556 // Don't add the same builtin candidate twice.
9557 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9558 continue;
9559
9560 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9561 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9562 }
9563
9564 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9566 if (AddedTypes.insert(NullPtrTy).second) {
9567 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9568 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9569 }
9570 }
9571 }
9572 }
9573
9574 // C++ [over.built]p15:
9575 //
9576 // For every T, where T is an enumeration type or a pointer type,
9577 // there exist candidate operator functions of the form
9578 //
9579 // bool operator<(T, T);
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 // R operator<=>(T, T)
9586 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9587 // C++ [over.match.oper]p3:
9588 // [...]the built-in candidates include all of the candidate operator
9589 // functions defined in 13.6 that, compared to the given operator, [...]
9590 // do not have the same parameter-type-list as any non-template non-member
9591 // candidate.
9592 //
9593 // Note that in practice, this only affects enumeration types because there
9594 // aren't any built-in candidates of record type, and a user-defined operator
9595 // must have an operand of record or enumeration type. Also, the only other
9596 // overloaded operator with enumeration arguments, operator=,
9597 // cannot be overloaded for enumeration types, so this is the only place
9598 // where we must suppress candidates like this.
9599 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9600 UserDefinedBinaryOperators;
9601
9602 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9603 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9604 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9605 CEnd = CandidateSet.end();
9606 C != CEnd; ++C) {
9607 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9608 continue;
9609
9610 if (C->Function->isFunctionTemplateSpecialization())
9611 continue;
9612
9613 // We interpret "same parameter-type-list" as applying to the
9614 // "synthesized candidate, with the order of the two parameters
9615 // reversed", not to the original function.
9616 bool Reversed = C->isReversed();
9617 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9618 ->getType()
9619 .getUnqualifiedType();
9620 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9621 ->getType()
9622 .getUnqualifiedType();
9623
9624 // Skip if either parameter isn't of enumeral type.
9625 if (!FirstParamType->isEnumeralType() ||
9626 !SecondParamType->isEnumeralType())
9627 continue;
9628
9629 // Add this operator to the set of known user-defined operators.
9630 UserDefinedBinaryOperators.insert(
9631 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9632 S.Context.getCanonicalType(SecondParamType)));
9633 }
9634 }
9635 }
9636
9637 /// Set of (canonical) types that we've already handled.
9638 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9639
9640 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9641 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9642 // Don't add the same builtin candidate twice.
9643 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9644 continue;
9645 if (IsSpaceship && PtrTy->isFunctionPointerType())
9646 continue;
9647
9648 QualType ParamTypes[2] = {PtrTy, PtrTy};
9649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9650 }
9651 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9652 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9653
9654 // Don't add the same builtin candidate twice, or if a user defined
9655 // candidate exists.
9656 if (!AddedTypes.insert(CanonType).second ||
9657 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9658 CanonType)))
9659 continue;
9660 QualType ParamTypes[2] = {EnumTy, EnumTy};
9661 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9662 }
9663 }
9664 }
9665
9666 // C++ [over.built]p13:
9667 //
9668 // For every cv-qualified or cv-unqualified object type T
9669 // there exist candidate operator functions of the form
9670 //
9671 // T* operator+(T*, ptrdiff_t);
9672 // T& operator[](T*, ptrdiff_t); [BELOW]
9673 // T* operator-(T*, ptrdiff_t);
9674 // T* operator+(ptrdiff_t, T*);
9675 // T& operator[](ptrdiff_t, T*); [BELOW]
9676 //
9677 // C++ [over.built]p14:
9678 //
9679 // For every T, where T is a pointer to object type, there
9680 // exist candidate operator functions of the form
9681 //
9682 // ptrdiff_t operator-(T, T);
9683 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9684 /// Set of (canonical) types that we've already handled.
9685 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9686
9687 for (int Arg = 0; Arg < 2; ++Arg) {
9688 QualType AsymmetricParamTypes[2] = {
9691 };
9692 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9693 QualType PointeeTy = PtrTy->getPointeeType();
9694 if (!PointeeTy->isObjectType())
9695 continue;
9696
9697 AsymmetricParamTypes[Arg] = PtrTy;
9698 if (Arg == 0 || Op == OO_Plus) {
9699 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9700 // T* operator+(ptrdiff_t, T*);
9701 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9702 }
9703 if (Op == OO_Minus) {
9704 // ptrdiff_t operator-(T, T);
9705 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9706 continue;
9707
9708 QualType ParamTypes[2] = {PtrTy, PtrTy};
9709 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9710 }
9711 }
9712 }
9713 }
9714
9715 // C++ [over.built]p12:
9716 //
9717 // For every pair of promoted arithmetic types L and R, there
9718 // exist candidate operator functions of the form
9719 //
9720 // LR operator*(L, R);
9721 // LR operator/(L, R);
9722 // LR operator+(L, R);
9723 // LR operator-(L, R);
9724 // bool 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 //
9731 // where LR is the result of the usual arithmetic conversions
9732 // between types L and R.
9733 //
9734 // C++ [over.built]p24:
9735 //
9736 // For every pair of promoted arithmetic types L and R, there exist
9737 // candidate operator functions of the form
9738 //
9739 // LR operator?(bool, L, R);
9740 //
9741 // where LR is the result of the usual arithmetic conversions
9742 // between types L and R.
9743 // Our candidates ignore the first parameter.
9744 void addGenericBinaryArithmeticOverloads() {
9745 if (!HasArithmeticOrEnumeralCandidateType)
9746 return;
9747
9748 for (unsigned Left = FirstPromotedArithmeticType;
9749 Left < LastPromotedArithmeticType; ++Left) {
9750 for (unsigned Right = FirstPromotedArithmeticType;
9751 Right < LastPromotedArithmeticType; ++Right) {
9752 QualType LandR[2] = { ArithmeticTypes[Left],
9753 ArithmeticTypes[Right] };
9754 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9755 }
9756 }
9757
9758 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9759 // conditional operator for vector types.
9760 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9761 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9762 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9763 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9764 }
9765 }
9766
9767 /// Add binary operator overloads for each candidate matrix type M1, M2:
9768 /// * (M1, M1) -> M1
9769 /// * (M1, M1.getElementType()) -> M1
9770 /// * (M2.getElementType(), M2) -> M2
9771 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9772 void addMatrixBinaryArithmeticOverloads() {
9773 if (!HasArithmeticOrEnumeralCandidateType)
9774 return;
9775
9776 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9777 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9778 AddCandidate(M1, M1);
9779 }
9780
9781 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9782 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9783 if (!CandidateTypes[0].containsMatrixType(M2))
9784 AddCandidate(M2, M2);
9785 }
9786 }
9787
9788 // C++2a [over.built]p14:
9789 //
9790 // For every integral type T there exists a candidate operator function
9791 // of the form
9792 //
9793 // std::strong_ordering operator<=>(T, T)
9794 //
9795 // C++2a [over.built]p15:
9796 //
9797 // For every pair of floating-point types L and R, there exists a candidate
9798 // operator function of the form
9799 //
9800 // std::partial_ordering operator<=>(L, R);
9801 //
9802 // FIXME: The current specification for integral types doesn't play nice with
9803 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9804 // comparisons. Under the current spec this can lead to ambiguity during
9805 // overload resolution. For example:
9806 //
9807 // enum A : int {a};
9808 // auto x = (a <=> (long)42);
9809 //
9810 // error: call is ambiguous for arguments 'A' and 'long'.
9811 // note: candidate operator<=>(int, int)
9812 // note: candidate operator<=>(long, long)
9813 //
9814 // To avoid this error, this function deviates from the specification and adds
9815 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9816 // arithmetic types (the same as the generic relational overloads).
9817 //
9818 // For now this function acts as a placeholder.
9819 void addThreeWayArithmeticOverloads() {
9820 addGenericBinaryArithmeticOverloads();
9821 }
9822
9823 // C++ [over.built]p17:
9824 //
9825 // For every pair of promoted integral types L and R, there
9826 // exist candidate operator functions of the form
9827 //
9828 // LR operator%(L, R);
9829 // LR operator&(L, R);
9830 // LR operator^(L, R);
9831 // LR operator|(L, R);
9832 // L operator<<(L, R);
9833 // L operator>>(L, R);
9834 //
9835 // where LR is the result of the usual arithmetic conversions
9836 // between types L and R.
9837 void addBinaryBitwiseArithmeticOverloads() {
9838 if (!HasArithmeticOrEnumeralCandidateType)
9839 return;
9840
9841 for (unsigned Left = FirstPromotedIntegralType;
9842 Left < LastPromotedIntegralType; ++Left) {
9843 for (unsigned Right = FirstPromotedIntegralType;
9844 Right < LastPromotedIntegralType; ++Right) {
9845 QualType LandR[2] = { ArithmeticTypes[Left],
9846 ArithmeticTypes[Right] };
9847 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9848 }
9849 }
9850 }
9851
9852 // C++ [over.built]p20:
9853 //
9854 // For every pair (T, VQ), where T is an enumeration or
9855 // pointer to member type and VQ is either volatile or
9856 // empty, there exist candidate operator functions of the form
9857 //
9858 // VQ T& operator=(VQ T&, T);
9859 void addAssignmentMemberPointerOrEnumeralOverloads() {
9860 /// Set of (canonical) types that we've already handled.
9861 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9862
9863 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9864 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9865 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9866 continue;
9867
9868 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9869 }
9870
9871 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9872 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9873 continue;
9874
9875 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9876 }
9877 }
9878 }
9879
9880 // C++ [over.built]p19:
9881 //
9882 // For every pair (T, VQ), where T is any type and VQ is either
9883 // volatile or empty, there exist candidate operator functions
9884 // of the form
9885 //
9886 // T*VQ& operator=(T*VQ&, T*);
9887 //
9888 // C++ [over.built]p21:
9889 //
9890 // For every pair (T, VQ), where T is a cv-qualified or
9891 // cv-unqualified object type and VQ is either volatile or
9892 // empty, there exist candidate operator functions of the form
9893 //
9894 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9895 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9896 void addAssignmentPointerOverloads(bool isEqualOp) {
9897 /// Set of (canonical) types that we've already handled.
9898 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9899
9900 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9901 // If this is operator=, keep track of the builtin candidates we added.
9902 if (isEqualOp)
9903 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9904 else if (!PtrTy->getPointeeType()->isObjectType())
9905 continue;
9906
9907 // non-volatile version
9908 QualType ParamTypes[2] = {
9910 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9911 };
9912 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9913 /*IsAssignmentOperator=*/ isEqualOp);
9914
9915 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9916 VisibleTypeConversionsQuals.hasVolatile();
9917 if (NeedVolatile) {
9918 // volatile version
9919 ParamTypes[0] =
9921 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9922 /*IsAssignmentOperator=*/isEqualOp);
9923 }
9924
9925 if (!PtrTy.isRestrictQualified() &&
9926 VisibleTypeConversionsQuals.hasRestrict()) {
9927 // restrict version
9928 ParamTypes[0] =
9930 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9931 /*IsAssignmentOperator=*/isEqualOp);
9932
9933 if (NeedVolatile) {
9934 // volatile restrict version
9935 ParamTypes[0] =
9938 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9939 /*IsAssignmentOperator=*/isEqualOp);
9940 }
9941 }
9942 }
9943
9944 if (isEqualOp) {
9945 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9946 // Make sure we don't add the same candidate twice.
9947 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9948 continue;
9949
9950 QualType ParamTypes[2] = {
9952 PtrTy,
9953 };
9954
9955 // non-volatile version
9956 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9957 /*IsAssignmentOperator=*/true);
9958
9959 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9960 VisibleTypeConversionsQuals.hasVolatile();
9961 if (NeedVolatile) {
9962 // volatile version
9963 ParamTypes[0] = S.Context.getLValueReferenceType(
9964 S.Context.getVolatileType(PtrTy));
9965 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9966 /*IsAssignmentOperator=*/true);
9967 }
9968
9969 if (!PtrTy.isRestrictQualified() &&
9970 VisibleTypeConversionsQuals.hasRestrict()) {
9971 // restrict version
9972 ParamTypes[0] = S.Context.getLValueReferenceType(
9973 S.Context.getRestrictType(PtrTy));
9974 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9975 /*IsAssignmentOperator=*/true);
9976
9977 if (NeedVolatile) {
9978 // volatile restrict version
9979 ParamTypes[0] =
9982 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9983 /*IsAssignmentOperator=*/true);
9984 }
9985 }
9986 }
9987 }
9988 }
9989
9990 // C++ [over.built]p18:
9991 //
9992 // For every triple (L, VQ, R), where L is an arithmetic type,
9993 // VQ is either volatile or empty, and R is a promoted
9994 // arithmetic type, there exist candidate operator functions of
9995 // the form
9996 //
9997 // VQ L& operator=(VQ L&, R);
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 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10003 if (!HasArithmeticOrEnumeralCandidateType)
10004 return;
10005
10006 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10007 for (unsigned Right = FirstPromotedArithmeticType;
10008 Right < LastPromotedArithmeticType; ++Right) {
10009 QualType ParamTypes[2];
10010 ParamTypes[1] = ArithmeticTypes[Right];
10012 S, ArithmeticTypes[Left], Args[0]);
10013
10015 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10016 ParamTypes[0] =
10017 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10018 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10019 /*IsAssignmentOperator=*/isEqualOp);
10020 });
10021 }
10022 }
10023
10024 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10025 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10026 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10027 QualType ParamTypes[2];
10028 ParamTypes[1] = Vec2Ty;
10029 // Add this built-in operator as a candidate (VQ is empty).
10030 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10031 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10032 /*IsAssignmentOperator=*/isEqualOp);
10033
10034 // Add this built-in operator as a candidate (VQ is 'volatile').
10035 if (VisibleTypeConversionsQuals.hasVolatile()) {
10036 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10037 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10038 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10039 /*IsAssignmentOperator=*/isEqualOp);
10040 }
10041 }
10042 }
10043
10044 // C++ [over.built]p22:
10045 //
10046 // For every triple (L, VQ, R), where L is an integral type, VQ
10047 // is either volatile or empty, and R is a promoted integral
10048 // type, there exist candidate operator functions of the form
10049 //
10050 // VQ L& operator%=(VQ L&, R);
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 void addAssignmentIntegralOverloads() {
10057 if (!HasArithmeticOrEnumeralCandidateType)
10058 return;
10059
10060 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10061 for (unsigned Right = FirstPromotedIntegralType;
10062 Right < LastPromotedIntegralType; ++Right) {
10063 QualType ParamTypes[2];
10064 ParamTypes[1] = ArithmeticTypes[Right];
10066 S, ArithmeticTypes[Left], Args[0]);
10067
10069 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10070 ParamTypes[0] =
10071 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10072 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10073 });
10074 }
10075 }
10076 }
10077
10078 // C++ [over.operator]p23:
10079 //
10080 // There also exist candidate operator functions of the form
10081 //
10082 // bool operator!(bool);
10083 // bool operator&&(bool, bool);
10084 // bool operator||(bool, bool);
10085 void addExclaimOverload() {
10086 QualType ParamTy = S.Context.BoolTy;
10087 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10088 /*IsAssignmentOperator=*/false,
10089 /*NumContextualBoolArguments=*/1);
10090 }
10091 void addAmpAmpOrPipePipeOverload() {
10092 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10093 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10094 /*IsAssignmentOperator=*/false,
10095 /*NumContextualBoolArguments=*/2);
10096 }
10097
10098 // C++ [over.built]p13:
10099 //
10100 // For every cv-qualified or cv-unqualified object type T there
10101 // exist candidate operator functions of the form
10102 //
10103 // T* operator+(T*, ptrdiff_t); [ABOVE]
10104 // T& operator[](T*, ptrdiff_t);
10105 // T* operator-(T*, ptrdiff_t); [ABOVE]
10106 // T* operator+(ptrdiff_t, T*); [ABOVE]
10107 // T& operator[](ptrdiff_t, T*);
10108 void addSubscriptOverloads() {
10109 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10110 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10111 QualType PointeeType = PtrTy->getPointeeType();
10112 if (!PointeeType->isObjectType())
10113 continue;
10114
10115 // T& operator[](T*, ptrdiff_t)
10116 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10117 }
10118
10119 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10120 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10121 QualType PointeeType = PtrTy->getPointeeType();
10122 if (!PointeeType->isObjectType())
10123 continue;
10124
10125 // T& operator[](ptrdiff_t, T*)
10126 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10127 }
10128 }
10129
10130 // C++ [over.built]p11:
10131 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10132 // C1 is the same type as C2 or is a derived class of C2, T is an object
10133 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10134 // there exist candidate operator functions of the form
10135 //
10136 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10137 //
10138 // where CV12 is the union of CV1 and CV2.
10139 void addArrowStarOverloads() {
10140 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10141 QualType C1Ty = PtrTy;
10142 QualType C1;
10143 QualifierCollector Q1;
10144 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10145 if (!isa<RecordType>(C1))
10146 continue;
10147 // heuristic to reduce number of builtin candidates in the set.
10148 // Add volatile/restrict version only if there are conversions to a
10149 // volatile/restrict type.
10150 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10151 continue;
10152 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10153 continue;
10154 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10155 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10156 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10157 *D2 = mptr->getMostRecentCXXRecordDecl();
10158 if (!declaresSameEntity(D1, D2) &&
10159 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10160 break;
10161 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10162 // build CV12 T&
10163 QualType T = mptr->getPointeeType();
10164 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10165 T.isVolatileQualified())
10166 continue;
10167 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10168 T.isRestrictQualified())
10169 continue;
10170 T = Q1.apply(S.Context, T);
10171 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10172 }
10173 }
10174 }
10175
10176 // Note that we don't consider the first argument, since it has been
10177 // contextually converted to bool long ago. The candidates below are
10178 // therefore added as binary.
10179 //
10180 // C++ [over.built]p25:
10181 // For every type T, where T is a pointer, pointer-to-member, or scoped
10182 // enumeration type, there exist candidate operator functions of the form
10183 //
10184 // T operator?(bool, T, T);
10185 //
10186 void addConditionalOperatorOverloads() {
10187 /// Set of (canonical) types that we've already handled.
10188 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10189
10190 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10191 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10192 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10193 continue;
10194
10195 QualType ParamTypes[2] = {PtrTy, PtrTy};
10196 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10197 }
10198
10199 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10200 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10201 continue;
10202
10203 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10204 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10205 }
10206
10207 if (S.getLangOpts().CPlusPlus11) {
10208 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10209 if (!EnumTy->castAsCanonical<EnumType>()
10210 ->getOriginalDecl()
10211 ->isScoped())
10212 continue;
10213
10214 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10215 continue;
10216
10217 QualType ParamTypes[2] = {EnumTy, EnumTy};
10218 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10219 }
10220 }
10221 }
10222 }
10223};
10224
10225} // end anonymous namespace
10226
10228 SourceLocation OpLoc,
10229 ArrayRef<Expr *> Args,
10230 OverloadCandidateSet &CandidateSet) {
10231 // Find all of the types that the arguments can convert to, but only
10232 // if the operator we're looking at has built-in operator candidates
10233 // that make use of these types. Also record whether we encounter non-record
10234 // candidate types or either arithmetic or enumeral candidate types.
10235 QualifiersAndAtomic VisibleTypeConversionsQuals;
10236 VisibleTypeConversionsQuals.addConst();
10237 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10238 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10239 if (Args[ArgIdx]->getType()->isAtomicType())
10240 VisibleTypeConversionsQuals.addAtomic();
10241 }
10242
10243 bool HasNonRecordCandidateType = false;
10244 bool HasArithmeticOrEnumeralCandidateType = false;
10246 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10247 CandidateTypes.emplace_back(*this);
10248 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10249 OpLoc,
10250 true,
10251 (Op == OO_Exclaim ||
10252 Op == OO_AmpAmp ||
10253 Op == OO_PipePipe),
10254 VisibleTypeConversionsQuals);
10255 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10256 CandidateTypes[ArgIdx].hasNonRecordTypes();
10257 HasArithmeticOrEnumeralCandidateType =
10258 HasArithmeticOrEnumeralCandidateType ||
10259 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10260 }
10261
10262 // Exit early when no non-record types have been added to the candidate set
10263 // for any of the arguments to the operator.
10264 //
10265 // We can't exit early for !, ||, or &&, since there we have always have
10266 // 'bool' overloads.
10267 if (!HasNonRecordCandidateType &&
10268 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10269 return;
10270
10271 // Setup an object to manage the common state for building overloads.
10272 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10273 VisibleTypeConversionsQuals,
10274 HasArithmeticOrEnumeralCandidateType,
10275 CandidateTypes, CandidateSet);
10276
10277 // Dispatch over the operation to add in only those overloads which apply.
10278 switch (Op) {
10279 case OO_None:
10281 llvm_unreachable("Expected an overloaded operator");
10282
10283 case OO_New:
10284 case OO_Delete:
10285 case OO_Array_New:
10286 case OO_Array_Delete:
10287 case OO_Call:
10288 llvm_unreachable(
10289 "Special operators don't use AddBuiltinOperatorCandidates");
10290
10291 case OO_Comma:
10292 case OO_Arrow:
10293 case OO_Coawait:
10294 // C++ [over.match.oper]p3:
10295 // -- For the operator ',', the unary operator '&', the
10296 // operator '->', or the operator 'co_await', the
10297 // built-in candidates set is empty.
10298 break;
10299
10300 case OO_Plus: // '+' is either unary or binary
10301 if (Args.size() == 1)
10302 OpBuilder.addUnaryPlusPointerOverloads();
10303 [[fallthrough]];
10304
10305 case OO_Minus: // '-' is either unary or binary
10306 if (Args.size() == 1) {
10307 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10308 } else {
10309 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10310 OpBuilder.addGenericBinaryArithmeticOverloads();
10311 OpBuilder.addMatrixBinaryArithmeticOverloads();
10312 }
10313 break;
10314
10315 case OO_Star: // '*' is either unary or binary
10316 if (Args.size() == 1)
10317 OpBuilder.addUnaryStarPointerOverloads();
10318 else {
10319 OpBuilder.addGenericBinaryArithmeticOverloads();
10320 OpBuilder.addMatrixBinaryArithmeticOverloads();
10321 }
10322 break;
10323
10324 case OO_Slash:
10325 OpBuilder.addGenericBinaryArithmeticOverloads();
10326 break;
10327
10328 case OO_PlusPlus:
10329 case OO_MinusMinus:
10330 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10331 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10332 break;
10333
10334 case OO_EqualEqual:
10335 case OO_ExclaimEqual:
10336 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10337 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10338 OpBuilder.addGenericBinaryArithmeticOverloads();
10339 break;
10340
10341 case OO_Less:
10342 case OO_Greater:
10343 case OO_LessEqual:
10344 case OO_GreaterEqual:
10345 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10346 OpBuilder.addGenericBinaryArithmeticOverloads();
10347 break;
10348
10349 case OO_Spaceship:
10350 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10351 OpBuilder.addThreeWayArithmeticOverloads();
10352 break;
10353
10354 case OO_Percent:
10355 case OO_Caret:
10356 case OO_Pipe:
10357 case OO_LessLess:
10358 case OO_GreaterGreater:
10359 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10360 break;
10361
10362 case OO_Amp: // '&' is either unary or binary
10363 if (Args.size() == 1)
10364 // C++ [over.match.oper]p3:
10365 // -- For the operator ',', the unary operator '&', or the
10366 // operator '->', the built-in candidates set is empty.
10367 break;
10368
10369 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10370 break;
10371
10372 case OO_Tilde:
10373 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10374 break;
10375
10376 case OO_Equal:
10377 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10378 [[fallthrough]];
10379
10380 case OO_PlusEqual:
10381 case OO_MinusEqual:
10382 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10383 [[fallthrough]];
10384
10385 case OO_StarEqual:
10386 case OO_SlashEqual:
10387 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10388 break;
10389
10390 case OO_PercentEqual:
10391 case OO_LessLessEqual:
10392 case OO_GreaterGreaterEqual:
10393 case OO_AmpEqual:
10394 case OO_CaretEqual:
10395 case OO_PipeEqual:
10396 OpBuilder.addAssignmentIntegralOverloads();
10397 break;
10398
10399 case OO_Exclaim:
10400 OpBuilder.addExclaimOverload();
10401 break;
10402
10403 case OO_AmpAmp:
10404 case OO_PipePipe:
10405 OpBuilder.addAmpAmpOrPipePipeOverload();
10406 break;
10407
10408 case OO_Subscript:
10409 if (Args.size() == 2)
10410 OpBuilder.addSubscriptOverloads();
10411 break;
10412
10413 case OO_ArrowStar:
10414 OpBuilder.addArrowStarOverloads();
10415 break;
10416
10417 case OO_Conditional:
10418 OpBuilder.addConditionalOperatorOverloads();
10419 OpBuilder.addGenericBinaryArithmeticOverloads();
10420 break;
10421 }
10422}
10423
10424void
10426 SourceLocation Loc,
10427 ArrayRef<Expr *> Args,
10428 TemplateArgumentListInfo *ExplicitTemplateArgs,
10429 OverloadCandidateSet& CandidateSet,
10430 bool PartialOverloading) {
10431 ADLResult Fns;
10432
10433 // FIXME: This approach for uniquing ADL results (and removing
10434 // redundant candidates from the set) relies on pointer-equality,
10435 // which means we need to key off the canonical decl. However,
10436 // always going back to the canonical decl might not get us the
10437 // right set of default arguments. What default arguments are
10438 // we supposed to consider on ADL candidates, anyway?
10439
10440 // FIXME: Pass in the explicit template arguments?
10441 ArgumentDependentLookup(Name, Loc, Args, Fns);
10442
10443 ArrayRef<Expr *> ReversedArgs;
10444
10445 // Erase all of the candidates we already knew about.
10446 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10447 CandEnd = CandidateSet.end();
10448 Cand != CandEnd; ++Cand)
10449 if (Cand->Function) {
10450 FunctionDecl *Fn = Cand->Function;
10451 Fns.erase(Fn);
10452 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10453 Fns.erase(FunTmpl);
10454 }
10455
10456 // For each of the ADL candidates we found, add it to the overload
10457 // set.
10458 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10460
10461 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10462 if (ExplicitTemplateArgs)
10463 continue;
10464
10466 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10467 PartialOverloading, /*AllowExplicit=*/true,
10468 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10469 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10471 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10472 /*SuppressUserConversions=*/false, PartialOverloading,
10473 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10474 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10475 }
10476 } else {
10477 auto *FTD = cast<FunctionTemplateDecl>(*I);
10479 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10480 /*SuppressUserConversions=*/false, PartialOverloading,
10481 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10482 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10483 *this, Args, FTD->getTemplatedDecl())) {
10484
10485 // As template candidates are not deduced immediately,
10486 // persist the array in the overload set.
10487 if (ReversedArgs.empty())
10488 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10489
10491 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10492 /*SuppressUserConversions=*/false, PartialOverloading,
10493 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10495 }
10496 }
10497 }
10498}
10499
10500namespace {
10501enum class Comparison { Equal, Better, Worse };
10502}
10503
10504/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10505/// overload resolution.
10506///
10507/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10508/// Cand1's first N enable_if attributes have precisely the same conditions as
10509/// Cand2's first N enable_if attributes (where N = the number of enable_if
10510/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10511///
10512/// Note that you can have a pair of candidates such that Cand1's enable_if
10513/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10514/// worse than Cand1's.
10515static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10516 const FunctionDecl *Cand2) {
10517 // Common case: One (or both) decls don't have enable_if attrs.
10518 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10519 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10520 if (!Cand1Attr || !Cand2Attr) {
10521 if (Cand1Attr == Cand2Attr)
10522 return Comparison::Equal;
10523 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10524 }
10525
10526 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10527 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10528
10529 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10530 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10531 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10532 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10533
10534 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10535 // has fewer enable_if attributes than Cand2, and vice versa.
10536 if (!Cand1A)
10537 return Comparison::Worse;
10538 if (!Cand2A)
10539 return Comparison::Better;
10540
10541 Cand1ID.clear();
10542 Cand2ID.clear();
10543
10544 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10545 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10546 if (Cand1ID != Cand2ID)
10547 return Comparison::Worse;
10548 }
10549
10550 return Comparison::Equal;
10551}
10552
10553static Comparison
10555 const OverloadCandidate &Cand2) {
10556 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10557 !Cand2.Function->isMultiVersion())
10558 return Comparison::Equal;
10559
10560 // If both are invalid, they are equal. If one of them is invalid, the other
10561 // is better.
10562 if (Cand1.Function->isInvalidDecl()) {
10563 if (Cand2.Function->isInvalidDecl())
10564 return Comparison::Equal;
10565 return Comparison::Worse;
10566 }
10567 if (Cand2.Function->isInvalidDecl())
10568 return Comparison::Better;
10569
10570 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10571 // cpu_dispatch, else arbitrarily based on the identifiers.
10572 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10573 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10574 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10575 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10576
10577 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10578 return Comparison::Equal;
10579
10580 if (Cand1CPUDisp && !Cand2CPUDisp)
10581 return Comparison::Better;
10582 if (Cand2CPUDisp && !Cand1CPUDisp)
10583 return Comparison::Worse;
10584
10585 if (Cand1CPUSpec && Cand2CPUSpec) {
10586 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10587 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10588 ? Comparison::Better
10589 : Comparison::Worse;
10590
10591 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10592 FirstDiff = std::mismatch(
10593 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10594 Cand2CPUSpec->cpus_begin(),
10595 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10596 return LHS->getName() == RHS->getName();
10597 });
10598
10599 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10600 "Two different cpu-specific versions should not have the same "
10601 "identifier list, otherwise they'd be the same decl!");
10602 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10603 ? Comparison::Better
10604 : Comparison::Worse;
10605 }
10606 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10607}
10608
10609/// Compute the type of the implicit object parameter for the given function,
10610/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10611/// null QualType if there is a 'matches anything' implicit object parameter.
10612static std::optional<QualType>
10615 return std::nullopt;
10616
10617 auto *M = cast<CXXMethodDecl>(F);
10618 // Static member functions' object parameters match all types.
10619 if (M->isStatic())
10620 return QualType();
10621 return M->getFunctionObjectParameterReferenceType();
10622}
10623
10624// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10625// represent the same entity.
10626static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10627 const FunctionDecl *F2) {
10628 if (declaresSameEntity(F1, F2))
10629 return true;
10630 auto PT1 = F1->getPrimaryTemplate();
10631 auto PT2 = F2->getPrimaryTemplate();
10632 if (PT1 && PT2) {
10633 if (declaresSameEntity(PT1, PT2) ||
10634 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10635 PT2->getInstantiatedFromMemberTemplate()))
10636 return true;
10637 }
10638 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10639 // different functions with same params). Consider removing this (as no test
10640 // fail w/o it).
10641 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10642 if (First) {
10643 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10644 return *T;
10645 }
10646 assert(I < F->getNumParams());
10647 return F->getParamDecl(I++)->getType();
10648 };
10649
10650 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10651 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10652
10653 if (F1NumParams != F2NumParams)
10654 return false;
10655
10656 unsigned I1 = 0, I2 = 0;
10657 for (unsigned I = 0; I != F1NumParams; ++I) {
10658 QualType T1 = NextParam(F1, I1, I == 0);
10659 QualType T2 = NextParam(F2, I2, I == 0);
10660 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10661 if (!Context.hasSameUnqualifiedType(T1, T2))
10662 return false;
10663 }
10664 return true;
10665}
10666
10667/// We're allowed to use constraints partial ordering only if the candidates
10668/// have the same parameter types:
10669/// [over.match.best.general]p2.6
10670/// F1 and F2 are non-template functions with the same
10671/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10673 FunctionDecl *Fn2,
10674 bool IsFn1Reversed,
10675 bool IsFn2Reversed) {
10676 assert(Fn1 && Fn2);
10677 if (Fn1->isVariadic() != Fn2->isVariadic())
10678 return false;
10679
10680 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10681 IsFn1Reversed ^ IsFn2Reversed))
10682 return false;
10683
10684 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10685 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10686 if (Mem1 && Mem2) {
10687 // if they are member functions, both are direct members of the same class,
10688 // and
10689 if (Mem1->getParent() != Mem2->getParent())
10690 return false;
10691 // if both are non-static member functions, they have the same types for
10692 // their object parameters
10693 if (Mem1->isInstance() && Mem2->isInstance() &&
10695 Mem1->getFunctionObjectParameterReferenceType(),
10696 Mem1->getFunctionObjectParameterReferenceType()))
10697 return false;
10698 }
10699 return true;
10700}
10701
10702static FunctionDecl *
10704 bool IsFn1Reversed, bool IsFn2Reversed) {
10705 if (!Fn1 || !Fn2)
10706 return nullptr;
10707
10708 // C++ [temp.constr.order]:
10709 // A non-template function F1 is more partial-ordering-constrained than a
10710 // non-template function F2 if:
10711 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10712 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10713
10714 if (Cand1IsSpecialization || Cand2IsSpecialization)
10715 return nullptr;
10716
10717 // - they have the same non-object-parameter-type-lists, and [...]
10718 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10719 IsFn2Reversed))
10720 return nullptr;
10721
10722 // - the declaration of F1 is more constrained than the declaration of F2.
10723 return S.getMoreConstrainedFunction(Fn1, Fn2);
10724}
10725
10726/// isBetterOverloadCandidate - Determines whether the first overload
10727/// candidate is a better candidate than the second (C++ 13.3.3p1).
10729 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10731 bool PartialOverloading) {
10732 // Define viable functions to be better candidates than non-viable
10733 // functions.
10734 if (!Cand2.Viable)
10735 return Cand1.Viable;
10736 else if (!Cand1.Viable)
10737 return false;
10738
10739 // [CUDA] A function with 'never' preference is marked not viable, therefore
10740 // is never shown up here. The worst preference shown up here is 'wrong side',
10741 // e.g. an H function called by a HD function in device compilation. This is
10742 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10743 // function which is called only by an H function. A deferred diagnostic will
10744 // be triggered if it is emitted. However a wrong-sided function is still
10745 // a viable candidate here.
10746 //
10747 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10748 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10749 // can be emitted, Cand1 is not better than Cand2. This rule should have
10750 // precedence over other rules.
10751 //
10752 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10753 // other rules should be used to determine which is better. This is because
10754 // host/device based overloading resolution is mostly for determining
10755 // viability of a function. If two functions are both viable, other factors
10756 // should take precedence in preference, e.g. the standard-defined preferences
10757 // like argument conversion ranks or enable_if partial-ordering. The
10758 // preference for pass-object-size parameters is probably most similar to a
10759 // type-based-overloading decision and so should take priority.
10760 //
10761 // If other rules cannot determine which is better, CUDA preference will be
10762 // used again to determine which is better.
10763 //
10764 // TODO: Currently IdentifyPreference does not return correct values
10765 // for functions called in global variable initializers due to missing
10766 // correct context about device/host. Therefore we can only enforce this
10767 // rule when there is a caller. We should enforce this rule for functions
10768 // in global variable initializers once proper context is added.
10769 //
10770 // TODO: We can only enable the hostness based overloading resolution when
10771 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10772 // overloading resolution diagnostics.
10773 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10774 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10775 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10776 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10777 bool IsCand1ImplicitHD =
10779 bool IsCand2ImplicitHD =
10781 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10782 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10783 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10784 // The implicit HD function may be a function in a system header which
10785 // is forced by pragma. In device compilation, if we prefer HD candidates
10786 // over wrong-sided candidates, overloading resolution may change, which
10787 // may result in non-deferrable diagnostics. As a workaround, we let
10788 // implicit HD candidates take equal preference as wrong-sided candidates.
10789 // This will preserve the overloading resolution.
10790 // TODO: We still need special handling of implicit HD functions since
10791 // they may incur other diagnostics to be deferred. We should make all
10792 // host/device related diagnostics deferrable and remove special handling
10793 // of implicit HD functions.
10794 auto EmitThreshold =
10795 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10796 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10799 auto Cand1Emittable = P1 > EmitThreshold;
10800 auto Cand2Emittable = P2 > EmitThreshold;
10801 if (Cand1Emittable && !Cand2Emittable)
10802 return true;
10803 if (!Cand1Emittable && Cand2Emittable)
10804 return false;
10805 }
10806 }
10807
10808 // C++ [over.match.best]p1: (Changed in C++23)
10809 //
10810 // -- if F is a static member function, ICS1(F) is defined such
10811 // that ICS1(F) is neither better nor worse than ICS1(G) for
10812 // any function G, and, symmetrically, ICS1(G) is neither
10813 // better nor worse than ICS1(F).
10814 unsigned StartArg = 0;
10815 if (!Cand1.TookAddressOfOverload &&
10817 StartArg = 1;
10818
10819 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10820 // We don't allow incompatible pointer conversions in C++.
10821 if (!S.getLangOpts().CPlusPlus)
10822 return ICS.isStandard() &&
10823 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10824
10825 // The only ill-formed conversion we allow in C++ is the string literal to
10826 // char* conversion, which is only considered ill-formed after C++11.
10827 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10829 };
10830
10831 // Define functions that don't require ill-formed conversions for a given
10832 // argument to be better candidates than functions that do.
10833 unsigned NumArgs = Cand1.Conversions.size();
10834 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10835 bool HasBetterConversion = false;
10836 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10837 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10838 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10839 if (Cand1Bad != Cand2Bad) {
10840 if (Cand1Bad)
10841 return false;
10842 HasBetterConversion = true;
10843 }
10844 }
10845
10846 if (HasBetterConversion)
10847 return true;
10848
10849 // C++ [over.match.best]p1:
10850 // A viable function F1 is defined to be a better function than another
10851 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10852 // conversion sequence than ICSi(F2), and then...
10853 bool HasWorseConversion = false;
10854 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10856 Cand1.Conversions[ArgIdx],
10857 Cand2.Conversions[ArgIdx])) {
10859 // Cand1 has a better conversion sequence.
10860 HasBetterConversion = true;
10861 break;
10862
10864 if (Cand1.Function && Cand2.Function &&
10865 Cand1.isReversed() != Cand2.isReversed() &&
10866 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10867 // Work around large-scale breakage caused by considering reversed
10868 // forms of operator== in C++20:
10869 //
10870 // When comparing a function against a reversed function, if we have a
10871 // better conversion for one argument and a worse conversion for the
10872 // other, the implicit conversion sequences are treated as being equally
10873 // good.
10874 //
10875 // This prevents a comparison function from being considered ambiguous
10876 // with a reversed form that is written in the same way.
10877 //
10878 // We diagnose this as an extension from CreateOverloadedBinOp.
10879 HasWorseConversion = true;
10880 break;
10881 }
10882
10883 // Cand1 can't be better than Cand2.
10884 return false;
10885
10887 // Do nothing.
10888 break;
10889 }
10890 }
10891
10892 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10893 // ICSj(F2), or, if not that,
10894 if (HasBetterConversion && !HasWorseConversion)
10895 return true;
10896
10897 // -- the context is an initialization by user-defined conversion
10898 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10899 // from the return type of F1 to the destination type (i.e.,
10900 // the type of the entity being initialized) is a better
10901 // conversion sequence than the standard conversion sequence
10902 // from the return type of F2 to the destination type.
10904 Cand1.Function && Cand2.Function &&
10907
10908 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10909 // First check whether we prefer one of the conversion functions over the
10910 // other. This only distinguishes the results in non-standard, extension
10911 // cases such as the conversion from a lambda closure type to a function
10912 // pointer or block.
10917 Cand1.FinalConversion,
10918 Cand2.FinalConversion);
10919
10922
10923 // FIXME: Compare kind of reference binding if conversion functions
10924 // convert to a reference type used in direct reference binding, per
10925 // C++14 [over.match.best]p1 section 2 bullet 3.
10926 }
10927
10928 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10929 // as combined with the resolution to CWG issue 243.
10930 //
10931 // When the context is initialization by constructor ([over.match.ctor] or
10932 // either phase of [over.match.list]), a constructor is preferred over
10933 // a conversion function.
10934 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10935 Cand1.Function && Cand2.Function &&
10938 return isa<CXXConstructorDecl>(Cand1.Function);
10939
10940 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10941 return Cand2.StrictPackMatch;
10942
10943 // -- F1 is a non-template function and F2 is a function template
10944 // specialization, or, if not that,
10945 bool Cand1IsSpecialization = Cand1.Function &&
10947 bool Cand2IsSpecialization = Cand2.Function &&
10949 if (Cand1IsSpecialization != Cand2IsSpecialization)
10950 return Cand2IsSpecialization;
10951
10952 // -- F1 and F2 are function template specializations, and the function
10953 // template for F1 is more specialized than the template for F2
10954 // according to the partial ordering rules described in 14.5.5.2, or,
10955 // if not that,
10956 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10957 const auto *Obj1Context =
10958 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10959 const auto *Obj2Context =
10960 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10961 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10963 Cand2.Function->getPrimaryTemplate(), Loc,
10965 : TPOC_Call,
10967 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
10968 : QualType{},
10969 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
10970 : QualType{},
10971 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10972 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10973 }
10974 }
10975
10976 // -— F1 and F2 are non-template functions and F1 is more
10977 // partial-ordering-constrained than F2 [...],
10979 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10980 Cand2.isReversed());
10981 F && F == Cand1.Function)
10982 return true;
10983
10984 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10985 // class B of D, and for all arguments the corresponding parameters of
10986 // F1 and F2 have the same type.
10987 // FIXME: Implement the "all parameters have the same type" check.
10988 bool Cand1IsInherited =
10989 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10990 bool Cand2IsInherited =
10991 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10992 if (Cand1IsInherited != Cand2IsInherited)
10993 return Cand2IsInherited;
10994 else if (Cand1IsInherited) {
10995 assert(Cand2IsInherited);
10996 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10997 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10998 if (Cand1Class->isDerivedFrom(Cand2Class))
10999 return true;
11000 if (Cand2Class->isDerivedFrom(Cand1Class))
11001 return false;
11002 // Inherited from sibling base classes: still ambiguous.
11003 }
11004
11005 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11006 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11007 // with reversed order of parameters and F1 is not
11008 //
11009 // We rank reversed + different operator as worse than just reversed, but
11010 // that comparison can never happen, because we only consider reversing for
11011 // the maximally-rewritten operator (== or <=>).
11012 if (Cand1.RewriteKind != Cand2.RewriteKind)
11013 return Cand1.RewriteKind < Cand2.RewriteKind;
11014
11015 // Check C++17 tie-breakers for deduction guides.
11016 {
11017 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11018 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11019 if (Guide1 && Guide2) {
11020 // -- F1 is generated from a deduction-guide and F2 is not
11021 if (Guide1->isImplicit() != Guide2->isImplicit())
11022 return Guide2->isImplicit();
11023
11024 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11025 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11026 return true;
11027 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11028 return false;
11029
11030 // --F1 is generated from a non-template constructor and F2 is generated
11031 // from a constructor template
11032 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11033 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11034 if (Constructor1 && Constructor2) {
11035 bool isC1Templated = Constructor1->getTemplatedKind() !=
11037 bool isC2Templated = Constructor2->getTemplatedKind() !=
11039 if (isC1Templated != isC2Templated)
11040 return isC2Templated;
11041 }
11042 }
11043 }
11044
11045 // Check for enable_if value-based overload resolution.
11046 if (Cand1.Function && Cand2.Function) {
11047 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11048 if (Cmp != Comparison::Equal)
11049 return Cmp == Comparison::Better;
11050 }
11051
11052 bool HasPS1 = Cand1.Function != nullptr &&
11054 bool HasPS2 = Cand2.Function != nullptr &&
11056 if (HasPS1 != HasPS2 && HasPS1)
11057 return true;
11058
11059 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11060 if (MV == Comparison::Better)
11061 return true;
11062 if (MV == Comparison::Worse)
11063 return false;
11064
11065 // If other rules cannot determine which is better, CUDA preference is used
11066 // to determine which is better.
11067 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11068 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11069 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11070 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11071 }
11072
11073 // General member function overloading is handled above, so this only handles
11074 // constructors with address spaces.
11075 // This only handles address spaces since C++ has no other
11076 // qualifier that can be used with constructors.
11077 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11078 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11079 if (CD1 && CD2) {
11080 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11081 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11082 if (AS1 != AS2) {
11084 return true;
11086 return false;
11087 }
11088 }
11089
11090 return false;
11091}
11092
11093/// Determine whether two declarations are "equivalent" for the purposes of
11094/// name lookup and overload resolution. This applies when the same internal/no
11095/// linkage entity is defined by two modules (probably by textually including
11096/// the same header). In such a case, we don't consider the declarations to
11097/// declare the same entity, but we also don't want lookups with both
11098/// declarations visible to be ambiguous in some cases (this happens when using
11099/// a modularized libstdc++).
11101 const NamedDecl *B) {
11102 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11103 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11104 if (!VA || !VB)
11105 return false;
11106
11107 // The declarations must be declaring the same name as an internal linkage
11108 // entity in different modules.
11109 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11110 VB->getDeclContext()->getRedeclContext()) ||
11111 getOwningModule(VA) == getOwningModule(VB) ||
11112 VA->isExternallyVisible() || VB->isExternallyVisible())
11113 return false;
11114
11115 // Check that the declarations appear to be equivalent.
11116 //
11117 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11118 // For constants and functions, we should check the initializer or body is
11119 // the same. For non-constant variables, we shouldn't allow it at all.
11120 if (Context.hasSameType(VA->getType(), VB->getType()))
11121 return true;
11122
11123 // Enum constants within unnamed enumerations will have different types, but
11124 // may still be similar enough to be interchangeable for our purposes.
11125 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11126 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11127 // Only handle anonymous enums. If the enumerations were named and
11128 // equivalent, they would have been merged to the same type.
11129 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11130 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11131 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11132 !Context.hasSameType(EnumA->getIntegerType(),
11133 EnumB->getIntegerType()))
11134 return false;
11135 // Allow this only if the value is the same for both enumerators.
11136 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11137 }
11138 }
11139
11140 // Nothing else is sufficiently similar.
11141 return false;
11142}
11143
11146 assert(D && "Unknown declaration");
11147 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11148
11149 Module *M = getOwningModule(D);
11150 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11151 << !M << (M ? M->getFullModuleName() : "");
11152
11153 for (auto *E : Equiv) {
11154 Module *M = getOwningModule(E);
11155 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11156 << !M << (M ? M->getFullModuleName() : "");
11157 }
11158}
11159
11162 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11164 static_cast<CNSInfo *>(DeductionFailure.Data)
11165 ->Satisfaction.ContainsErrors;
11166}
11167
11170 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11171 bool PartialOverloading, bool AllowExplicit,
11173 bool AggregateCandidateDeduction) {
11174
11175 auto *C =
11176 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11177
11180 /*AllowObjCConversionOnExplicit=*/false,
11181 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11182 PartialOverloading, AggregateCandidateDeduction},
11184 FoundDecl,
11185 Args,
11186 IsADLCandidate,
11187 PO};
11188
11189 HasDeferredTemplateConstructors |=
11190 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11191}
11192
11194 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11195 CXXRecordDecl *ActingContext, QualType ObjectType,
11196 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11197 bool SuppressUserConversions, bool PartialOverloading,
11199
11200 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11201
11202 auto *C =
11203 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11204
11207 /*AllowObjCConversionOnExplicit=*/false,
11208 /*AllowResultConversion=*/false,
11209 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11210 /*AggregateCandidateDeduction=*/false},
11211 MethodTmpl,
11212 FoundDecl,
11213 Args,
11214 ActingContext,
11215 ObjectClassification,
11216 ObjectType,
11217 PO};
11218}
11219
11222 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11223 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11224 bool AllowResultConversion) {
11225
11226 auto *C =
11227 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11228
11231 AllowObjCConversionOnExplicit, AllowResultConversion,
11232 /*AllowExplicit=*/false,
11233 /*SuppressUserConversions=*/false,
11234 /*PartialOverloading*/ false,
11235 /*AggregateCandidateDeduction=*/false},
11237 FoundDecl,
11238 ActingContext,
11239 From,
11240 ToType};
11241}
11242
11243static void
11246
11248 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11249 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11250 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11251}
11252
11253static void
11257 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11258 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11259 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11260 C.AggregateCandidateDeduction);
11261}
11262
11263static void
11267 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11268 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11269 C.AllowResultConversion);
11270}
11271
11273 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11274 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11275 while (Cand) {
11276 switch (Cand->Kind) {
11279 S, *this,
11280 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11281 break;
11284 S, *this,
11285 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11286 break;
11289 S, *this,
11290 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11291 break;
11292 }
11293 Cand = Cand->Next;
11294 }
11295 FirstDeferredCandidate = nullptr;
11296 DeferredCandidatesCount = 0;
11297}
11298
11300OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11301 Best->Best = true;
11302 if (Best->Function && Best->Function->isDeleted())
11303 return OR_Deleted;
11304 return OR_Success;
11305}
11306
11307void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11309 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11310 // are accepted by both clang and NVCC. However, during a particular
11311 // compilation mode only one call variant is viable. We need to
11312 // exclude non-viable overload candidates from consideration based
11313 // only on their host/device attributes. Specifically, if one
11314 // candidate call is WrongSide and the other is SameSide, we ignore
11315 // the WrongSide candidate.
11316 // We only need to remove wrong-sided candidates here if
11317 // -fgpu-exclude-wrong-side-overloads is off. When
11318 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11319 // uniformly in isBetterOverloadCandidate.
11320 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11321 return;
11322 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11323
11324 bool ContainsSameSideCandidate =
11325 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11326 // Check viable function only.
11327 return Cand->Viable && Cand->Function &&
11328 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11330 });
11331
11332 if (!ContainsSameSideCandidate)
11333 return;
11334
11335 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11336 // Check viable function only to avoid unnecessary data copying/moving.
11337 return Cand->Viable && Cand->Function &&
11338 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11340 };
11341 llvm::erase_if(Candidates, IsWrongSideCandidate);
11342}
11343
11344/// Computes the best viable function (C++ 13.3.3)
11345/// within an overload candidate set.
11346///
11347/// \param Loc The location of the function name (or operator symbol) for
11348/// which overload resolution occurs.
11349///
11350/// \param Best If overload resolution was successful or found a deleted
11351/// function, \p Best points to the candidate function found.
11352///
11353/// \returns The result of overload resolution.
11355 SourceLocation Loc,
11356 iterator &Best) {
11357
11359 DeferredCandidatesCount == 0) &&
11360 "Unexpected deferred template candidates");
11361
11362 bool TwoPhaseResolution =
11363 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11364
11365 if (TwoPhaseResolution) {
11366 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11367 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11368 if (!(HasDeferredTemplateConstructors &&
11369 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11370 return Res;
11371 }
11372 }
11373
11375 return BestViableFunctionImpl(S, Loc, Best);
11376}
11377
11378OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11380
11382 Candidates.reserve(this->Candidates.size());
11383 std::transform(this->Candidates.begin(), this->Candidates.end(),
11384 std::back_inserter(Candidates),
11385 [](OverloadCandidate &Cand) { return &Cand; });
11386
11387 if (S.getLangOpts().CUDA)
11388 CudaExcludeWrongSideCandidates(S, Candidates);
11389
11390 Best = end();
11391 for (auto *Cand : Candidates) {
11392 Cand->Best = false;
11393 if (Cand->Viable) {
11394 if (Best == end() ||
11395 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11396 Best = Cand;
11397 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11398 // This candidate has constraint that we were unable to evaluate because
11399 // it referenced an expression that contained an error. Rather than fall
11400 // back onto a potentially unintended candidate (made worse by
11401 // subsuming constraints), treat this as 'no viable candidate'.
11402 Best = end();
11403 return OR_No_Viable_Function;
11404 }
11405 }
11406
11407 // If we didn't find any viable functions, abort.
11408 if (Best == end())
11409 return OR_No_Viable_Function;
11410
11411 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11412 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11413 PendingBest.push_back(&*Best);
11414 Best->Best = true;
11415
11416 // Make sure that this function is better than every other viable
11417 // function. If not, we have an ambiguity.
11418 while (!PendingBest.empty()) {
11419 auto *Curr = PendingBest.pop_back_val();
11420 for (auto *Cand : Candidates) {
11421 if (Cand->Viable && !Cand->Best &&
11422 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11423 PendingBest.push_back(Cand);
11424 Cand->Best = true;
11425
11427 Curr->Function))
11428 EquivalentCands.push_back(Cand->Function);
11429 else
11430 Best = end();
11431 }
11432 }
11433 }
11434
11435 if (Best == end())
11436 return OR_Ambiguous;
11437
11438 OverloadingResult R = ResultForBestCandidate(Best);
11439
11440 if (!EquivalentCands.empty())
11442 EquivalentCands);
11443 return R;
11444}
11445
11446namespace {
11447
11448enum OverloadCandidateKind {
11449 oc_function,
11450 oc_method,
11451 oc_reversed_binary_operator,
11452 oc_constructor,
11453 oc_implicit_default_constructor,
11454 oc_implicit_copy_constructor,
11455 oc_implicit_move_constructor,
11456 oc_implicit_copy_assignment,
11457 oc_implicit_move_assignment,
11458 oc_implicit_equality_comparison,
11459 oc_inherited_constructor
11460};
11461
11462enum OverloadCandidateSelect {
11463 ocs_non_template,
11464 ocs_template,
11465 ocs_described_template,
11466};
11467
11468static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11469ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11470 const FunctionDecl *Fn,
11472 std::string &Description) {
11473
11474 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11475 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11476 isTemplate = true;
11477 Description = S.getTemplateArgumentBindingsText(
11478 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11479 }
11480
11481 OverloadCandidateSelect Select = [&]() {
11482 if (!Description.empty())
11483 return ocs_described_template;
11484 return isTemplate ? ocs_template : ocs_non_template;
11485 }();
11486
11487 OverloadCandidateKind Kind = [&]() {
11488 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11489 return oc_implicit_equality_comparison;
11490
11491 if (CRK & CRK_Reversed)
11492 return oc_reversed_binary_operator;
11493
11494 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11495 if (!Ctor->isImplicit()) {
11497 return oc_inherited_constructor;
11498 else
11499 return oc_constructor;
11500 }
11501
11502 if (Ctor->isDefaultConstructor())
11503 return oc_implicit_default_constructor;
11504
11505 if (Ctor->isMoveConstructor())
11506 return oc_implicit_move_constructor;
11507
11508 assert(Ctor->isCopyConstructor() &&
11509 "unexpected sort of implicit constructor");
11510 return oc_implicit_copy_constructor;
11511 }
11512
11513 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11514 // This actually gets spelled 'candidate function' for now, but
11515 // it doesn't hurt to split it out.
11516 if (!Meth->isImplicit())
11517 return oc_method;
11518
11519 if (Meth->isMoveAssignmentOperator())
11520 return oc_implicit_move_assignment;
11521
11522 if (Meth->isCopyAssignmentOperator())
11523 return oc_implicit_copy_assignment;
11524
11525 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11526 return oc_method;
11527 }
11528
11529 return oc_function;
11530 }();
11531
11532 return std::make_pair(Kind, Select);
11533}
11534
11535void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11536 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11537 // set.
11538 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11539 S.Diag(FoundDecl->getLocation(),
11540 diag::note_ovl_candidate_inherited_constructor)
11541 << Shadow->getNominatedBaseClass();
11542}
11543
11544} // end anonymous namespace
11545
11547 const FunctionDecl *FD) {
11548 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11549 bool AlwaysTrue;
11550 if (EnableIf->getCond()->isValueDependent() ||
11551 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11552 return false;
11553 if (!AlwaysTrue)
11554 return false;
11555 }
11556 return true;
11557}
11558
11559/// Returns true if we can take the address of the function.
11560///
11561/// \param Complain - If true, we'll emit a diagnostic
11562/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11563/// we in overload resolution?
11564/// \param Loc - The location of the statement we're complaining about. Ignored
11565/// if we're not complaining, or if we're in overload resolution.
11567 bool Complain,
11568 bool InOverloadResolution,
11569 SourceLocation Loc) {
11570 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11571 if (Complain) {
11572 if (InOverloadResolution)
11573 S.Diag(FD->getBeginLoc(),
11574 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11575 else
11576 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11577 }
11578 return false;
11579 }
11580
11581 if (FD->getTrailingRequiresClause()) {
11582 ConstraintSatisfaction Satisfaction;
11583 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11584 return false;
11585 if (!Satisfaction.IsSatisfied) {
11586 if (Complain) {
11587 if (InOverloadResolution) {
11588 SmallString<128> TemplateArgString;
11589 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11590 TemplateArgString += " ";
11591 TemplateArgString += S.getTemplateArgumentBindingsText(
11592 FunTmpl->getTemplateParameters(),
11594 }
11595
11596 S.Diag(FD->getBeginLoc(),
11597 diag::note_ovl_candidate_unsatisfied_constraints)
11598 << TemplateArgString;
11599 } else
11600 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11601 << FD;
11602 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11603 }
11604 return false;
11605 }
11606 }
11607
11608 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11609 return P->hasAttr<PassObjectSizeAttr>();
11610 });
11611 if (I == FD->param_end())
11612 return true;
11613
11614 if (Complain) {
11615 // Add one to ParamNo because it's user-facing
11616 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11617 if (InOverloadResolution)
11618 S.Diag(FD->getLocation(),
11619 diag::note_ovl_candidate_has_pass_object_size_params)
11620 << ParamNo;
11621 else
11622 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11623 << FD << ParamNo;
11624 }
11625 return false;
11626}
11627
11629 const FunctionDecl *FD) {
11630 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11631 /*InOverloadResolution=*/true,
11632 /*Loc=*/SourceLocation());
11633}
11634
11636 bool Complain,
11637 SourceLocation Loc) {
11638 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11639 /*InOverloadResolution=*/false,
11640 Loc);
11641}
11642
11643// Don't print candidates other than the one that matches the calling
11644// convention of the call operator, since that is guaranteed to exist.
11646 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11647
11648 if (!ConvD)
11649 return false;
11650 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11651 if (!RD->isLambda())
11652 return false;
11653
11654 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11655 CallingConv CallOpCC =
11656 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11657 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11658 CallingConv ConvToCC =
11659 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11660
11661 return ConvToCC != CallOpCC;
11662}
11663
11664// Notes the location of an overload candidate.
11666 OverloadCandidateRewriteKind RewriteKind,
11667 QualType DestType, bool TakingAddress) {
11668 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11669 return;
11670 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11671 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11672 return;
11673 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11674 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11675 return;
11677 return;
11678
11679 std::string FnDesc;
11680 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11681 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11682 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11683 << (unsigned)KSPair.first << (unsigned)KSPair.second
11684 << Fn << FnDesc;
11685
11686 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11687 Diag(Fn->getLocation(), PD);
11688 MaybeEmitInheritedConstructorNote(*this, Found);
11689}
11690
11691static void
11693 // Perhaps the ambiguity was caused by two atomic constraints that are
11694 // 'identical' but not equivalent:
11695 //
11696 // void foo() requires (sizeof(T) > 4) { } // #1
11697 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11698 //
11699 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11700 // #2 to subsume #1, but these constraint are not considered equivalent
11701 // according to the subsumption rules because they are not the same
11702 // source-level construct. This behavior is quite confusing and we should try
11703 // to help the user figure out what happened.
11704
11705 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11706 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11707 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11708 if (!I->Function)
11709 continue;
11711 if (auto *Template = I->Function->getPrimaryTemplate())
11712 Template->getAssociatedConstraints(AC);
11713 else
11714 I->Function->getAssociatedConstraints(AC);
11715 if (AC.empty())
11716 continue;
11717 if (FirstCand == nullptr) {
11718 FirstCand = I->Function;
11719 FirstAC = AC;
11720 } else if (SecondCand == nullptr) {
11721 SecondCand = I->Function;
11722 SecondAC = AC;
11723 } else {
11724 // We have more than one pair of constrained functions - this check is
11725 // expensive and we'd rather not try to diagnose it.
11726 return;
11727 }
11728 }
11729 if (!SecondCand)
11730 return;
11731 // The diagnostic can only happen if there are associated constraints on
11732 // both sides (there needs to be some identical atomic constraint).
11733 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11734 SecondCand, SecondAC))
11735 // Just show the user one diagnostic, they'll probably figure it out
11736 // from here.
11737 return;
11738}
11739
11740// Notes the location of all overload candidates designated through
11741// OverloadedExpr
11742void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11743 bool TakingAddress) {
11744 assert(OverloadedExpr->getType() == Context.OverloadTy);
11745
11746 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11747 OverloadExpr *OvlExpr = Ovl.Expression;
11748
11749 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11750 IEnd = OvlExpr->decls_end();
11751 I != IEnd; ++I) {
11752 if (FunctionTemplateDecl *FunTmpl =
11753 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11754 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11755 TakingAddress);
11756 } else if (FunctionDecl *Fun
11757 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11758 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11759 }
11760 }
11761}
11762
11763/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11764/// "lead" diagnostic; it will be given two arguments, the source and
11765/// target types of the conversion.
11767 Sema &S,
11768 SourceLocation CaretLoc,
11769 const PartialDiagnostic &PDiag) const {
11770 S.Diag(CaretLoc, PDiag)
11771 << Ambiguous.getFromType() << Ambiguous.getToType();
11772 unsigned CandsShown = 0;
11774 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11775 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11776 break;
11777 ++CandsShown;
11778 S.NoteOverloadCandidate(I->first, I->second);
11779 }
11780 S.Diags.overloadCandidatesShown(CandsShown);
11781 if (I != E)
11782 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11783}
11784
11786 unsigned I, bool TakingCandidateAddress) {
11787 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11788 assert(Conv.isBad());
11789 assert(Cand->Function && "for now, candidate must be a function");
11790 FunctionDecl *Fn = Cand->Function;
11791
11792 // There's a conversion slot for the object argument if this is a
11793 // non-constructor method. Note that 'I' corresponds the
11794 // conversion-slot index.
11795 bool isObjectArgument = false;
11796 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11798 if (I == 0)
11799 isObjectArgument = true;
11800 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11801 I--;
11802 }
11803
11804 std::string FnDesc;
11805 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11806 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11807 FnDesc);
11808
11809 Expr *FromExpr = Conv.Bad.FromExpr;
11810 QualType FromTy = Conv.Bad.getFromType();
11811 QualType ToTy = Conv.Bad.getToType();
11812 SourceRange ToParamRange;
11813
11814 // FIXME: In presence of parameter packs we can't determine parameter range
11815 // reliably, as we don't have access to instantiation.
11816 bool HasParamPack =
11817 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11818 return Parm->isParameterPack();
11819 });
11820 if (!isObjectArgument && !HasParamPack)
11821 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11822
11823 if (FromTy == S.Context.OverloadTy) {
11824 assert(FromExpr && "overload set argument came from implicit argument?");
11825 Expr *E = FromExpr->IgnoreParens();
11826 if (isa<UnaryOperator>(E))
11827 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11828 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11829
11830 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11831 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11832 << ToParamRange << ToTy << Name << I + 1;
11833 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11834 return;
11835 }
11836
11837 // Do some hand-waving analysis to see if the non-viability is due
11838 // to a qualifier mismatch.
11839 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11840 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11841 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11842 CToTy = RT->getPointeeType();
11843 else {
11844 // TODO: detect and diagnose the full richness of const mismatches.
11845 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11846 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11847 CFromTy = FromPT->getPointeeType();
11848 CToTy = ToPT->getPointeeType();
11849 }
11850 }
11851
11852 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11853 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11854 Qualifiers FromQs = CFromTy.getQualifiers();
11855 Qualifiers ToQs = CToTy.getQualifiers();
11856
11857 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11858 if (isObjectArgument)
11859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11860 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11861 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11862 else
11863 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11864 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11865 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11866 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11867 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11868 return;
11869 }
11870
11871 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11873 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11874 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11875 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11876 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11877 return;
11878 }
11879
11880 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11881 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11882 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11883 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11884 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11885 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11886 return;
11887 }
11888
11889 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11891 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11892 << FromTy << !!FromQs.getPointerAuth()
11893 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11894 << ToQs.getPointerAuth().getAsString() << I + 1
11895 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11896 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11897 return;
11898 }
11899
11900 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11901 assert(CVR && "expected qualifiers mismatch");
11902
11903 if (isObjectArgument) {
11904 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11905 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11906 << FromTy << (CVR - 1);
11907 } else {
11908 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11909 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11910 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11911 }
11912 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11913 return;
11914 }
11915
11918 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11919 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11920 << (unsigned)isObjectArgument << I + 1
11922 << ToParamRange;
11923 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11924 return;
11925 }
11926
11927 // Special diagnostic for failure to convert an initializer list, since
11928 // telling the user that it has type void is not useful.
11929 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11930 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11931 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11932 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11935 ? 2
11936 : 0);
11937 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11938 return;
11939 }
11940
11941 // Diagnose references or pointers to incomplete types differently,
11942 // since it's far from impossible that the incompleteness triggered
11943 // the failure.
11944 QualType TempFromTy = FromTy.getNonReferenceType();
11945 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11946 TempFromTy = PTy->getPointeeType();
11947 if (TempFromTy->isIncompleteType()) {
11948 // Emit the generic diagnostic and, optionally, add the hints to it.
11949 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11950 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11951 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11952 << (unsigned)(Cand->Fix.Kind);
11953
11954 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11955 return;
11956 }
11957
11958 // Diagnose base -> derived pointer conversions.
11959 unsigned BaseToDerivedConversion = 0;
11960 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11961 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11962 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11963 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11964 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11965 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11966 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11967 FromPtrTy->getPointeeType()))
11968 BaseToDerivedConversion = 1;
11969 }
11970 } else if (const ObjCObjectPointerType *FromPtrTy
11971 = FromTy->getAs<ObjCObjectPointerType>()) {
11972 if (const ObjCObjectPointerType *ToPtrTy
11973 = ToTy->getAs<ObjCObjectPointerType>())
11974 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11975 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11976 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11977 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11978 FromIface->isSuperClassOf(ToIface))
11979 BaseToDerivedConversion = 2;
11980 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11981 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11982 S.getASTContext()) &&
11983 !FromTy->isIncompleteType() &&
11984 !ToRefTy->getPointeeType()->isIncompleteType() &&
11985 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11986 BaseToDerivedConversion = 3;
11987 }
11988 }
11989
11990 if (BaseToDerivedConversion) {
11991 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11992 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11993 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11994 << I + 1;
11995 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11996 return;
11997 }
11998
11999 if (isa<ObjCObjectPointerType>(CFromTy) &&
12000 isa<PointerType>(CToTy)) {
12001 Qualifiers FromQs = CFromTy.getQualifiers();
12002 Qualifiers ToQs = CToTy.getQualifiers();
12003 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12004 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12005 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12006 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12007 << I + 1;
12008 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12009 return;
12010 }
12011 }
12012
12013 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12014 return;
12015
12016 // Emit the generic diagnostic and, optionally, add the hints to it.
12017 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12018 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12019 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12020 << (unsigned)(Cand->Fix.Kind);
12021
12022 // Check that location of Fn is not in system header.
12023 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12024 // If we can fix the conversion, suggest the FixIts.
12025 for (const FixItHint &HI : Cand->Fix.Hints)
12026 FDiag << HI;
12027 }
12028
12029 S.Diag(Fn->getLocation(), FDiag);
12030
12031 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12032}
12033
12034/// Additional arity mismatch diagnosis specific to a function overload
12035/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12036/// over a candidate in any candidate set.
12038 unsigned NumArgs, bool IsAddressOf = false) {
12039 assert(Cand->Function && "Candidate is required to be a function.");
12040 FunctionDecl *Fn = Cand->Function;
12041 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12042 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12043
12044 // With invalid overloaded operators, it's possible that we think we
12045 // have an arity mismatch when in fact it looks like we have the
12046 // right number of arguments, because only overloaded operators have
12047 // the weird behavior of overloading member and non-member functions.
12048 // Just don't report anything.
12049 if (Fn->isInvalidDecl() &&
12050 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12051 return true;
12052
12053 if (NumArgs < MinParams) {
12054 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12056 Cand->DeductionFailure.getResult() ==
12058 } else {
12059 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12061 Cand->DeductionFailure.getResult() ==
12063 }
12064
12065 return false;
12066}
12067
12068/// General arity mismatch diagnosis over a candidate in a candidate set.
12070 unsigned NumFormalArgs,
12071 bool IsAddressOf = false) {
12072 assert(isa<FunctionDecl>(D) &&
12073 "The templated declaration should at least be a function"
12074 " when diagnosing bad template argument deduction due to too many"
12075 " or too few arguments");
12076
12078
12079 // TODO: treat calls to a missing default constructor as a special case
12080 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12081 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12082 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12083
12084 // at least / at most / exactly
12085 bool HasExplicitObjectParam =
12086 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12087
12088 unsigned ParamCount =
12089 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12090 unsigned mode, modeCount;
12091
12092 if (NumFormalArgs < MinParams) {
12093 if (MinParams != ParamCount || FnTy->isVariadic() ||
12094 FnTy->isTemplateVariadic())
12095 mode = 0; // "at least"
12096 else
12097 mode = 2; // "exactly"
12098 modeCount = MinParams;
12099 } else {
12100 if (MinParams != ParamCount)
12101 mode = 1; // "at most"
12102 else
12103 mode = 2; // "exactly"
12104 modeCount = ParamCount;
12105 }
12106
12107 std::string Description;
12108 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12109 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12110
12111 if (modeCount == 1 && !IsAddressOf &&
12112 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12114 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12115 << Description << mode
12116 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12117 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12118 else
12119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12120 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12121 << Description << mode << modeCount << NumFormalArgs
12122 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12123
12124 MaybeEmitInheritedConstructorNote(S, Found);
12125}
12126
12127/// Arity mismatch diagnosis specific to a function overload candidate.
12129 unsigned NumFormalArgs) {
12130 assert(Cand->Function && "Candidate must be a function");
12131 FunctionDecl *Fn = Cand->Function;
12132 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12133 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12134 Cand->TookAddressOfOverload);
12135}
12136
12138 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12139 return TD;
12140 llvm_unreachable("Unsupported: Getting the described template declaration"
12141 " for bad deduction diagnosis");
12142}
12143
12144/// Diagnose a failed template-argument deduction.
12145static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12146 DeductionFailureInfo &DeductionFailure,
12147 unsigned NumArgs,
12148 bool TakingCandidateAddress) {
12149 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12150 NamedDecl *ParamD;
12151 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12152 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12153 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12154 switch (DeductionFailure.getResult()) {
12156 llvm_unreachable(
12157 "TemplateDeductionResult::Success while diagnosing bad deduction");
12159 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12160 "while diagnosing bad deduction");
12163 return;
12164
12166 assert(ParamD && "no parameter found for incomplete deduction result");
12167 S.Diag(Templated->getLocation(),
12168 diag::note_ovl_candidate_incomplete_deduction)
12169 << ParamD->getDeclName();
12170 MaybeEmitInheritedConstructorNote(S, Found);
12171 return;
12172 }
12173
12175 assert(ParamD && "no parameter found for incomplete deduction result");
12176 S.Diag(Templated->getLocation(),
12177 diag::note_ovl_candidate_incomplete_deduction_pack)
12178 << ParamD->getDeclName()
12179 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12180 << *DeductionFailure.getFirstArg();
12181 MaybeEmitInheritedConstructorNote(S, Found);
12182 return;
12183 }
12184
12186 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12188
12189 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12190
12191 // Param will have been canonicalized, but it should just be a
12192 // qualified version of ParamD, so move the qualifiers to that.
12194 Qs.strip(Param);
12195 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12196 assert(S.Context.hasSameType(Param, NonCanonParam));
12197
12198 // Arg has also been canonicalized, but there's nothing we can do
12199 // about that. It also doesn't matter as much, because it won't
12200 // have any template parameters in it (because deduction isn't
12201 // done on dependent types).
12202 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12203
12204 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12205 << ParamD->getDeclName() << Arg << NonCanonParam;
12206 MaybeEmitInheritedConstructorNote(S, Found);
12207 return;
12208 }
12209
12211 assert(ParamD && "no parameter found for inconsistent deduction result");
12212 int which = 0;
12213 if (isa<TemplateTypeParmDecl>(ParamD))
12214 which = 0;
12215 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12216 // Deduction might have failed because we deduced arguments of two
12217 // different types for a non-type template parameter.
12218 // FIXME: Use a different TDK value for this.
12219 QualType T1 =
12220 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12221 QualType T2 =
12222 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12223 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12224 S.Diag(Templated->getLocation(),
12225 diag::note_ovl_candidate_inconsistent_deduction_types)
12226 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12227 << *DeductionFailure.getSecondArg() << T2;
12228 MaybeEmitInheritedConstructorNote(S, Found);
12229 return;
12230 }
12231
12232 which = 1;
12233 } else {
12234 which = 2;
12235 }
12236
12237 // Tweak the diagnostic if the problem is that we deduced packs of
12238 // different arities. We'll print the actual packs anyway in case that
12239 // includes additional useful information.
12240 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12241 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12242 DeductionFailure.getFirstArg()->pack_size() !=
12243 DeductionFailure.getSecondArg()->pack_size()) {
12244 which = 3;
12245 }
12246
12247 S.Diag(Templated->getLocation(),
12248 diag::note_ovl_candidate_inconsistent_deduction)
12249 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12250 << *DeductionFailure.getSecondArg();
12251 MaybeEmitInheritedConstructorNote(S, Found);
12252 return;
12253 }
12254
12256 assert(ParamD && "no parameter found for invalid explicit arguments");
12257 if (ParamD->getDeclName())
12258 S.Diag(Templated->getLocation(),
12259 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12260 << ParamD->getDeclName();
12261 else {
12262 int index = 0;
12263 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12264 index = TTP->getIndex();
12265 else if (NonTypeTemplateParmDecl *NTTP
12266 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12267 index = NTTP->getIndex();
12268 else
12269 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12270 S.Diag(Templated->getLocation(),
12271 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12272 << (index + 1);
12273 }
12274 MaybeEmitInheritedConstructorNote(S, Found);
12275 return;
12276
12278 // Format the template argument list into the argument string.
12279 SmallString<128> TemplateArgString;
12280 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12281 TemplateArgString = " ";
12282 TemplateArgString += S.getTemplateArgumentBindingsText(
12283 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12284 if (TemplateArgString.size() == 1)
12285 TemplateArgString.clear();
12286 S.Diag(Templated->getLocation(),
12287 diag::note_ovl_candidate_unsatisfied_constraints)
12288 << TemplateArgString;
12289
12291 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12292 return;
12293 }
12296 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12297 return;
12298
12300 S.Diag(Templated->getLocation(),
12301 diag::note_ovl_candidate_instantiation_depth);
12302 MaybeEmitInheritedConstructorNote(S, Found);
12303 return;
12304
12306 // Format the template argument list into the argument string.
12307 SmallString<128> TemplateArgString;
12308 if (TemplateArgumentList *Args =
12309 DeductionFailure.getTemplateArgumentList()) {
12310 TemplateArgString = " ";
12311 TemplateArgString += S.getTemplateArgumentBindingsText(
12312 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12313 if (TemplateArgString.size() == 1)
12314 TemplateArgString.clear();
12315 }
12316
12317 // If this candidate was disabled by enable_if, say so.
12318 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12319 if (PDiag && PDiag->second.getDiagID() ==
12320 diag::err_typename_nested_not_found_enable_if) {
12321 // FIXME: Use the source range of the condition, and the fully-qualified
12322 // name of the enable_if template. These are both present in PDiag.
12323 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12324 << "'enable_if'" << TemplateArgString;
12325 return;
12326 }
12327
12328 // We found a specific requirement that disabled the enable_if.
12329 if (PDiag && PDiag->second.getDiagID() ==
12330 diag::err_typename_nested_not_found_requirement) {
12331 S.Diag(Templated->getLocation(),
12332 diag::note_ovl_candidate_disabled_by_requirement)
12333 << PDiag->second.getStringArg(0) << TemplateArgString;
12334 return;
12335 }
12336
12337 // Format the SFINAE diagnostic into the argument string.
12338 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12339 // formatted message in another diagnostic.
12340 SmallString<128> SFINAEArgString;
12341 SourceRange R;
12342 if (PDiag) {
12343 SFINAEArgString = ": ";
12344 R = SourceRange(PDiag->first, PDiag->first);
12345 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12346 }
12347
12348 S.Diag(Templated->getLocation(),
12349 diag::note_ovl_candidate_substitution_failure)
12350 << TemplateArgString << SFINAEArgString << R;
12351 MaybeEmitInheritedConstructorNote(S, Found);
12352 return;
12353 }
12354
12357 // Format the template argument list into the argument string.
12358 SmallString<128> TemplateArgString;
12359 if (TemplateArgumentList *Args =
12360 DeductionFailure.getTemplateArgumentList()) {
12361 TemplateArgString = " ";
12362 TemplateArgString += S.getTemplateArgumentBindingsText(
12363 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12364 if (TemplateArgString.size() == 1)
12365 TemplateArgString.clear();
12366 }
12367
12368 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12369 << (*DeductionFailure.getCallArgIndex() + 1)
12370 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12371 << TemplateArgString
12372 << (DeductionFailure.getResult() ==
12374 break;
12375 }
12376
12378 // FIXME: Provide a source location to indicate what we couldn't match.
12379 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12380 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12381 if (FirstTA.getKind() == TemplateArgument::Template &&
12382 SecondTA.getKind() == TemplateArgument::Template) {
12383 TemplateName FirstTN = FirstTA.getAsTemplate();
12384 TemplateName SecondTN = SecondTA.getAsTemplate();
12385 if (FirstTN.getKind() == TemplateName::Template &&
12386 SecondTN.getKind() == TemplateName::Template) {
12387 if (FirstTN.getAsTemplateDecl()->getName() ==
12388 SecondTN.getAsTemplateDecl()->getName()) {
12389 // FIXME: This fixes a bad diagnostic where both templates are named
12390 // the same. This particular case is a bit difficult since:
12391 // 1) It is passed as a string to the diagnostic printer.
12392 // 2) The diagnostic printer only attempts to find a better
12393 // name for types, not decls.
12394 // Ideally, this should folded into the diagnostic printer.
12395 S.Diag(Templated->getLocation(),
12396 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12397 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12398 return;
12399 }
12400 }
12401 }
12402
12403 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12405 return;
12406
12407 // FIXME: For generic lambda parameters, check if the function is a lambda
12408 // call operator, and if so, emit a prettier and more informative
12409 // diagnostic that mentions 'auto' and lambda in addition to
12410 // (or instead of?) the canonical template type parameters.
12411 S.Diag(Templated->getLocation(),
12412 diag::note_ovl_candidate_non_deduced_mismatch)
12413 << FirstTA << SecondTA;
12414 return;
12415 }
12416 // TODO: diagnose these individually, then kill off
12417 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12419 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12420 MaybeEmitInheritedConstructorNote(S, Found);
12421 return;
12423 S.Diag(Templated->getLocation(),
12424 diag::note_cuda_ovl_candidate_target_mismatch);
12425 return;
12426 }
12427}
12428
12429/// Diagnose a failed template-argument deduction, for function calls.
12431 unsigned NumArgs,
12432 bool TakingCandidateAddress) {
12433 assert(Cand->Function && "Candidate must be a function");
12434 FunctionDecl *Fn = Cand->Function;
12438 if (CheckArityMismatch(S, Cand, NumArgs))
12439 return;
12440 }
12441 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12442 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12443}
12444
12445/// CUDA: diagnose an invalid call across targets.
12447 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12448 assert(Cand->Function && "Candidate must be a Function.");
12449 FunctionDecl *Callee = Cand->Function;
12450
12451 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12452 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12453
12454 std::string FnDesc;
12455 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12456 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12457 Cand->getRewriteKind(), FnDesc);
12458
12459 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12460 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12461 << FnDesc /* Ignored */
12462 << CalleeTarget << CallerTarget;
12463
12464 // This could be an implicit constructor for which we could not infer the
12465 // target due to a collsion. Diagnose that case.
12466 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12467 if (Meth != nullptr && Meth->isImplicit()) {
12468 CXXRecordDecl *ParentClass = Meth->getParent();
12470
12471 switch (FnKindPair.first) {
12472 default:
12473 return;
12474 case oc_implicit_default_constructor:
12476 break;
12477 case oc_implicit_copy_constructor:
12479 break;
12480 case oc_implicit_move_constructor:
12482 break;
12483 case oc_implicit_copy_assignment:
12485 break;
12486 case oc_implicit_move_assignment:
12488 break;
12489 };
12490
12491 bool ConstRHS = false;
12492 if (Meth->getNumParams()) {
12493 if (const ReferenceType *RT =
12494 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12495 ConstRHS = RT->getPointeeType().isConstQualified();
12496 }
12497 }
12498
12499 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12500 /* ConstRHS */ ConstRHS,
12501 /* Diagnose */ true);
12502 }
12503}
12504
12506 assert(Cand->Function && "Candidate must be a function");
12507 FunctionDecl *Callee = Cand->Function;
12508 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12509
12510 S.Diag(Callee->getLocation(),
12511 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12512 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12513}
12514
12516 assert(Cand->Function && "Candidate must be a function");
12517 FunctionDecl *Fn = Cand->Function;
12519 assert(ES.isExplicit() && "not an explicit candidate");
12520
12521 unsigned Kind;
12522 switch (Fn->getDeclKind()) {
12523 case Decl::Kind::CXXConstructor:
12524 Kind = 0;
12525 break;
12526 case Decl::Kind::CXXConversion:
12527 Kind = 1;
12528 break;
12529 case Decl::Kind::CXXDeductionGuide:
12530 Kind = Fn->isImplicit() ? 0 : 2;
12531 break;
12532 default:
12533 llvm_unreachable("invalid Decl");
12534 }
12535
12536 // Note the location of the first (in-class) declaration; a redeclaration
12537 // (particularly an out-of-class definition) will typically lack the
12538 // 'explicit' specifier.
12539 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12540 FunctionDecl *First = Fn->getFirstDecl();
12541 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12542 First = Pattern->getFirstDecl();
12543
12544 S.Diag(First->getLocation(),
12545 diag::note_ovl_candidate_explicit)
12546 << Kind << (ES.getExpr() ? 1 : 0)
12547 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12548}
12549
12551 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12552 if (!DG)
12553 return;
12554 TemplateDecl *OriginTemplate =
12556 // We want to always print synthesized deduction guides for type aliases.
12557 // They would retain the explicit bit of the corresponding constructor.
12558 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12559 return;
12560 std::string FunctionProto;
12561 llvm::raw_string_ostream OS(FunctionProto);
12562 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12563 if (!Template) {
12564 // This also could be an instantiation. Find out the primary template.
12565 FunctionDecl *Pattern =
12566 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12567 if (!Pattern) {
12568 // The implicit deduction guide is built on an explicit non-template
12569 // deduction guide. Currently, this might be the case only for type
12570 // aliases.
12571 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12572 // gets merged.
12573 assert(OriginTemplate->isTypeAlias() &&
12574 "Non-template implicit deduction guides are only possible for "
12575 "type aliases");
12576 DG->print(OS);
12577 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12578 << FunctionProto;
12579 return;
12580 }
12582 assert(Template && "Cannot find the associated function template of "
12583 "CXXDeductionGuideDecl?");
12584 }
12585 Template->print(OS);
12586 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12587 << FunctionProto;
12588}
12589
12590/// Generates a 'note' diagnostic for an overload candidate. We've
12591/// already generated a primary error at the call site.
12592///
12593/// It really does need to be a single diagnostic with its caret
12594/// pointed at the candidate declaration. Yes, this creates some
12595/// major challenges of technical writing. Yes, this makes pointing
12596/// out problems with specific arguments quite awkward. It's still
12597/// better than generating twenty screens of text for every failed
12598/// overload.
12599///
12600/// It would be great to be able to express per-candidate problems
12601/// more richly for those diagnostic clients that cared, but we'd
12602/// still have to be just as careful with the default diagnostics.
12603/// \param CtorDestAS Addr space of object being constructed (for ctor
12604/// candidates only).
12606 unsigned NumArgs,
12607 bool TakingCandidateAddress,
12608 LangAS CtorDestAS = LangAS::Default) {
12609 assert(Cand->Function && "Candidate must be a function");
12610 FunctionDecl *Fn = Cand->Function;
12612 return;
12613
12614 // There is no physical candidate declaration to point to for OpenCL builtins.
12615 // Except for failed conversions, the notes are identical for each candidate,
12616 // so do not generate such notes.
12617 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12619 return;
12620
12621 // Skip implicit member functions when trying to resolve
12622 // the address of a an overload set for a function pointer.
12623 if (Cand->TookAddressOfOverload &&
12624 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12625 return;
12626
12627 // Note deleted candidates, but only if they're viable.
12628 if (Cand->Viable) {
12629 if (Fn->isDeleted()) {
12630 std::string FnDesc;
12631 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12632 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12633 Cand->getRewriteKind(), FnDesc);
12634
12635 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12636 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12637 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12638 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12639 return;
12640 }
12641
12642 // We don't really have anything else to say about viable candidates.
12643 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12644 return;
12645 }
12646
12647 // If this is a synthesized deduction guide we're deducing against, add a note
12648 // for it. These deduction guides are not explicitly spelled in the source
12649 // code, so simply printing a deduction failure note mentioning synthesized
12650 // template parameters or pointing to the header of the surrounding RecordDecl
12651 // would be confusing.
12652 //
12653 // We prefer adding such notes at the end of the deduction failure because
12654 // duplicate code snippets appearing in the diagnostic would likely become
12655 // noisy.
12656 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12657
12658 switch (Cand->FailureKind) {
12661 return DiagnoseArityMismatch(S, Cand, NumArgs);
12662
12664 return DiagnoseBadDeduction(S, Cand, NumArgs,
12665 TakingCandidateAddress);
12666
12668 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12669 << (Fn->getPrimaryTemplate() ? 1 : 0);
12670 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12671 return;
12672 }
12673
12675 Qualifiers QualsForPrinting;
12676 QualsForPrinting.setAddressSpace(CtorDestAS);
12677 S.Diag(Fn->getLocation(),
12678 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12679 << QualsForPrinting;
12680 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12681 return;
12682 }
12683
12687 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12688
12690 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12691 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12692 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12693 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12694
12695 // FIXME: this currently happens when we're called from SemaInit
12696 // when user-conversion overload fails. Figure out how to handle
12697 // those conditions and diagnose them well.
12698 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12699 }
12700
12702 return DiagnoseBadTarget(S, Cand);
12703
12704 case ovl_fail_enable_if:
12705 return DiagnoseFailedEnableIfAttr(S, Cand);
12706
12707 case ovl_fail_explicit:
12708 return DiagnoseFailedExplicitSpec(S, Cand);
12709
12711 // It's generally not interesting to note copy/move constructors here.
12712 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12713 return;
12714 S.Diag(Fn->getLocation(),
12715 diag::note_ovl_candidate_inherited_constructor_slice)
12716 << (Fn->getPrimaryTemplate() ? 1 : 0)
12717 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12718 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12719 return;
12720
12722 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12723 (void)Available;
12724 assert(!Available);
12725 break;
12726 }
12728 // Do nothing, these should simply be ignored.
12729 break;
12730
12732 std::string FnDesc;
12733 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12734 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12735 Cand->getRewriteKind(), FnDesc);
12736
12737 S.Diag(Fn->getLocation(),
12738 diag::note_ovl_candidate_constraints_not_satisfied)
12739 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12740 << FnDesc /* Ignored */;
12741 ConstraintSatisfaction Satisfaction;
12742 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12743 break;
12744 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12745 }
12746 }
12747}
12748
12751 return;
12752
12753 // Desugar the type of the surrogate down to a function type,
12754 // retaining as many typedefs as possible while still showing
12755 // the function type (and, therefore, its parameter types).
12756 QualType FnType = Cand->Surrogate->getConversionType();
12757 bool isLValueReference = false;
12758 bool isRValueReference = false;
12759 bool isPointer = false;
12760 if (const LValueReferenceType *FnTypeRef =
12761 FnType->getAs<LValueReferenceType>()) {
12762 FnType = FnTypeRef->getPointeeType();
12763 isLValueReference = true;
12764 } else if (const RValueReferenceType *FnTypeRef =
12765 FnType->getAs<RValueReferenceType>()) {
12766 FnType = FnTypeRef->getPointeeType();
12767 isRValueReference = true;
12768 }
12769 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12770 FnType = FnTypePtr->getPointeeType();
12771 isPointer = true;
12772 }
12773 // Desugar down to a function type.
12774 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12775 // Reconstruct the pointer/reference as appropriate.
12776 if (isPointer) FnType = S.Context.getPointerType(FnType);
12777 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12778 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12779
12780 if (!Cand->Viable &&
12782 S.Diag(Cand->Surrogate->getLocation(),
12783 diag::note_ovl_surrogate_constraints_not_satisfied)
12784 << Cand->Surrogate;
12785 ConstraintSatisfaction Satisfaction;
12786 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12787 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12788 } else {
12789 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12790 << FnType;
12791 }
12792}
12793
12794static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12795 SourceLocation OpLoc,
12796 OverloadCandidate *Cand) {
12797 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12798 std::string TypeStr("operator");
12799 TypeStr += Opc;
12800 TypeStr += "(";
12801 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12802 if (Cand->Conversions.size() == 1) {
12803 TypeStr += ")";
12804 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12805 } else {
12806 TypeStr += ", ";
12807 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12808 TypeStr += ")";
12809 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12810 }
12811}
12812
12814 OverloadCandidate *Cand) {
12815 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12816 if (ICS.isBad()) break; // all meaningless after first invalid
12817 if (!ICS.isAmbiguous()) continue;
12818
12820 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12821 }
12822}
12823
12825 if (Cand->Function)
12826 return Cand->Function->getLocation();
12827 if (Cand->IsSurrogate)
12828 return Cand->Surrogate->getLocation();
12829 return SourceLocation();
12830}
12831
12832static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12833 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12837 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12838
12842 return 1;
12843
12846 return 2;
12847
12855 return 3;
12856
12858 return 4;
12859
12861 return 5;
12862
12865 return 6;
12866 }
12867 llvm_unreachable("Unhandled deduction result");
12868}
12869
12870namespace {
12871
12872struct CompareOverloadCandidatesForDisplay {
12873 Sema &S;
12874 SourceLocation Loc;
12875 size_t NumArgs;
12877
12878 CompareOverloadCandidatesForDisplay(
12879 Sema &S, SourceLocation Loc, size_t NArgs,
12881 : S(S), NumArgs(NArgs), CSK(CSK) {}
12882
12883 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12884 // If there are too many or too few arguments, that's the high-order bit we
12885 // want to sort by, even if the immediate failure kind was something else.
12886 if (C->FailureKind == ovl_fail_too_many_arguments ||
12887 C->FailureKind == ovl_fail_too_few_arguments)
12888 return static_cast<OverloadFailureKind>(C->FailureKind);
12889
12890 if (C->Function) {
12891 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12893 if (NumArgs < C->Function->getMinRequiredArguments())
12895 }
12896
12897 return static_cast<OverloadFailureKind>(C->FailureKind);
12898 }
12899
12900 bool operator()(const OverloadCandidate *L,
12901 const OverloadCandidate *R) {
12902 // Fast-path this check.
12903 if (L == R) return false;
12904
12905 // Order first by viability.
12906 if (L->Viable) {
12907 if (!R->Viable) return true;
12908
12909 if (int Ord = CompareConversions(*L, *R))
12910 return Ord < 0;
12911 // Use other tie breakers.
12912 } else if (R->Viable)
12913 return false;
12914
12915 assert(L->Viable == R->Viable);
12916
12917 // Criteria by which we can sort non-viable candidates:
12918 if (!L->Viable) {
12919 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12920 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12921
12922 // 1. Arity mismatches come after other candidates.
12923 if (LFailureKind == ovl_fail_too_many_arguments ||
12924 LFailureKind == ovl_fail_too_few_arguments) {
12925 if (RFailureKind == ovl_fail_too_many_arguments ||
12926 RFailureKind == ovl_fail_too_few_arguments) {
12927 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12928 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12929 if (LDist == RDist) {
12930 if (LFailureKind == RFailureKind)
12931 // Sort non-surrogates before surrogates.
12932 return !L->IsSurrogate && R->IsSurrogate;
12933 // Sort candidates requiring fewer parameters than there were
12934 // arguments given after candidates requiring more parameters
12935 // than there were arguments given.
12936 return LFailureKind == ovl_fail_too_many_arguments;
12937 }
12938 return LDist < RDist;
12939 }
12940 return false;
12941 }
12942 if (RFailureKind == ovl_fail_too_many_arguments ||
12943 RFailureKind == ovl_fail_too_few_arguments)
12944 return true;
12945
12946 // 2. Bad conversions come first and are ordered by the number
12947 // of bad conversions and quality of good conversions.
12948 if (LFailureKind == ovl_fail_bad_conversion) {
12949 if (RFailureKind != ovl_fail_bad_conversion)
12950 return true;
12951
12952 // The conversion that can be fixed with a smaller number of changes,
12953 // comes first.
12954 unsigned numLFixes = L->Fix.NumConversionsFixed;
12955 unsigned numRFixes = R->Fix.NumConversionsFixed;
12956 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12957 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12958 if (numLFixes != numRFixes) {
12959 return numLFixes < numRFixes;
12960 }
12961
12962 // If there's any ordering between the defined conversions...
12963 if (int Ord = CompareConversions(*L, *R))
12964 return Ord < 0;
12965 } else if (RFailureKind == ovl_fail_bad_conversion)
12966 return false;
12967
12968 if (LFailureKind == ovl_fail_bad_deduction) {
12969 if (RFailureKind != ovl_fail_bad_deduction)
12970 return true;
12971
12973 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12974 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12975 if (LRank != RRank)
12976 return LRank < RRank;
12977 }
12978 } else if (RFailureKind == ovl_fail_bad_deduction)
12979 return false;
12980
12981 // TODO: others?
12982 }
12983
12984 // Sort everything else by location.
12985 SourceLocation LLoc = GetLocationForCandidate(L);
12986 SourceLocation RLoc = GetLocationForCandidate(R);
12987
12988 // Put candidates without locations (e.g. builtins) at the end.
12989 if (LLoc.isValid() && RLoc.isValid())
12990 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12991 if (LLoc.isValid() && !RLoc.isValid())
12992 return true;
12993 if (RLoc.isValid() && !LLoc.isValid())
12994 return false;
12995 assert(!LLoc.isValid() && !RLoc.isValid());
12996 // For builtins and other functions without locations, fallback to the order
12997 // in which they were added into the candidate set.
12998 return L < R;
12999 }
13000
13001private:
13002 struct ConversionSignals {
13003 unsigned KindRank = 0;
13005
13006 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13007 ConversionSignals Sig;
13008 Sig.KindRank = Seq.getKindRank();
13009 if (Seq.isStandard())
13010 Sig.Rank = Seq.Standard.getRank();
13011 else if (Seq.isUserDefined())
13012 Sig.Rank = Seq.UserDefined.After.getRank();
13013 // We intend StaticObjectArgumentConversion to compare the same as
13014 // StandardConversion with ICR_ExactMatch rank.
13015 return Sig;
13016 }
13017
13018 static ConversionSignals ForObjectArgument() {
13019 // We intend StaticObjectArgumentConversion to compare the same as
13020 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13021 return {};
13022 }
13023 };
13024
13025 // Returns -1 if conversions in L are considered better.
13026 // 0 if they are considered indistinguishable.
13027 // 1 if conversions in R are better.
13028 int CompareConversions(const OverloadCandidate &L,
13029 const OverloadCandidate &R) {
13030 // We cannot use `isBetterOverloadCandidate` because it is defined
13031 // according to the C++ standard and provides a partial order, but we need
13032 // a total order as this function is used in sort.
13033 assert(L.Conversions.size() == R.Conversions.size());
13034 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13035 auto LS = L.IgnoreObjectArgument && I == 0
13036 ? ConversionSignals::ForObjectArgument()
13037 : ConversionSignals::ForSequence(L.Conversions[I]);
13038 auto RS = R.IgnoreObjectArgument
13039 ? ConversionSignals::ForObjectArgument()
13040 : ConversionSignals::ForSequence(R.Conversions[I]);
13041 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13042 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13043 ? -1
13044 : 1;
13045 }
13046 // FIXME: find a way to compare templates for being more or less
13047 // specialized that provides a strict weak ordering.
13048 return 0;
13049 }
13050};
13051}
13052
13053/// CompleteNonViableCandidate - Normally, overload resolution only
13054/// computes up to the first bad conversion. Produces the FixIt set if
13055/// possible.
13056static void
13058 ArrayRef<Expr *> Args,
13060 assert(!Cand->Viable);
13061
13062 // Don't do anything on failures other than bad conversion.
13064 return;
13065
13066 // We only want the FixIts if all the arguments can be corrected.
13067 bool Unfixable = false;
13068 // Use a implicit copy initialization to check conversion fixes.
13070
13071 // Attempt to fix the bad conversion.
13072 unsigned ConvCount = Cand->Conversions.size();
13073 for (unsigned ConvIdx =
13074 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13075 : 0);
13076 /**/; ++ConvIdx) {
13077 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13078 if (Cand->Conversions[ConvIdx].isInitialized() &&
13079 Cand->Conversions[ConvIdx].isBad()) {
13080 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13081 break;
13082 }
13083 }
13084
13085 // FIXME: this should probably be preserved from the overload
13086 // operation somehow.
13087 bool SuppressUserConversions = false;
13088
13089 unsigned ConvIdx = 0;
13090 unsigned ArgIdx = 0;
13091 ArrayRef<QualType> ParamTypes;
13092 bool Reversed = Cand->isReversed();
13093
13094 if (Cand->IsSurrogate) {
13095 QualType ConvType
13097 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13098 ConvType = ConvPtrType->getPointeeType();
13099 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13100 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13101 ConvIdx = 1;
13102 } else if (Cand->Function) {
13103 ParamTypes =
13104 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13105 if (isa<CXXMethodDecl>(Cand->Function) &&
13108 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13109 ConvIdx = 1;
13111 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13113 OO_Subscript)
13114 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13115 ArgIdx = 1;
13116 }
13117 } else {
13118 // Builtin operator.
13119 assert(ConvCount <= 3);
13120 ParamTypes = Cand->BuiltinParamTypes;
13121 }
13122
13123 // Fill in the rest of the conversions.
13124 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13125 ConvIdx != ConvCount && ArgIdx < Args.size();
13126 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13127 if (Cand->Conversions[ConvIdx].isInitialized()) {
13128 // We've already checked this conversion.
13129 } else if (ParamIdx < ParamTypes.size()) {
13130 if (ParamTypes[ParamIdx]->isDependentType())
13131 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13132 Args[ArgIdx]->getType());
13133 else {
13134 Cand->Conversions[ConvIdx] =
13135 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13136 SuppressUserConversions,
13137 /*InOverloadResolution=*/true,
13138 /*AllowObjCWritebackConversion=*/
13139 S.getLangOpts().ObjCAutoRefCount);
13140 // Store the FixIt in the candidate if it exists.
13141 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13142 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13143 }
13144 } else
13145 Cand->Conversions[ConvIdx].setEllipsis();
13146 }
13147}
13148
13151 SourceLocation OpLoc,
13152 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13153
13155
13156 // Sort the candidates by viability and position. Sorting directly would
13157 // be prohibitive, so we make a set of pointers and sort those.
13159 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13160 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13161 Cand != LastCand; ++Cand) {
13162 if (!Filter(*Cand))
13163 continue;
13164 switch (OCD) {
13165 case OCD_AllCandidates:
13166 if (!Cand->Viable) {
13167 if (!Cand->Function && !Cand->IsSurrogate) {
13168 // This a non-viable builtin candidate. We do not, in general,
13169 // want to list every possible builtin candidate.
13170 continue;
13171 }
13172 CompleteNonViableCandidate(S, Cand, Args, Kind);
13173 }
13174 break;
13175
13177 if (!Cand->Viable)
13178 continue;
13179 break;
13180
13182 if (!Cand->Best)
13183 continue;
13184 break;
13185 }
13186
13187 Cands.push_back(Cand);
13188 }
13189
13190 llvm::stable_sort(
13191 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13192
13193 return Cands;
13194}
13195
13197 SourceLocation OpLoc) {
13198 bool DeferHint = false;
13199 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13200 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13201 // host device candidates.
13202 auto WrongSidedCands =
13203 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13204 return (Cand.Viable == false &&
13206 (Cand.Function &&
13207 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13208 Cand.Function->template hasAttr<CUDADeviceAttr>());
13209 });
13210 DeferHint = !WrongSidedCands.empty();
13211 }
13212 return DeferHint;
13213}
13214
13215/// When overload resolution fails, prints diagnostic messages containing the
13216/// candidates in the candidate set.
13219 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13220 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13221
13222 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13223
13224 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
13225
13226 // In WebAssembly we don't want to emit further diagnostics if a table is
13227 // passed as an argument to a function.
13228 bool NoteCands = true;
13229 for (const Expr *Arg : Args) {
13230 if (Arg->getType()->isWebAssemblyTableType())
13231 NoteCands = false;
13232 }
13233
13234 if (NoteCands)
13235 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13236
13237 if (OCD == OCD_AmbiguousCandidates)
13239 {Candidates.begin(), Candidates.end()});
13240}
13241
13244 StringRef Opc, SourceLocation OpLoc) {
13245 bool ReportedAmbiguousConversions = false;
13246
13247 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13248 unsigned CandsShown = 0;
13249 auto I = Cands.begin(), E = Cands.end();
13250 for (; I != E; ++I) {
13251 OverloadCandidate *Cand = *I;
13252
13253 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13254 ShowOverloads == Ovl_Best) {
13255 break;
13256 }
13257 ++CandsShown;
13258
13259 if (Cand->Function)
13260 NoteFunctionCandidate(S, Cand, Args.size(),
13261 Kind == CSK_AddressOfOverloadSet, DestAS);
13262 else if (Cand->IsSurrogate)
13263 NoteSurrogateCandidate(S, Cand);
13264 else {
13265 assert(Cand->Viable &&
13266 "Non-viable built-in candidates are not added to Cands.");
13267 // Generally we only see ambiguities including viable builtin
13268 // operators if overload resolution got screwed up by an
13269 // ambiguous user-defined conversion.
13270 //
13271 // FIXME: It's quite possible for different conversions to see
13272 // different ambiguities, though.
13273 if (!ReportedAmbiguousConversions) {
13274 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13275 ReportedAmbiguousConversions = true;
13276 }
13277
13278 // If this is a viable builtin, print it.
13279 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13280 }
13281 }
13282
13283 // Inform S.Diags that we've shown an overload set with N elements. This may
13284 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13285 S.Diags.overloadCandidatesShown(CandsShown);
13286
13287 if (I != E)
13288 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
13289 shouldDeferDiags(S, Args, OpLoc))
13290 << int(E - I);
13291}
13292
13293static SourceLocation
13295 return Cand->Specialization ? Cand->Specialization->getLocation()
13296 : SourceLocation();
13297}
13298
13299namespace {
13300struct CompareTemplateSpecCandidatesForDisplay {
13301 Sema &S;
13302 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13303
13304 bool operator()(const TemplateSpecCandidate *L,
13305 const TemplateSpecCandidate *R) {
13306 // Fast-path this check.
13307 if (L == R)
13308 return false;
13309
13310 // Assuming that both candidates are not matches...
13311
13312 // Sort by the ranking of deduction failures.
13316
13317 // Sort everything else by location.
13318 SourceLocation LLoc = GetLocationForCandidate(L);
13319 SourceLocation RLoc = GetLocationForCandidate(R);
13320
13321 // Put candidates without locations (e.g. builtins) at the end.
13322 if (LLoc.isInvalid())
13323 return false;
13324 if (RLoc.isInvalid())
13325 return true;
13326
13327 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13328 }
13329};
13330}
13331
13332/// Diagnose a template argument deduction failure.
13333/// We are treating these failures as overload failures due to bad
13334/// deductions.
13336 bool ForTakingAddress) {
13338 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13339}
13340
13341void TemplateSpecCandidateSet::destroyCandidates() {
13342 for (iterator i = begin(), e = end(); i != e; ++i) {
13343 i->DeductionFailure.Destroy();
13344 }
13345}
13346
13348 destroyCandidates();
13349 Candidates.clear();
13350}
13351
13352/// NoteCandidates - When no template specialization match is found, prints
13353/// diagnostic messages containing the non-matching specializations that form
13354/// the candidate set.
13355/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13356/// OCD == OCD_AllCandidates and Cand->Viable == false.
13358 // Sort the candidates by position (assuming no candidate is a match).
13359 // Sorting directly would be prohibitive, so we make a set of pointers
13360 // and sort those.
13362 Cands.reserve(size());
13363 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13364 if (Cand->Specialization)
13365 Cands.push_back(Cand);
13366 // Otherwise, this is a non-matching builtin candidate. We do not,
13367 // in general, want to list every possible builtin candidate.
13368 }
13369
13370 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13371
13372 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13373 // for generalization purposes (?).
13374 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13375
13377 unsigned CandsShown = 0;
13378 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13379 TemplateSpecCandidate *Cand = *I;
13380
13381 // Set an arbitrary limit on the number of candidates we'll spam
13382 // the user with. FIXME: This limit should depend on details of the
13383 // candidate list.
13384 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13385 break;
13386 ++CandsShown;
13387
13388 assert(Cand->Specialization &&
13389 "Non-matching built-in candidates are not added to Cands.");
13390 Cand->NoteDeductionFailure(S, ForTakingAddress);
13391 }
13392
13393 if (I != E)
13394 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13395}
13396
13397// [PossiblyAFunctionType] --> [Return]
13398// NonFunctionType --> NonFunctionType
13399// R (A) --> R(A)
13400// R (*)(A) --> R (A)
13401// R (&)(A) --> R (A)
13402// R (S::*)(A) --> R (A)
13404 QualType Ret = PossiblyAFunctionType;
13405 if (const PointerType *ToTypePtr =
13406 PossiblyAFunctionType->getAs<PointerType>())
13407 Ret = ToTypePtr->getPointeeType();
13408 else if (const ReferenceType *ToTypeRef =
13409 PossiblyAFunctionType->getAs<ReferenceType>())
13410 Ret = ToTypeRef->getPointeeType();
13411 else if (const MemberPointerType *MemTypePtr =
13412 PossiblyAFunctionType->getAs<MemberPointerType>())
13413 Ret = MemTypePtr->getPointeeType();
13414 Ret =
13415 Context.getCanonicalType(Ret).getUnqualifiedType();
13416 return Ret;
13417}
13418
13420 bool Complain = true) {
13421 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13422 S.DeduceReturnType(FD, Loc, Complain))
13423 return true;
13424
13425 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13426 if (S.getLangOpts().CPlusPlus17 &&
13427 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13428 !S.ResolveExceptionSpec(Loc, FPT))
13429 return true;
13430
13431 return false;
13432}
13433
13434namespace {
13435// A helper class to help with address of function resolution
13436// - allows us to avoid passing around all those ugly parameters
13437class AddressOfFunctionResolver {
13438 Sema& S;
13439 Expr* SourceExpr;
13440 const QualType& TargetType;
13441 QualType TargetFunctionType; // Extracted function type from target type
13442
13443 bool Complain;
13444 //DeclAccessPair& ResultFunctionAccessPair;
13445 ASTContext& Context;
13446
13447 bool TargetTypeIsNonStaticMemberFunction;
13448 bool FoundNonTemplateFunction;
13449 bool StaticMemberFunctionFromBoundPointer;
13450 bool HasComplained;
13451
13452 OverloadExpr::FindResult OvlExprInfo;
13453 OverloadExpr *OvlExpr;
13454 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13455 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13456 TemplateSpecCandidateSet FailedCandidates;
13457
13458public:
13459 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13460 const QualType &TargetType, bool Complain)
13461 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13462 Complain(Complain), Context(S.getASTContext()),
13463 TargetTypeIsNonStaticMemberFunction(
13464 !!TargetType->getAs<MemberPointerType>()),
13465 FoundNonTemplateFunction(false),
13466 StaticMemberFunctionFromBoundPointer(false),
13467 HasComplained(false),
13468 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13469 OvlExpr(OvlExprInfo.Expression),
13470 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13471 ExtractUnqualifiedFunctionTypeFromTargetType();
13472
13473 if (TargetFunctionType->isFunctionType()) {
13474 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13475 if (!UME->isImplicitAccess() &&
13477 StaticMemberFunctionFromBoundPointer = true;
13478 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13479 DeclAccessPair dap;
13480 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13481 OvlExpr, false, &dap)) {
13482 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13483 if (!Method->isStatic()) {
13484 // If the target type is a non-function type and the function found
13485 // is a non-static member function, pretend as if that was the
13486 // target, it's the only possible type to end up with.
13487 TargetTypeIsNonStaticMemberFunction = true;
13488
13489 // And skip adding the function if its not in the proper form.
13490 // We'll diagnose this due to an empty set of functions.
13491 if (!OvlExprInfo.HasFormOfMemberPointer)
13492 return;
13493 }
13494
13495 Matches.push_back(std::make_pair(dap, Fn));
13496 }
13497 return;
13498 }
13499
13500 if (OvlExpr->hasExplicitTemplateArgs())
13501 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13502
13503 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13504 // C++ [over.over]p4:
13505 // If more than one function is selected, [...]
13506 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13507 if (FoundNonTemplateFunction) {
13508 EliminateAllTemplateMatches();
13509 EliminateLessPartialOrderingConstrainedMatches();
13510 } else
13511 EliminateAllExceptMostSpecializedTemplate();
13512 }
13513 }
13514
13515 if (S.getLangOpts().CUDA && Matches.size() > 1)
13516 EliminateSuboptimalCudaMatches();
13517 }
13518
13519 bool hasComplained() const { return HasComplained; }
13520
13521private:
13522 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13523 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13524 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13525 }
13526
13527 /// \return true if A is considered a better overload candidate for the
13528 /// desired type than B.
13529 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13530 // If A doesn't have exactly the correct type, we don't want to classify it
13531 // as "better" than anything else. This way, the user is required to
13532 // disambiguate for us if there are multiple candidates and no exact match.
13533 return candidateHasExactlyCorrectType(A) &&
13534 (!candidateHasExactlyCorrectType(B) ||
13535 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13536 }
13537
13538 /// \return true if we were able to eliminate all but one overload candidate,
13539 /// false otherwise.
13540 bool eliminiateSuboptimalOverloadCandidates() {
13541 // Same algorithm as overload resolution -- one pass to pick the "best",
13542 // another pass to be sure that nothing is better than the best.
13543 auto Best = Matches.begin();
13544 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13545 if (isBetterCandidate(I->second, Best->second))
13546 Best = I;
13547
13548 const FunctionDecl *BestFn = Best->second;
13549 auto IsBestOrInferiorToBest = [this, BestFn](
13550 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13551 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13552 };
13553
13554 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13555 // option, so we can potentially give the user a better error
13556 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13557 return false;
13558 Matches[0] = *Best;
13559 Matches.resize(1);
13560 return true;
13561 }
13562
13563 bool isTargetTypeAFunction() const {
13564 return TargetFunctionType->isFunctionType();
13565 }
13566
13567 // [ToType] [Return]
13568
13569 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13570 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13571 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13572 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13573 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13574 }
13575
13576 // return true if any matching specializations were found
13577 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13578 const DeclAccessPair& CurAccessFunPair) {
13579 if (CXXMethodDecl *Method
13580 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13581 // Skip non-static function templates when converting to pointer, and
13582 // static when converting to member pointer.
13583 bool CanConvertToFunctionPointer =
13584 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13585 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13586 return false;
13587 }
13588 else if (TargetTypeIsNonStaticMemberFunction)
13589 return false;
13590
13591 // C++ [over.over]p2:
13592 // If the name is a function template, template argument deduction is
13593 // done (14.8.2.2), and if the argument deduction succeeds, the
13594 // resulting template argument list is used to generate a single
13595 // function template specialization, which is added to the set of
13596 // overloaded functions considered.
13597 FunctionDecl *Specialization = nullptr;
13598 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13600 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13601 Specialization, Info, /*IsAddressOfFunction*/ true);
13602 Result != TemplateDeductionResult::Success) {
13603 // Make a note of the failed deduction for diagnostics.
13604 FailedCandidates.addCandidate()
13605 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13606 MakeDeductionFailureInfo(Context, Result, Info));
13607 return false;
13608 }
13609
13610 // Template argument deduction ensures that we have an exact match or
13611 // compatible pointer-to-function arguments that would be adjusted by ICS.
13612 // This function template specicalization works.
13614 Context.getCanonicalType(Specialization->getType()),
13615 Context.getCanonicalType(TargetFunctionType)));
13616
13618 return false;
13619
13620 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13621 return true;
13622 }
13623
13624 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13625 const DeclAccessPair& CurAccessFunPair) {
13626 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13627 // Skip non-static functions when converting to pointer, and static
13628 // when converting to member pointer.
13629 bool CanConvertToFunctionPointer =
13630 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13631 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13632 return false;
13633 }
13634 else if (TargetTypeIsNonStaticMemberFunction)
13635 return false;
13636
13637 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13638 if (S.getLangOpts().CUDA) {
13639 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13640 if (!(Caller && Caller->isImplicit()) &&
13641 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13642 return false;
13643 }
13644 if (FunDecl->isMultiVersion()) {
13645 const auto *TA = FunDecl->getAttr<TargetAttr>();
13646 if (TA && !TA->isDefaultVersion())
13647 return false;
13648 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13649 if (TVA && !TVA->isDefaultVersion())
13650 return false;
13651 }
13652
13653 // If any candidate has a placeholder return type, trigger its deduction
13654 // now.
13655 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13656 Complain)) {
13657 HasComplained |= Complain;
13658 return false;
13659 }
13660
13661 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13662 return false;
13663
13664 // If we're in C, we need to support types that aren't exactly identical.
13665 if (!S.getLangOpts().CPlusPlus ||
13666 candidateHasExactlyCorrectType(FunDecl)) {
13667 Matches.push_back(std::make_pair(
13668 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13669 FoundNonTemplateFunction = true;
13670 return true;
13671 }
13672 }
13673
13674 return false;
13675 }
13676
13677 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13678 bool Ret = false;
13679
13680 // If the overload expression doesn't have the form of a pointer to
13681 // member, don't try to convert it to a pointer-to-member type.
13682 if (IsInvalidFormOfPointerToMemberFunction())
13683 return false;
13684
13685 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13686 E = OvlExpr->decls_end();
13687 I != E; ++I) {
13688 // Look through any using declarations to find the underlying function.
13689 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13690
13691 // C++ [over.over]p3:
13692 // Non-member functions and static member functions match
13693 // targets of type "pointer-to-function" or "reference-to-function."
13694 // Nonstatic member functions match targets of
13695 // type "pointer-to-member-function."
13696 // Note that according to DR 247, the containing class does not matter.
13697 if (FunctionTemplateDecl *FunctionTemplate
13698 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13699 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13700 Ret = true;
13701 }
13702 // If we have explicit template arguments supplied, skip non-templates.
13703 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13704 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13705 Ret = true;
13706 }
13707 assert(Ret || Matches.empty());
13708 return Ret;
13709 }
13710
13711 void EliminateAllExceptMostSpecializedTemplate() {
13712 // [...] and any given function template specialization F1 is
13713 // eliminated if the set contains a second function template
13714 // specialization whose function template is more specialized
13715 // than the function template of F1 according to the partial
13716 // ordering rules of 14.5.5.2.
13717
13718 // The algorithm specified above is quadratic. We instead use a
13719 // two-pass algorithm (similar to the one used to identify the
13720 // best viable function in an overload set) that identifies the
13721 // best function template (if it exists).
13722
13723 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13724 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13725 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13726
13727 // TODO: It looks like FailedCandidates does not serve much purpose
13728 // here, since the no_viable diagnostic has index 0.
13729 UnresolvedSetIterator Result = S.getMostSpecialized(
13730 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13731 SourceExpr->getBeginLoc(), S.PDiag(),
13732 S.PDiag(diag::err_addr_ovl_ambiguous)
13733 << Matches[0].second->getDeclName(),
13734 S.PDiag(diag::note_ovl_candidate)
13735 << (unsigned)oc_function << (unsigned)ocs_described_template,
13736 Complain, TargetFunctionType);
13737
13738 if (Result != MatchesCopy.end()) {
13739 // Make it the first and only element
13740 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13741 Matches[0].second = cast<FunctionDecl>(*Result);
13742 Matches.resize(1);
13743 } else
13744 HasComplained |= Complain;
13745 }
13746
13747 void EliminateAllTemplateMatches() {
13748 // [...] any function template specializations in the set are
13749 // eliminated if the set also contains a non-template function, [...]
13750 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13751 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13752 ++I;
13753 else {
13754 Matches[I] = Matches[--N];
13755 Matches.resize(N);
13756 }
13757 }
13758 }
13759
13760 void EliminateLessPartialOrderingConstrainedMatches() {
13761 // C++ [over.over]p5:
13762 // [...] Any given non-template function F0 is eliminated if the set
13763 // contains a second non-template function that is more
13764 // partial-ordering-constrained than F0. [...]
13765 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13766 "Call EliminateAllTemplateMatches() first");
13767 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13768 Results.push_back(Matches[0]);
13769 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13770 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13771 FunctionDecl *F = getMorePartialOrderingConstrained(
13772 S, Matches[I].second, Results[0].second,
13773 /*IsFn1Reversed=*/false,
13774 /*IsFn2Reversed=*/false);
13775 if (!F) {
13776 Results.push_back(Matches[I]);
13777 continue;
13778 }
13779 if (F == Matches[I].second) {
13780 Results.clear();
13781 Results.push_back(Matches[I]);
13782 }
13783 }
13784 std::swap(Matches, Results);
13785 }
13786
13787 void EliminateSuboptimalCudaMatches() {
13788 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13789 Matches);
13790 }
13791
13792public:
13793 void ComplainNoMatchesFound() const {
13794 assert(Matches.empty());
13795 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13796 << OvlExpr->getName() << TargetFunctionType
13797 << OvlExpr->getSourceRange();
13798 if (FailedCandidates.empty())
13799 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13800 /*TakingAddress=*/true);
13801 else {
13802 // We have some deduction failure messages. Use them to diagnose
13803 // the function templates, and diagnose the non-template candidates
13804 // normally.
13805 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13806 IEnd = OvlExpr->decls_end();
13807 I != IEnd; ++I)
13808 if (FunctionDecl *Fun =
13809 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13811 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13812 /*TakingAddress=*/true);
13813 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13814 }
13815 }
13816
13817 bool IsInvalidFormOfPointerToMemberFunction() const {
13818 return TargetTypeIsNonStaticMemberFunction &&
13819 !OvlExprInfo.HasFormOfMemberPointer;
13820 }
13821
13822 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13823 // TODO: Should we condition this on whether any functions might
13824 // have matched, or is it more appropriate to do that in callers?
13825 // TODO: a fixit wouldn't hurt.
13826 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13827 << TargetType << OvlExpr->getSourceRange();
13828 }
13829
13830 bool IsStaticMemberFunctionFromBoundPointer() const {
13831 return StaticMemberFunctionFromBoundPointer;
13832 }
13833
13834 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13835 S.Diag(OvlExpr->getBeginLoc(),
13836 diag::err_invalid_form_pointer_member_function)
13837 << OvlExpr->getSourceRange();
13838 }
13839
13840 void ComplainOfInvalidConversion() const {
13841 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13842 << OvlExpr->getName() << TargetType;
13843 }
13844
13845 void ComplainMultipleMatchesFound() const {
13846 assert(Matches.size() > 1);
13847 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13848 << OvlExpr->getName() << OvlExpr->getSourceRange();
13849 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13850 /*TakingAddress=*/true);
13851 }
13852
13853 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13854
13855 int getNumMatches() const { return Matches.size(); }
13856
13857 FunctionDecl* getMatchingFunctionDecl() const {
13858 if (Matches.size() != 1) return nullptr;
13859 return Matches[0].second;
13860 }
13861
13862 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13863 if (Matches.size() != 1) return nullptr;
13864 return &Matches[0].first;
13865 }
13866};
13867}
13868
13869FunctionDecl *
13871 QualType TargetType,
13872 bool Complain,
13873 DeclAccessPair &FoundResult,
13874 bool *pHadMultipleCandidates) {
13875 assert(AddressOfExpr->getType() == Context.OverloadTy);
13876
13877 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13878 Complain);
13879 int NumMatches = Resolver.getNumMatches();
13880 FunctionDecl *Fn = nullptr;
13881 bool ShouldComplain = Complain && !Resolver.hasComplained();
13882 if (NumMatches == 0 && ShouldComplain) {
13883 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13884 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13885 else
13886 Resolver.ComplainNoMatchesFound();
13887 }
13888 else if (NumMatches > 1 && ShouldComplain)
13889 Resolver.ComplainMultipleMatchesFound();
13890 else if (NumMatches == 1) {
13891 Fn = Resolver.getMatchingFunctionDecl();
13892 assert(Fn);
13893 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13894 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13895 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13896 if (Complain) {
13897 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13898 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13899 else
13900 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13901 }
13902 }
13903
13904 if (pHadMultipleCandidates)
13905 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13906 return Fn;
13907}
13908
13912 OverloadExpr *Ovl = R.Expression;
13913 bool IsResultAmbiguous = false;
13914 FunctionDecl *Result = nullptr;
13915 DeclAccessPair DAP;
13916 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13917
13918 // Return positive for better, negative for worse, 0 for equal preference.
13919 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13920 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13921 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13922 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13923 };
13924
13925 // Don't use the AddressOfResolver because we're specifically looking for
13926 // cases where we have one overload candidate that lacks
13927 // enable_if/pass_object_size/...
13928 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13929 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13930 if (!FD)
13931 return nullptr;
13932
13934 continue;
13935
13936 // If we found a better result, update Result.
13937 auto FoundBetter = [&]() {
13938 IsResultAmbiguous = false;
13939 DAP = I.getPair();
13940 Result = FD;
13941 };
13942
13943 // We have more than one result - see if it is more
13944 // partial-ordering-constrained than the previous one.
13945 if (Result) {
13946 // Check CUDA preference first. If the candidates have differennt CUDA
13947 // preference, choose the one with higher CUDA preference. Otherwise,
13948 // choose the one with more constraints.
13949 if (getLangOpts().CUDA) {
13950 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13951 // FD has different preference than Result.
13952 if (PreferenceByCUDA != 0) {
13953 // FD is more preferable than Result.
13954 if (PreferenceByCUDA > 0)
13955 FoundBetter();
13956 continue;
13957 }
13958 }
13959 // FD has the same CUDA preference than Result. Continue to check
13960 // constraints.
13961
13962 // C++ [over.over]p5:
13963 // [...] Any given non-template function F0 is eliminated if the set
13964 // contains a second non-template function that is more
13965 // partial-ordering-constrained than F0 [...]
13966 FunctionDecl *MoreConstrained =
13968 /*IsFn1Reversed=*/false,
13969 /*IsFn2Reversed=*/false);
13970 if (MoreConstrained != FD) {
13971 if (!MoreConstrained) {
13972 IsResultAmbiguous = true;
13973 AmbiguousDecls.push_back(FD);
13974 }
13975 continue;
13976 }
13977 // FD is more constrained - replace Result with it.
13978 }
13979 FoundBetter();
13980 }
13981
13982 if (IsResultAmbiguous)
13983 return nullptr;
13984
13985 if (Result) {
13986 // We skipped over some ambiguous declarations which might be ambiguous with
13987 // the selected result.
13988 for (FunctionDecl *Skipped : AmbiguousDecls) {
13989 // If skipped candidate has different CUDA preference than the result,
13990 // there is no ambiguity. Otherwise check whether they have different
13991 // constraints.
13992 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13993 continue;
13994 if (!getMoreConstrainedFunction(Skipped, Result))
13995 return nullptr;
13996 }
13997 Pair = DAP;
13998 }
13999 return Result;
14000}
14001
14003 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14004 Expr *E = SrcExpr.get();
14005 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14006
14007 DeclAccessPair DAP;
14009 if (!Found || Found->isCPUDispatchMultiVersion() ||
14010 Found->isCPUSpecificMultiVersion())
14011 return false;
14012
14013 // Emitting multiple diagnostics for a function that is both inaccessible and
14014 // unavailable is consistent with our behavior elsewhere. So, always check
14015 // for both.
14019 if (Res.isInvalid())
14020 return false;
14021 Expr *Fixed = Res.get();
14022 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14023 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14024 else
14025 SrcExpr = Fixed;
14026 return true;
14027}
14028
14030 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14031 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14032 // C++ [over.over]p1:
14033 // [...] [Note: any redundant set of parentheses surrounding the
14034 // overloaded function name is ignored (5.1). ]
14035 // C++ [over.over]p1:
14036 // [...] The overloaded function name can be preceded by the &
14037 // operator.
14038
14039 // If we didn't actually find any template-ids, we're done.
14040 if (!ovl->hasExplicitTemplateArgs())
14041 return nullptr;
14042
14043 TemplateArgumentListInfo ExplicitTemplateArgs;
14044 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14045
14046 // Look through all of the overloaded functions, searching for one
14047 // whose type matches exactly.
14048 FunctionDecl *Matched = nullptr;
14049 for (UnresolvedSetIterator I = ovl->decls_begin(),
14050 E = ovl->decls_end(); I != E; ++I) {
14051 // C++0x [temp.arg.explicit]p3:
14052 // [...] In contexts where deduction is done and fails, or in contexts
14053 // where deduction is not done, if a template argument list is
14054 // specified and it, along with any default template arguments,
14055 // identifies a single function template specialization, then the
14056 // template-id is an lvalue for the function template specialization.
14058 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14059 if (!FunctionTemplate)
14060 continue;
14061
14062 // C++ [over.over]p2:
14063 // If the name is a function template, template argument deduction is
14064 // done (14.8.2.2), and if the argument deduction succeeds, the
14065 // resulting template argument list is used to generate a single
14066 // function template specialization, which is added to the set of
14067 // overloaded functions considered.
14068 FunctionDecl *Specialization = nullptr;
14069 TemplateDeductionInfo Info(ovl->getNameLoc());
14071 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14072 /*IsAddressOfFunction*/ true);
14074 // Make a note of the failed deduction for diagnostics.
14075 if (FailedTSC)
14076 FailedTSC->addCandidate().set(
14077 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14079 continue;
14080 }
14081
14082 assert(Specialization && "no specialization and no error?");
14083
14084 // C++ [temp.deduct.call]p6:
14085 // [...] If all successful deductions yield the same deduced A, that
14086 // deduced A is the result of deduction; otherwise, the parameter is
14087 // treated as a non-deduced context.
14088 if (Matched) {
14089 if (ForTypeDeduction &&
14091 Specialization->getType()))
14092 continue;
14093 // Multiple matches; we can't resolve to a single declaration.
14094 if (Complain) {
14095 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14096 << ovl->getName();
14098 }
14099 return nullptr;
14100 }
14101
14102 Matched = Specialization;
14103 if (FoundResult) *FoundResult = I.getPair();
14104 }
14105
14106 if (Matched &&
14107 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14108 return nullptr;
14109
14110 return Matched;
14111}
14112
14114 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14115 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14116 unsigned DiagIDForComplaining) {
14117 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14118
14120
14121 DeclAccessPair found;
14122 ExprResult SingleFunctionExpression;
14124 ovl.Expression, /*complain*/ false, &found)) {
14125 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14126 SrcExpr = ExprError();
14127 return true;
14128 }
14129
14130 // It is only correct to resolve to an instance method if we're
14131 // resolving a form that's permitted to be a pointer to member.
14132 // Otherwise we'll end up making a bound member expression, which
14133 // is illegal in all the contexts we resolve like this.
14134 if (!ovl.HasFormOfMemberPointer &&
14135 isa<CXXMethodDecl>(fn) &&
14136 cast<CXXMethodDecl>(fn)->isInstance()) {
14137 if (!complain) return false;
14138
14139 Diag(ovl.Expression->getExprLoc(),
14140 diag::err_bound_member_function)
14141 << 0 << ovl.Expression->getSourceRange();
14142
14143 // TODO: I believe we only end up here if there's a mix of
14144 // static and non-static candidates (otherwise the expression
14145 // would have 'bound member' type, not 'overload' type).
14146 // Ideally we would note which candidate was chosen and why
14147 // the static candidates were rejected.
14148 SrcExpr = ExprError();
14149 return true;
14150 }
14151
14152 // Fix the expression to refer to 'fn'.
14153 SingleFunctionExpression =
14154 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14155
14156 // If desired, do function-to-pointer decay.
14157 if (doFunctionPointerConversion) {
14158 SingleFunctionExpression =
14159 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14160 if (SingleFunctionExpression.isInvalid()) {
14161 SrcExpr = ExprError();
14162 return true;
14163 }
14164 }
14165 }
14166
14167 if (!SingleFunctionExpression.isUsable()) {
14168 if (complain) {
14169 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14170 << ovl.Expression->getName()
14171 << DestTypeForComplaining
14172 << OpRangeForComplaining
14174 NoteAllOverloadCandidates(SrcExpr.get());
14175
14176 SrcExpr = ExprError();
14177 return true;
14178 }
14179
14180 return false;
14181 }
14182
14183 SrcExpr = SingleFunctionExpression;
14184 return true;
14185}
14186
14187/// Add a single candidate to the overload set.
14189 DeclAccessPair FoundDecl,
14190 TemplateArgumentListInfo *ExplicitTemplateArgs,
14191 ArrayRef<Expr *> Args,
14192 OverloadCandidateSet &CandidateSet,
14193 bool PartialOverloading,
14194 bool KnownValid) {
14195 NamedDecl *Callee = FoundDecl.getDecl();
14196 if (isa<UsingShadowDecl>(Callee))
14197 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14198
14199 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14200 if (ExplicitTemplateArgs) {
14201 assert(!KnownValid && "Explicit template arguments?");
14202 return;
14203 }
14204 // Prevent ill-formed function decls to be added as overload candidates.
14205 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14206 return;
14207
14208 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14209 /*SuppressUserConversions=*/false,
14210 PartialOverloading);
14211 return;
14212 }
14213
14214 if (FunctionTemplateDecl *FuncTemplate
14215 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14216 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14217 ExplicitTemplateArgs, Args, CandidateSet,
14218 /*SuppressUserConversions=*/false,
14219 PartialOverloading);
14220 return;
14221 }
14222
14223 assert(!KnownValid && "unhandled case in overloaded call candidate");
14224}
14225
14227 ArrayRef<Expr *> Args,
14228 OverloadCandidateSet &CandidateSet,
14229 bool PartialOverloading) {
14230
14231#ifndef NDEBUG
14232 // Verify that ArgumentDependentLookup is consistent with the rules
14233 // in C++0x [basic.lookup.argdep]p3:
14234 //
14235 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14236 // and let Y be the lookup set produced by argument dependent
14237 // lookup (defined as follows). If X contains
14238 //
14239 // -- a declaration of a class member, or
14240 //
14241 // -- a block-scope function declaration that is not a
14242 // using-declaration, or
14243 //
14244 // -- a declaration that is neither a function or a function
14245 // template
14246 //
14247 // then Y is empty.
14248
14249 if (ULE->requiresADL()) {
14251 E = ULE->decls_end(); I != E; ++I) {
14252 assert(!(*I)->getDeclContext()->isRecord());
14253 assert(isa<UsingShadowDecl>(*I) ||
14254 !(*I)->getDeclContext()->isFunctionOrMethod());
14255 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14256 }
14257 }
14258#endif
14259
14260 // It would be nice to avoid this copy.
14261 TemplateArgumentListInfo TABuffer;
14262 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14263 if (ULE->hasExplicitTemplateArgs()) {
14264 ULE->copyTemplateArgumentsInto(TABuffer);
14265 ExplicitTemplateArgs = &TABuffer;
14266 }
14267
14269 E = ULE->decls_end(); I != E; ++I)
14270 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14271 CandidateSet, PartialOverloading,
14272 /*KnownValid*/ true);
14273
14274 if (ULE->requiresADL())
14276 Args, ExplicitTemplateArgs,
14277 CandidateSet, PartialOverloading);
14278}
14279
14281 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14282 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14283 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14284 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14285 CandidateSet, false, /*KnownValid*/ false);
14286}
14287
14288/// Determine whether a declaration with the specified name could be moved into
14289/// a different namespace.
14291 switch (Name.getCXXOverloadedOperator()) {
14292 case OO_New: case OO_Array_New:
14293 case OO_Delete: case OO_Array_Delete:
14294 return false;
14295
14296 default:
14297 return true;
14298 }
14299}
14300
14301/// Attempt to recover from an ill-formed use of a non-dependent name in a
14302/// template, where the non-dependent name was declared after the template
14303/// was defined. This is common in code written for a compilers which do not
14304/// correctly implement two-stage name lookup.
14305///
14306/// Returns true if a viable candidate was found and a diagnostic was issued.
14308 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14310 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14311 CXXRecordDecl **FoundInClass = nullptr) {
14312 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14313 return false;
14314
14315 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14316 if (DC->isTransparentContext())
14317 continue;
14318
14319 SemaRef.LookupQualifiedName(R, DC);
14320
14321 if (!R.empty()) {
14323
14324 OverloadCandidateSet Candidates(FnLoc, CSK);
14325 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14326 Candidates);
14327
14330 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14331
14332 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14333 // We either found non-function declarations or a best viable function
14334 // at class scope. A class-scope lookup result disables ADL. Don't
14335 // look past this, but let the caller know that we found something that
14336 // either is, or might be, usable in this class.
14337 if (FoundInClass) {
14338 *FoundInClass = RD;
14339 if (OR == OR_Success) {
14340 R.clear();
14341 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14342 R.resolveKind();
14343 }
14344 }
14345 return false;
14346 }
14347
14348 if (OR != OR_Success) {
14349 // There wasn't a unique best function or function template.
14350 return false;
14351 }
14352
14353 // Find the namespaces where ADL would have looked, and suggest
14354 // declaring the function there instead.
14355 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14356 Sema::AssociatedClassSet AssociatedClasses;
14357 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14358 AssociatedNamespaces,
14359 AssociatedClasses);
14360 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14362 DeclContext *Std = SemaRef.getStdNamespace();
14363 for (Sema::AssociatedNamespaceSet::iterator
14364 it = AssociatedNamespaces.begin(),
14365 end = AssociatedNamespaces.end(); it != end; ++it) {
14366 // Never suggest declaring a function within namespace 'std'.
14367 if (Std && Std->Encloses(*it))
14368 continue;
14369
14370 // Never suggest declaring a function within a namespace with a
14371 // reserved name, like __gnu_cxx.
14372 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14373 if (NS &&
14374 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14375 continue;
14376
14377 SuggestedNamespaces.insert(*it);
14378 }
14379 }
14380
14381 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14382 << R.getLookupName();
14383 if (SuggestedNamespaces.empty()) {
14384 SemaRef.Diag(Best->Function->getLocation(),
14385 diag::note_not_found_by_two_phase_lookup)
14386 << R.getLookupName() << 0;
14387 } else if (SuggestedNamespaces.size() == 1) {
14388 SemaRef.Diag(Best->Function->getLocation(),
14389 diag::note_not_found_by_two_phase_lookup)
14390 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14391 } else {
14392 // FIXME: It would be useful to list the associated namespaces here,
14393 // but the diagnostics infrastructure doesn't provide a way to produce
14394 // a localized representation of a list of items.
14395 SemaRef.Diag(Best->Function->getLocation(),
14396 diag::note_not_found_by_two_phase_lookup)
14397 << R.getLookupName() << 2;
14398 }
14399
14400 // Try to recover by calling this function.
14401 return true;
14402 }
14403
14404 R.clear();
14405 }
14406
14407 return false;
14408}
14409
14410/// Attempt to recover from ill-formed use of a non-dependent operator in a
14411/// template, where the non-dependent operator was declared after the template
14412/// was defined.
14413///
14414/// Returns true if a viable candidate was found and a diagnostic was issued.
14415static bool
14417 SourceLocation OpLoc,
14418 ArrayRef<Expr *> Args) {
14419 DeclarationName OpName =
14421 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14422 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14424 /*ExplicitTemplateArgs=*/nullptr, Args);
14425}
14426
14427namespace {
14428class BuildRecoveryCallExprRAII {
14429 Sema &SemaRef;
14430 Sema::SatisfactionStackResetRAII SatStack;
14431
14432public:
14433 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14434 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14435 SemaRef.IsBuildingRecoveryCallExpr = true;
14436 }
14437
14438 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14439};
14440}
14441
14442/// Attempts to recover from a call where no functions were found.
14443///
14444/// This function will do one of three things:
14445/// * Diagnose, recover, and return a recovery expression.
14446/// * Diagnose, fail to recover, and return ExprError().
14447/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14448/// expected to diagnose as appropriate.
14449static ExprResult
14452 SourceLocation LParenLoc,
14454 SourceLocation RParenLoc,
14455 bool EmptyLookup, bool AllowTypoCorrection) {
14456 // Do not try to recover if it is already building a recovery call.
14457 // This stops infinite loops for template instantiations like
14458 //
14459 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14460 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14461 if (SemaRef.IsBuildingRecoveryCallExpr)
14462 return ExprResult();
14463 BuildRecoveryCallExprRAII RCE(SemaRef);
14464
14465 CXXScopeSpec SS;
14466 SS.Adopt(ULE->getQualifierLoc());
14467 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14468
14469 TemplateArgumentListInfo TABuffer;
14470 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14471 if (ULE->hasExplicitTemplateArgs()) {
14472 ULE->copyTemplateArgumentsInto(TABuffer);
14473 ExplicitTemplateArgs = &TABuffer;
14474 }
14475
14476 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14478 CXXRecordDecl *FoundInClass = nullptr;
14479 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14481 ExplicitTemplateArgs, Args, &FoundInClass)) {
14482 // OK, diagnosed a two-phase lookup issue.
14483 } else if (EmptyLookup) {
14484 // Try to recover from an empty lookup with typo correction.
14485 R.clear();
14486 NoTypoCorrectionCCC NoTypoValidator{};
14487 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14488 ExplicitTemplateArgs != nullptr,
14489 dyn_cast<MemberExpr>(Fn));
14490 CorrectionCandidateCallback &Validator =
14491 AllowTypoCorrection
14492 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14493 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14494 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14495 Args))
14496 return ExprError();
14497 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14498 // We found a usable declaration of the name in a dependent base of some
14499 // enclosing class.
14500 // FIXME: We should also explain why the candidates found by name lookup
14501 // were not viable.
14502 if (SemaRef.DiagnoseDependentMemberLookup(R))
14503 return ExprError();
14504 } else {
14505 // We had viable candidates and couldn't recover; let the caller diagnose
14506 // this.
14507 return ExprResult();
14508 }
14509
14510 // If we get here, we should have issued a diagnostic and formed a recovery
14511 // lookup result.
14512 assert(!R.empty() && "lookup results empty despite recovery");
14513
14514 // If recovery created an ambiguity, just bail out.
14515 if (R.isAmbiguous()) {
14517 return ExprError();
14518 }
14519
14520 // Build an implicit member call if appropriate. Just drop the
14521 // casts and such from the call, we don't really care.
14522 ExprResult NewFn = ExprError();
14523 if ((*R.begin())->isCXXClassMember())
14524 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14525 ExplicitTemplateArgs, S);
14526 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14527 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14528 ExplicitTemplateArgs);
14529 else
14530 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14531
14532 if (NewFn.isInvalid())
14533 return ExprError();
14534
14535 // This shouldn't cause an infinite loop because we're giving it
14536 // an expression with viable lookup results, which should never
14537 // end up here.
14538 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14539 MultiExprArg(Args.data(), Args.size()),
14540 RParenLoc);
14541}
14542
14545 MultiExprArg Args,
14546 SourceLocation RParenLoc,
14547 OverloadCandidateSet *CandidateSet,
14548 ExprResult *Result) {
14549#ifndef NDEBUG
14550 if (ULE->requiresADL()) {
14551 // To do ADL, we must have found an unqualified name.
14552 assert(!ULE->getQualifier() && "qualified name with ADL");
14553
14554 // We don't perform ADL for implicit declarations of builtins.
14555 // Verify that this was correctly set up.
14556 FunctionDecl *F;
14557 if (ULE->decls_begin() != ULE->decls_end() &&
14558 ULE->decls_begin() + 1 == ULE->decls_end() &&
14559 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14560 F->getBuiltinID() && F->isImplicit())
14561 llvm_unreachable("performing ADL for builtin");
14562
14563 // We don't perform ADL in C.
14564 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14565 }
14566#endif
14567
14568 UnbridgedCastsSet UnbridgedCasts;
14569 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14570 *Result = ExprError();
14571 return true;
14572 }
14573
14574 // Add the functions denoted by the callee to the set of candidate
14575 // functions, including those from argument-dependent lookup.
14576 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14577
14578 if (getLangOpts().MSVCCompat &&
14579 CurContext->isDependentContext() && !isSFINAEContext() &&
14581
14583 if (CandidateSet->empty() ||
14584 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14586 // In Microsoft mode, if we are inside a template class member function
14587 // then create a type dependent CallExpr. The goal is to postpone name
14588 // lookup to instantiation time to be able to search into type dependent
14589 // base classes.
14590 CallExpr *CE =
14591 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14592 RParenLoc, CurFPFeatureOverrides());
14594 *Result = CE;
14595 return true;
14596 }
14597 }
14598
14599 if (CandidateSet->empty())
14600 return false;
14601
14602 UnbridgedCasts.restore();
14603 return false;
14604}
14605
14606// Guess at what the return type for an unresolvable overload should be.
14609 std::optional<QualType> Result;
14610 // Adjust Type after seeing a candidate.
14611 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14612 if (!Candidate.Function)
14613 return;
14614 if (Candidate.Function->isInvalidDecl())
14615 return;
14616 QualType T = Candidate.Function->getReturnType();
14617 if (T.isNull())
14618 return;
14619 if (!Result)
14620 Result = T;
14621 else if (Result != T)
14622 Result = QualType();
14623 };
14624
14625 // Look for an unambiguous type from a progressively larger subset.
14626 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14627 //
14628 // First, consider only the best candidate.
14629 if (Best && *Best != CS.end())
14630 ConsiderCandidate(**Best);
14631 // Next, consider only viable candidates.
14632 if (!Result)
14633 for (const auto &C : CS)
14634 if (C.Viable)
14635 ConsiderCandidate(C);
14636 // Finally, consider all candidates.
14637 if (!Result)
14638 for (const auto &C : CS)
14639 ConsiderCandidate(C);
14640
14641 if (!Result)
14642 return QualType();
14643 auto Value = *Result;
14644 if (Value.isNull() || Value->isUndeducedType())
14645 return QualType();
14646 return Value;
14647}
14648
14649/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14650/// the completed call expression. If overload resolution fails, emits
14651/// diagnostics and returns ExprError()
14654 SourceLocation LParenLoc,
14655 MultiExprArg Args,
14656 SourceLocation RParenLoc,
14657 Expr *ExecConfig,
14658 OverloadCandidateSet *CandidateSet,
14660 OverloadingResult OverloadResult,
14661 bool AllowTypoCorrection) {
14662 switch (OverloadResult) {
14663 case OR_Success: {
14664 FunctionDecl *FDecl = (*Best)->Function;
14665 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14666 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14667 return ExprError();
14668 ExprResult Res =
14669 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14670 if (Res.isInvalid())
14671 return ExprError();
14672 return SemaRef.BuildResolvedCallExpr(
14673 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14674 /*IsExecConfig=*/false,
14675 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14676 }
14677
14678 case OR_No_Viable_Function: {
14679 if (*Best != CandidateSet->end() &&
14680 CandidateSet->getKind() ==
14682 if (CXXMethodDecl *M =
14683 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14685 CandidateSet->NoteCandidates(
14687 Fn->getBeginLoc(),
14688 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14689 SemaRef, OCD_AmbiguousCandidates, Args);
14690 return ExprError();
14691 }
14692 }
14693
14694 // Try to recover by looking for viable functions which the user might
14695 // have meant to call.
14696 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14697 Args, RParenLoc,
14698 CandidateSet->empty(),
14699 AllowTypoCorrection);
14700 if (Recovery.isInvalid() || Recovery.isUsable())
14701 return Recovery;
14702
14703 // If the user passes in a function that we can't take the address of, we
14704 // generally end up emitting really bad error messages. Here, we attempt to
14705 // emit better ones.
14706 for (const Expr *Arg : Args) {
14707 if (!Arg->getType()->isFunctionType())
14708 continue;
14709 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14710 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14711 if (FD &&
14712 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14713 Arg->getExprLoc()))
14714 return ExprError();
14715 }
14716 }
14717
14718 CandidateSet->NoteCandidates(
14720 Fn->getBeginLoc(),
14721 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14722 << ULE->getName() << Fn->getSourceRange()),
14723 SemaRef, OCD_AllCandidates, Args);
14724 break;
14725 }
14726
14727 case OR_Ambiguous:
14728 CandidateSet->NoteCandidates(
14729 PartialDiagnosticAt(Fn->getBeginLoc(),
14730 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14731 << ULE->getName() << Fn->getSourceRange()),
14732 SemaRef, OCD_AmbiguousCandidates, Args);
14733 break;
14734
14735 case OR_Deleted: {
14736 FunctionDecl *FDecl = (*Best)->Function;
14737 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14738 Fn->getSourceRange(), ULE->getName(),
14739 *CandidateSet, FDecl, Args);
14740
14741 // We emitted an error for the unavailable/deleted function call but keep
14742 // the call in the AST.
14743 ExprResult Res =
14744 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14745 if (Res.isInvalid())
14746 return ExprError();
14747 return SemaRef.BuildResolvedCallExpr(
14748 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14749 /*IsExecConfig=*/false,
14750 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14751 }
14752 }
14753
14754 // Overload resolution failed, try to recover.
14755 SmallVector<Expr *, 8> SubExprs = {Fn};
14756 SubExprs.append(Args.begin(), Args.end());
14757 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14758 chooseRecoveryType(*CandidateSet, Best));
14759}
14760
14763 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14764 if (I->Viable &&
14765 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14766 I->Viable = false;
14767 I->FailureKind = ovl_fail_addr_not_available;
14768 }
14769 }
14770}
14771
14774 SourceLocation LParenLoc,
14775 MultiExprArg Args,
14776 SourceLocation RParenLoc,
14777 Expr *ExecConfig,
14778 bool AllowTypoCorrection,
14779 bool CalleesAddressIsTaken) {
14780
14784
14785 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14786 ExprResult result;
14787
14788 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14789 &result))
14790 return result;
14791
14792 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14793 // functions that aren't addressible are considered unviable.
14794 if (CalleesAddressIsTaken)
14795 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14796
14798 OverloadingResult OverloadResult =
14799 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14800
14801 // [C++23][over.call.func]
14802 // if overload resolution selects a non-static member function,
14803 // the call is ill-formed;
14805 Best != CandidateSet.end()) {
14806 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14807 M && M->isImplicitObjectMemberFunction()) {
14808 OverloadResult = OR_No_Viable_Function;
14809 }
14810 }
14811
14812 // Model the case with a call to a templated function whose definition
14813 // encloses the call and whose return type contains a placeholder type as if
14814 // the UnresolvedLookupExpr was type-dependent.
14815 if (OverloadResult == OR_Success) {
14816 const FunctionDecl *FDecl = Best->Function;
14817 if (LangOpts.CUDA)
14818 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14819 if (FDecl && FDecl->isTemplateInstantiation() &&
14820 FDecl->getReturnType()->isUndeducedType()) {
14821
14822 // Creating dependent CallExpr is not okay if the enclosing context itself
14823 // is not dependent. This situation notably arises if a non-dependent
14824 // member function calls the later-defined overloaded static function.
14825 //
14826 // For example, in
14827 // class A {
14828 // void c() { callee(1); }
14829 // static auto callee(auto x) { }
14830 // };
14831 //
14832 // Here callee(1) is unresolved at the call site, but is not inside a
14833 // dependent context. There will be no further attempt to resolve this
14834 // call if it is made dependent.
14835
14836 if (const auto *TP =
14837 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14838 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14839 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14840 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14841 }
14842 }
14843 }
14844
14845 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14846 ExecConfig, &CandidateSet, &Best,
14847 OverloadResult, AllowTypoCorrection);
14848}
14849
14853 const UnresolvedSetImpl &Fns,
14854 bool PerformADL) {
14856 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14857 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14858}
14859
14862 bool HadMultipleCandidates) {
14863 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14864 // the FoundDecl as it impedes TransformMemberExpr.
14865 // We go a bit further here: if there's no difference in UnderlyingDecl,
14866 // then using FoundDecl vs Method shouldn't make a difference either.
14867 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14868 FoundDecl = Method;
14869 // Convert the expression to match the conversion function's implicit object
14870 // parameter.
14871 ExprResult Exp;
14872 if (Method->isExplicitObjectMemberFunction())
14874 else
14876 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14877 if (Exp.isInvalid())
14878 return true;
14879
14880 if (Method->getParent()->isLambda() &&
14881 Method->getConversionType()->isBlockPointerType()) {
14882 // This is a lambda conversion to block pointer; check if the argument
14883 // was a LambdaExpr.
14884 Expr *SubE = E;
14885 auto *CE = dyn_cast<CastExpr>(SubE);
14886 if (CE && CE->getCastKind() == CK_NoOp)
14887 SubE = CE->getSubExpr();
14888 SubE = SubE->IgnoreParens();
14889 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14890 SubE = BE->getSubExpr();
14891 if (isa<LambdaExpr>(SubE)) {
14892 // For the conversion to block pointer on a lambda expression, we
14893 // construct a special BlockLiteral instead; this doesn't really make
14894 // a difference in ARC, but outside of ARC the resulting block literal
14895 // follows the normal lifetime rules for block literals instead of being
14896 // autoreleased.
14900 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14902
14903 // FIXME: This note should be produced by a CodeSynthesisContext.
14904 if (BlockExp.isInvalid())
14905 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14906 return BlockExp;
14907 }
14908 }
14909 CallExpr *CE;
14910 QualType ResultType = Method->getReturnType();
14912 ResultType = ResultType.getNonLValueExprType(Context);
14913 if (Method->isExplicitObjectMemberFunction()) {
14914 ExprResult FnExpr =
14915 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14916 HadMultipleCandidates, E->getBeginLoc());
14917 if (FnExpr.isInvalid())
14918 return ExprError();
14919 Expr *ObjectParam = Exp.get();
14920 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14921 ResultType, VK, Exp.get()->getEndLoc(),
14923 CE->setUsesMemberSyntax(true);
14924 } else {
14925 MemberExpr *ME =
14926 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14928 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14929 HadMultipleCandidates, DeclarationNameInfo(),
14930 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14931
14932 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14933 Exp.get()->getEndLoc(),
14935 }
14936
14937 if (CheckFunctionCall(Method, CE,
14938 Method->getType()->castAs<FunctionProtoType>()))
14939 return ExprError();
14940
14942}
14943
14946 const UnresolvedSetImpl &Fns,
14947 Expr *Input, bool PerformADL) {
14949 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14950 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14951 // TODO: provide better source location info.
14952 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14953
14954 if (checkPlaceholderForOverload(*this, Input))
14955 return ExprError();
14956
14957 Expr *Args[2] = { Input, nullptr };
14958 unsigned NumArgs = 1;
14959
14960 // For post-increment and post-decrement, add the implicit '0' as
14961 // the second argument, so that we know this is a post-increment or
14962 // post-decrement.
14963 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14964 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14965 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14966 SourceLocation());
14967 NumArgs = 2;
14968 }
14969
14970 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14971
14972 if (Input->isTypeDependent()) {
14974 // [C++26][expr.unary.op][expr.pre.incr]
14975 // The * operator yields an lvalue of type
14976 // The pre/post increment operators yied an lvalue.
14977 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14978 VK = VK_LValue;
14979
14980 if (Fns.empty())
14981 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14982 OK_Ordinary, OpLoc, false,
14984
14985 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14987 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14988 if (Fn.isInvalid())
14989 return ExprError();
14990 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14991 Context.DependentTy, VK_PRValue, OpLoc,
14993 }
14994
14995 // Build an empty overload set.
14997
14998 // Add the candidates from the given function set.
14999 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15000
15001 // Add operator candidates that are member functions.
15002 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15003
15004 // Add candidates from ADL.
15005 if (PerformADL) {
15006 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15007 /*ExplicitTemplateArgs*/nullptr,
15008 CandidateSet);
15009 }
15010
15011 // Add builtin operator candidates.
15012 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15013
15014 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15015
15016 // Perform overload resolution.
15018 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15019 case OR_Success: {
15020 // We found a built-in operator or an overloaded operator.
15021 FunctionDecl *FnDecl = Best->Function;
15022
15023 if (FnDecl) {
15024 Expr *Base = nullptr;
15025 // We matched an overloaded operator. Build a call to that
15026 // operator.
15027
15028 // Convert the arguments.
15029 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15030 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15031
15032 ExprResult InputInit;
15033 if (Method->isExplicitObjectMemberFunction())
15034 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15035 else
15037 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15038 if (InputInit.isInvalid())
15039 return ExprError();
15040 Base = Input = InputInit.get();
15041 } else {
15042 // Convert the arguments.
15043 ExprResult InputInit
15045 Context,
15046 FnDecl->getParamDecl(0)),
15048 Input);
15049 if (InputInit.isInvalid())
15050 return ExprError();
15051 Input = InputInit.get();
15052 }
15053
15054 // Build the actual expression node.
15055 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15056 Base, HadMultipleCandidates,
15057 OpLoc);
15058 if (FnExpr.isInvalid())
15059 return ExprError();
15060
15061 // Determine the result type.
15062 QualType ResultTy = FnDecl->getReturnType();
15064 ResultTy = ResultTy.getNonLValueExprType(Context);
15065
15066 Args[0] = Input;
15068 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15070 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15071
15072 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15073 return ExprError();
15074
15075 if (CheckFunctionCall(FnDecl, TheCall,
15076 FnDecl->getType()->castAs<FunctionProtoType>()))
15077 return ExprError();
15078 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15079 } else {
15080 // We matched a built-in operator. Convert the arguments, then
15081 // break out so that we will build the appropriate built-in
15082 // operator node.
15084 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15087 if (InputRes.isInvalid())
15088 return ExprError();
15089 Input = InputRes.get();
15090 break;
15091 }
15092 }
15093
15095 // This is an erroneous use of an operator which can be overloaded by
15096 // a non-member function. Check for non-member operators which were
15097 // defined too late to be candidates.
15098 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15099 // FIXME: Recover by calling the found function.
15100 return ExprError();
15101
15102 // No viable function; fall through to handling this as a
15103 // built-in operator, which will produce an error message for us.
15104 break;
15105
15106 case OR_Ambiguous:
15107 CandidateSet.NoteCandidates(
15108 PartialDiagnosticAt(OpLoc,
15109 PDiag(diag::err_ovl_ambiguous_oper_unary)
15111 << Input->getType() << Input->getSourceRange()),
15112 *this, OCD_AmbiguousCandidates, ArgsArray,
15113 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15114 return ExprError();
15115
15116 case OR_Deleted: {
15117 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15118 // object whose method was called. Later in NoteCandidates size of ArgsArray
15119 // is passed further and it eventually ends up compared to number of
15120 // function candidate parameters which never includes the object parameter,
15121 // so slice ArgsArray to make sure apples are compared to apples.
15122 StringLiteral *Msg = Best->Function->getDeletedMessage();
15123 CandidateSet.NoteCandidates(
15124 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15126 << (Msg != nullptr)
15127 << (Msg ? Msg->getString() : StringRef())
15128 << Input->getSourceRange()),
15129 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15130 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15131 return ExprError();
15132 }
15133 }
15134
15135 // Either we found no viable overloaded operator or we matched a
15136 // built-in operator. In either case, fall through to trying to
15137 // build a built-in operation.
15138 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15139}
15140
15143 const UnresolvedSetImpl &Fns,
15144 ArrayRef<Expr *> Args, bool PerformADL) {
15145 SourceLocation OpLoc = CandidateSet.getLocation();
15146
15147 OverloadedOperatorKind ExtraOp =
15150 : OO_None;
15151
15152 // Add the candidates from the given function set. This also adds the
15153 // rewritten candidates using these functions if necessary.
15154 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15155
15156 // As template candidates are not deduced immediately,
15157 // persist the array in the overload set.
15158 ArrayRef<Expr *> ReversedArgs;
15159 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15160 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15161 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15162
15163 // Add operator candidates that are member functions.
15164 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15165 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15166 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15168
15169 // In C++20, also add any rewritten member candidates.
15170 if (ExtraOp) {
15171 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15172 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15173 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15175 }
15176
15177 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15178 // performed for an assignment operator (nor for operator[] nor operator->,
15179 // which don't get here).
15180 if (Op != OO_Equal && PerformADL) {
15181 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15182 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15183 /*ExplicitTemplateArgs*/ nullptr,
15184 CandidateSet);
15185 if (ExtraOp) {
15186 DeclarationName ExtraOpName =
15187 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15188 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15189 /*ExplicitTemplateArgs*/ nullptr,
15190 CandidateSet);
15191 }
15192 }
15193
15194 // Add builtin operator candidates.
15195 //
15196 // FIXME: We don't add any rewritten candidates here. This is strictly
15197 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15198 // resulting in our selecting a rewritten builtin candidate. For example:
15199 //
15200 // enum class E { e };
15201 // bool operator!=(E, E) requires false;
15202 // bool k = E::e != E::e;
15203 //
15204 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15205 // it seems unreasonable to consider rewritten builtin candidates. A core
15206 // issue has been filed proposing to removed this requirement.
15207 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15208}
15209
15212 const UnresolvedSetImpl &Fns, Expr *LHS,
15213 Expr *RHS, bool PerformADL,
15214 bool AllowRewrittenCandidates,
15215 FunctionDecl *DefaultedFn) {
15216 Expr *Args[2] = { LHS, RHS };
15217 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15218
15219 if (!getLangOpts().CPlusPlus20)
15220 AllowRewrittenCandidates = false;
15221
15223
15224 // If either side is type-dependent, create an appropriate dependent
15225 // expression.
15226 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15227 if (Fns.empty()) {
15228 // If there are no functions to store, just build a dependent
15229 // BinaryOperator or CompoundAssignment.
15232 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15233 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15234 Context.DependentTy);
15236 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15238 }
15239
15240 // FIXME: save results of ADL from here?
15241 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15242 // TODO: provide better source location info in DNLoc component.
15243 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15244 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15246 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15247 if (Fn.isInvalid())
15248 return ExprError();
15249 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15250 Context.DependentTy, VK_PRValue, OpLoc,
15252 }
15253
15254 // If this is the .* operator, which is not overloadable, just
15255 // create a built-in binary operator.
15256 if (Opc == BO_PtrMemD) {
15257 auto CheckPlaceholder = [&](Expr *&Arg) {
15259 if (Res.isUsable())
15260 Arg = Res.get();
15261 return !Res.isUsable();
15262 };
15263
15264 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15265 // expression that contains placeholders (in either the LHS or RHS).
15266 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15267 return ExprError();
15268 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15269 }
15270
15271 // Always do placeholder-like conversions on the RHS.
15272 if (checkPlaceholderForOverload(*this, Args[1]))
15273 return ExprError();
15274
15275 // Do placeholder-like conversion on the LHS; note that we should
15276 // not get here with a PseudoObject LHS.
15277 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15278 if (checkPlaceholderForOverload(*this, Args[0]))
15279 return ExprError();
15280
15281 // If this is the assignment operator, we only perform overload resolution
15282 // if the left-hand side is a class or enumeration type. This is actually
15283 // a hack. The standard requires that we do overload resolution between the
15284 // various built-in candidates, but as DR507 points out, this can lead to
15285 // problems. So we do it this way, which pretty much follows what GCC does.
15286 // Note that we go the traditional code path for compound assignment forms.
15287 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15288 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15289
15290 // Build the overload set.
15293 Op, OpLoc, AllowRewrittenCandidates));
15294 if (DefaultedFn)
15295 CandidateSet.exclude(DefaultedFn);
15296 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15297
15298 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15299
15300 // Perform overload resolution.
15302 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15303 case OR_Success: {
15304 // We found a built-in operator or an overloaded operator.
15305 FunctionDecl *FnDecl = Best->Function;
15306
15307 bool IsReversed = Best->isReversed();
15308 if (IsReversed)
15309 std::swap(Args[0], Args[1]);
15310
15311 if (FnDecl) {
15312
15313 if (FnDecl->isInvalidDecl())
15314 return ExprError();
15315
15316 Expr *Base = nullptr;
15317 // We matched an overloaded operator. Build a call to that
15318 // operator.
15319
15320 OverloadedOperatorKind ChosenOp =
15322
15323 // C++2a [over.match.oper]p9:
15324 // If a rewritten operator== candidate is selected by overload
15325 // resolution for an operator@, its return type shall be cv bool
15326 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15327 !FnDecl->getReturnType()->isBooleanType()) {
15328 bool IsExtension =
15330 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15331 : diag::err_ovl_rewrite_equalequal_not_bool)
15332 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15333 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15334 Diag(FnDecl->getLocation(), diag::note_declared_at);
15335 if (!IsExtension)
15336 return ExprError();
15337 }
15338
15339 if (AllowRewrittenCandidates && !IsReversed &&
15340 CandidateSet.getRewriteInfo().isReversible()) {
15341 // We could have reversed this operator, but didn't. Check if some
15342 // reversed form was a viable candidate, and if so, if it had a
15343 // better conversion for either parameter. If so, this call is
15344 // formally ambiguous, and allowing it is an extension.
15346 for (OverloadCandidate &Cand : CandidateSet) {
15347 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15348 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15349 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15351 *this, OpLoc, Cand.Conversions[ArgIdx],
15352 Best->Conversions[ArgIdx]) ==
15354 AmbiguousWith.push_back(Cand.Function);
15355 break;
15356 }
15357 }
15358 }
15359 }
15360
15361 if (!AmbiguousWith.empty()) {
15362 bool AmbiguousWithSelf =
15363 AmbiguousWith.size() == 1 &&
15364 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15365 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15367 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15368 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15369 if (AmbiguousWithSelf) {
15370 Diag(FnDecl->getLocation(),
15371 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15372 // Mark member== const or provide matching != to disallow reversed
15373 // args. Eg.
15374 // struct S { bool operator==(const S&); };
15375 // S()==S();
15376 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15377 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15378 !MD->isConst() &&
15379 !MD->hasCXXExplicitFunctionObjectParameter() &&
15380 Context.hasSameUnqualifiedType(
15381 MD->getFunctionObjectParameterType(),
15382 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15383 Context.hasSameUnqualifiedType(
15384 MD->getFunctionObjectParameterType(),
15385 Args[0]->getType()) &&
15386 Context.hasSameUnqualifiedType(
15387 MD->getFunctionObjectParameterType(),
15388 Args[1]->getType()))
15389 Diag(FnDecl->getLocation(),
15390 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15391 } else {
15392 Diag(FnDecl->getLocation(),
15393 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15394 for (auto *F : AmbiguousWith)
15395 Diag(F->getLocation(),
15396 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15397 }
15398 }
15399 }
15400
15401 // Check for nonnull = nullable.
15402 // This won't be caught in the arg's initialization: the parameter to
15403 // the assignment operator is not marked nonnull.
15404 if (Op == OO_Equal)
15406 Args[1]->getType(), OpLoc);
15407
15408 // Convert the arguments.
15409 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15410 // Best->Access is only meaningful for class members.
15411 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15412
15413 ExprResult Arg0, Arg1;
15414 unsigned ParamIdx = 0;
15415 if (Method->isExplicitObjectMemberFunction()) {
15416 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15417 ParamIdx = 1;
15418 } else {
15420 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15421 }
15424 Context, FnDecl->getParamDecl(ParamIdx)),
15425 SourceLocation(), Args[1]);
15426 if (Arg0.isInvalid() || Arg1.isInvalid())
15427 return ExprError();
15428
15429 Base = Args[0] = Arg0.getAs<Expr>();
15430 Args[1] = RHS = Arg1.getAs<Expr>();
15431 } else {
15432 // Convert the arguments.
15435 FnDecl->getParamDecl(0)),
15436 SourceLocation(), Args[0]);
15437 if (Arg0.isInvalid())
15438 return ExprError();
15439
15440 ExprResult Arg1 =
15443 FnDecl->getParamDecl(1)),
15444 SourceLocation(), Args[1]);
15445 if (Arg1.isInvalid())
15446 return ExprError();
15447 Args[0] = LHS = Arg0.getAs<Expr>();
15448 Args[1] = RHS = Arg1.getAs<Expr>();
15449 }
15450
15451 // Build the actual expression node.
15452 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15453 Best->FoundDecl, Base,
15454 HadMultipleCandidates, OpLoc);
15455 if (FnExpr.isInvalid())
15456 return ExprError();
15457
15458 // Determine the result type.
15459 QualType ResultTy = FnDecl->getReturnType();
15461 ResultTy = ResultTy.getNonLValueExprType(Context);
15462
15463 CallExpr *TheCall;
15464 ArrayRef<const Expr *> ArgsArray(Args, 2);
15465 const Expr *ImplicitThis = nullptr;
15466
15467 // We always create a CXXOperatorCallExpr, even for explicit object
15468 // members; CodeGen should take care not to emit the this pointer.
15470 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15472 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15473
15474 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15475 Method && Method->isImplicitObjectMemberFunction()) {
15476 // Cut off the implicit 'this'.
15477 ImplicitThis = ArgsArray[0];
15478 ArgsArray = ArgsArray.slice(1);
15479 }
15480
15481 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15482 FnDecl))
15483 return ExprError();
15484
15485 if (Op == OO_Equal) {
15486 // Check for a self move.
15487 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15488 // lifetime check.
15490 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15491 Args[1]);
15492 }
15493 if (ImplicitThis) {
15494 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15495 QualType ThisTypeFromDecl = Context.getPointerType(
15496 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15497
15498 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15499 ThisTypeFromDecl);
15500 }
15501
15502 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15503 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15505
15506 ExprResult R = MaybeBindToTemporary(TheCall);
15507 if (R.isInvalid())
15508 return ExprError();
15509
15510 R = CheckForImmediateInvocation(R, FnDecl);
15511 if (R.isInvalid())
15512 return ExprError();
15513
15514 // For a rewritten candidate, we've already reversed the arguments
15515 // if needed. Perform the rest of the rewrite now.
15516 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15517 (Op == OO_Spaceship && IsReversed)) {
15518 if (Op == OO_ExclaimEqual) {
15519 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15520 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15521 } else {
15522 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15523 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15524 Expr *ZeroLiteral =
15526
15529 Ctx.Entity = FnDecl;
15531
15533 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15534 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15535 /*AllowRewrittenCandidates=*/false);
15536
15538 }
15539 if (R.isInvalid())
15540 return ExprError();
15541 } else {
15542 assert(ChosenOp == Op && "unexpected operator name");
15543 }
15544
15545 // Make a note in the AST if we did any rewriting.
15546 if (Best->RewriteKind != CRK_None)
15547 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15548
15549 return R;
15550 } else {
15551 // We matched a built-in operator. Convert the arguments, then
15552 // break out so that we will build the appropriate built-in
15553 // operator node.
15555 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15558 if (ArgsRes0.isInvalid())
15559 return ExprError();
15560 Args[0] = ArgsRes0.get();
15561
15563 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15566 if (ArgsRes1.isInvalid())
15567 return ExprError();
15568 Args[1] = ArgsRes1.get();
15569 break;
15570 }
15571 }
15572
15573 case OR_No_Viable_Function: {
15574 // C++ [over.match.oper]p9:
15575 // If the operator is the operator , [...] and there are no
15576 // viable functions, then the operator is assumed to be the
15577 // built-in operator and interpreted according to clause 5.
15578 if (Opc == BO_Comma)
15579 break;
15580
15581 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15582 // compare result using '==' and '<'.
15583 if (DefaultedFn && Opc == BO_Cmp) {
15584 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15585 Args[1], DefaultedFn);
15586 if (E.isInvalid() || E.isUsable())
15587 return E;
15588 }
15589
15590 // For class as left operand for assignment or compound assignment
15591 // operator do not fall through to handling in built-in, but report that
15592 // no overloaded assignment operator found
15594 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15595 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15596 Args, OpLoc);
15597 DeferDiagsRAII DDR(*this,
15598 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15599 if (Args[0]->getType()->isRecordType() &&
15600 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15601 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15603 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15604 if (Args[0]->getType()->isIncompleteType()) {
15605 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15606 << Args[0]->getType()
15607 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15608 }
15609 } else {
15610 // This is an erroneous use of an operator which can be overloaded by
15611 // a non-member function. Check for non-member operators which were
15612 // defined too late to be candidates.
15613 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15614 // FIXME: Recover by calling the found function.
15615 return ExprError();
15616
15617 // No viable function; try to create a built-in operation, which will
15618 // produce an error. Then, show the non-viable candidates.
15619 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15620 }
15621 assert(Result.isInvalid() &&
15622 "C++ binary operator overloading is missing candidates!");
15623 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15624 return Result;
15625 }
15626
15627 case OR_Ambiguous:
15628 CandidateSet.NoteCandidates(
15629 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15631 << Args[0]->getType()
15632 << Args[1]->getType()
15633 << Args[0]->getSourceRange()
15634 << Args[1]->getSourceRange()),
15636 OpLoc);
15637 return ExprError();
15638
15639 case OR_Deleted: {
15640 if (isImplicitlyDeleted(Best->Function)) {
15641 FunctionDecl *DeletedFD = Best->Function;
15643 if (DFK.isSpecialMember()) {
15644 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15645 << Args[0]->getType() << DFK.asSpecialMember();
15646 } else {
15647 assert(DFK.isComparison());
15648 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15649 << Args[0]->getType() << DeletedFD;
15650 }
15651
15652 // The user probably meant to call this special member. Just
15653 // explain why it's deleted.
15654 NoteDeletedFunction(DeletedFD);
15655 return ExprError();
15656 }
15657
15658 StringLiteral *Msg = Best->Function->getDeletedMessage();
15659 CandidateSet.NoteCandidates(
15661 OpLoc,
15662 PDiag(diag::err_ovl_deleted_oper)
15663 << getOperatorSpelling(Best->Function->getDeclName()
15664 .getCXXOverloadedOperator())
15665 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15666 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15668 OpLoc);
15669 return ExprError();
15670 }
15671 }
15672
15673 // We matched a built-in operator; build it.
15674 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15675}
15676
15678 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15679 FunctionDecl *DefaultedFn) {
15680 const ComparisonCategoryInfo *Info =
15681 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15682 // If we're not producing a known comparison category type, we can't
15683 // synthesize a three-way comparison. Let the caller diagnose this.
15684 if (!Info)
15685 return ExprResult((Expr*)nullptr);
15686
15687 // If we ever want to perform this synthesis more generally, we will need to
15688 // apply the temporary materialization conversion to the operands.
15689 assert(LHS->isGLValue() && RHS->isGLValue() &&
15690 "cannot use prvalue expressions more than once");
15691 Expr *OrigLHS = LHS;
15692 Expr *OrigRHS = RHS;
15693
15694 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15695 // each of them multiple times below.
15696 LHS = new (Context)
15697 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15698 LHS->getObjectKind(), LHS);
15699 RHS = new (Context)
15700 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15701 RHS->getObjectKind(), RHS);
15702
15703 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15704 DefaultedFn);
15705 if (Eq.isInvalid())
15706 return ExprError();
15707
15708 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15709 true, DefaultedFn);
15710 if (Less.isInvalid())
15711 return ExprError();
15712
15714 if (Info->isPartial()) {
15715 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15716 DefaultedFn);
15717 if (Greater.isInvalid())
15718 return ExprError();
15719 }
15720
15721 // Form the list of comparisons we're going to perform.
15722 struct Comparison {
15723 ExprResult Cmp;
15725 } Comparisons[4] =
15731 };
15732
15733 int I = Info->isPartial() ? 3 : 2;
15734
15735 // Combine the comparisons with suitable conditional expressions.
15737 for (; I >= 0; --I) {
15738 // Build a reference to the comparison category constant.
15739 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15740 // FIXME: Missing a constant for a comparison category. Diagnose this?
15741 if (!VI)
15742 return ExprResult((Expr*)nullptr);
15743 ExprResult ThisResult =
15745 if (ThisResult.isInvalid())
15746 return ExprError();
15747
15748 // Build a conditional unless this is the final case.
15749 if (Result.get()) {
15750 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15751 ThisResult.get(), Result.get());
15752 if (Result.isInvalid())
15753 return ExprError();
15754 } else {
15755 Result = ThisResult;
15756 }
15757 }
15758
15759 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15760 // bind the OpaqueValueExprs before they're (repeatedly) used.
15761 Expr *SyntacticForm = BinaryOperator::Create(
15762 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15763 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15765 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15766 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15767}
15768
15770 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15771 MultiExprArg Args, SourceLocation LParenLoc) {
15772
15773 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15774 unsigned NumParams = Proto->getNumParams();
15775 unsigned NumArgsSlots =
15776 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15777 // Build the full argument list for the method call (the implicit object
15778 // parameter is placed at the beginning of the list).
15779 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15780 bool IsError = false;
15781 // Initialize the implicit object parameter.
15782 // Check the argument types.
15783 for (unsigned i = 0; i != NumParams; i++) {
15784 Expr *Arg;
15785 if (i < Args.size()) {
15786 Arg = Args[i];
15787 ExprResult InputInit =
15789 S.Context, Method->getParamDecl(i)),
15790 SourceLocation(), Arg);
15791 IsError |= InputInit.isInvalid();
15792 Arg = InputInit.getAs<Expr>();
15793 } else {
15794 ExprResult DefArg =
15795 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15796 if (DefArg.isInvalid()) {
15797 IsError = true;
15798 break;
15799 }
15800 Arg = DefArg.getAs<Expr>();
15801 }
15802
15803 MethodArgs.push_back(Arg);
15804 }
15805 return IsError;
15806}
15807
15809 SourceLocation RLoc,
15810 Expr *Base,
15811 MultiExprArg ArgExpr) {
15813 Args.push_back(Base);
15814 for (auto *e : ArgExpr) {
15815 Args.push_back(e);
15816 }
15817 DeclarationName OpName =
15818 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15819
15820 SourceRange Range = ArgExpr.empty()
15821 ? SourceRange{}
15822 : SourceRange(ArgExpr.front()->getBeginLoc(),
15823 ArgExpr.back()->getEndLoc());
15824
15825 // If either side is type-dependent, create an appropriate dependent
15826 // expression.
15828
15829 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15830 // CHECKME: no 'operator' keyword?
15831 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15832 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15834 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15835 if (Fn.isInvalid())
15836 return ExprError();
15837 // Can't add any actual overloads yet
15838
15839 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15840 Context.DependentTy, VK_PRValue, RLoc,
15842 }
15843
15844 // Handle placeholders
15845 UnbridgedCastsSet UnbridgedCasts;
15846 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15847 return ExprError();
15848 }
15849 // Build an empty overload set.
15851
15852 // Subscript can only be overloaded as a member function.
15853
15854 // Add operator candidates that are member functions.
15855 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15856
15857 // Add builtin operator candidates.
15858 if (Args.size() == 2)
15859 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15860
15861 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15862
15863 // Perform overload resolution.
15865 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15866 case OR_Success: {
15867 // We found a built-in operator or an overloaded operator.
15868 FunctionDecl *FnDecl = Best->Function;
15869
15870 if (FnDecl) {
15871 // We matched an overloaded operator. Build a call to that
15872 // operator.
15873
15874 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15875
15876 // Convert the arguments.
15878 SmallVector<Expr *, 2> MethodArgs;
15879
15880 // Initialize the object parameter.
15881 if (Method->isExplicitObjectMemberFunction()) {
15882 ExprResult Res =
15884 if (Res.isInvalid())
15885 return ExprError();
15886 Args[0] = Res.get();
15887 ArgExpr = Args;
15888 } else {
15890 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15891 if (Arg0.isInvalid())
15892 return ExprError();
15893
15894 MethodArgs.push_back(Arg0.get());
15895 }
15896
15898 *this, MethodArgs, Method, ArgExpr, LLoc);
15899 if (IsError)
15900 return ExprError();
15901
15902 // Build the actual expression node.
15903 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15904 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15906 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15907 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15908 if (FnExpr.isInvalid())
15909 return ExprError();
15910
15911 // Determine the result type
15912 QualType ResultTy = FnDecl->getReturnType();
15914 ResultTy = ResultTy.getNonLValueExprType(Context);
15915
15917 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15919
15920 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15921 return ExprError();
15922
15923 if (CheckFunctionCall(Method, TheCall,
15924 Method->getType()->castAs<FunctionProtoType>()))
15925 return ExprError();
15926
15928 FnDecl);
15929 } else {
15930 // We matched a built-in operator. Convert the arguments, then
15931 // break out so that we will build the appropriate built-in
15932 // operator node.
15934 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15937 if (ArgsRes0.isInvalid())
15938 return ExprError();
15939 Args[0] = ArgsRes0.get();
15940
15942 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15945 if (ArgsRes1.isInvalid())
15946 return ExprError();
15947 Args[1] = ArgsRes1.get();
15948
15949 break;
15950 }
15951 }
15952
15953 case OR_No_Viable_Function: {
15955 CandidateSet.empty()
15956 ? (PDiag(diag::err_ovl_no_oper)
15957 << Args[0]->getType() << /*subscript*/ 0
15958 << Args[0]->getSourceRange() << Range)
15959 : (PDiag(diag::err_ovl_no_viable_subscript)
15960 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15961 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15962 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15963 return ExprError();
15964 }
15965
15966 case OR_Ambiguous:
15967 if (Args.size() == 2) {
15968 CandidateSet.NoteCandidates(
15970 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15971 << "[]" << Args[0]->getType() << Args[1]->getType()
15972 << Args[0]->getSourceRange() << Range),
15973 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15974 } else {
15975 CandidateSet.NoteCandidates(
15977 PDiag(diag::err_ovl_ambiguous_subscript_call)
15978 << Args[0]->getType()
15979 << Args[0]->getSourceRange() << Range),
15980 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15981 }
15982 return ExprError();
15983
15984 case OR_Deleted: {
15985 StringLiteral *Msg = Best->Function->getDeletedMessage();
15986 CandidateSet.NoteCandidates(
15988 PDiag(diag::err_ovl_deleted_oper)
15989 << "[]" << (Msg != nullptr)
15990 << (Msg ? Msg->getString() : StringRef())
15991 << Args[0]->getSourceRange() << Range),
15992 *this, OCD_AllCandidates, Args, "[]", LLoc);
15993 return ExprError();
15994 }
15995 }
15996
15997 // We matched a built-in operator; build it.
15998 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15999}
16000
16002 SourceLocation LParenLoc,
16003 MultiExprArg Args,
16004 SourceLocation RParenLoc,
16005 Expr *ExecConfig, bool IsExecConfig,
16006 bool AllowRecovery) {
16007 assert(MemExprE->getType() == Context.BoundMemberTy ||
16008 MemExprE->getType() == Context.OverloadTy);
16009
16010 // Dig out the member expression. This holds both the object
16011 // argument and the member function we're referring to.
16012 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16013
16014 // Determine whether this is a call to a pointer-to-member function.
16015 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16016 assert(op->getType() == Context.BoundMemberTy);
16017 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16018
16019 QualType fnType =
16020 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16021
16022 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16023 QualType resultType = proto->getCallResultType(Context);
16025
16026 // Check that the object type isn't more qualified than the
16027 // member function we're calling.
16028 Qualifiers funcQuals = proto->getMethodQuals();
16029
16030 QualType objectType = op->getLHS()->getType();
16031 if (op->getOpcode() == BO_PtrMemI)
16032 objectType = objectType->castAs<PointerType>()->getPointeeType();
16033 Qualifiers objectQuals = objectType.getQualifiers();
16034
16035 Qualifiers difference = objectQuals - funcQuals;
16036 difference.removeObjCGCAttr();
16037 difference.removeAddressSpace();
16038 if (difference) {
16039 std::string qualsString = difference.getAsString();
16040 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16041 << fnType.getUnqualifiedType()
16042 << qualsString
16043 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16044 }
16045
16047 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16049
16050 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16051 call, nullptr))
16052 return ExprError();
16053
16054 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16055 return ExprError();
16056
16057 if (CheckOtherCall(call, proto))
16058 return ExprError();
16059
16060 return MaybeBindToTemporary(call);
16061 }
16062
16063 // We only try to build a recovery expr at this level if we can preserve
16064 // the return type, otherwise we return ExprError() and let the caller
16065 // recover.
16066 auto BuildRecoveryExpr = [&](QualType Type) {
16067 if (!AllowRecovery)
16068 return ExprError();
16069 std::vector<Expr *> SubExprs = {MemExprE};
16070 llvm::append_range(SubExprs, Args);
16071 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16072 Type);
16073 };
16074 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16075 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16076 RParenLoc, CurFPFeatureOverrides());
16077
16078 UnbridgedCastsSet UnbridgedCasts;
16079 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16080 return ExprError();
16081
16082 MemberExpr *MemExpr;
16083 CXXMethodDecl *Method = nullptr;
16084 bool HadMultipleCandidates = false;
16085 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16086 NestedNameSpecifier Qualifier = std::nullopt;
16087 if (isa<MemberExpr>(NakedMemExpr)) {
16088 MemExpr = cast<MemberExpr>(NakedMemExpr);
16090 FoundDecl = MemExpr->getFoundDecl();
16091 Qualifier = MemExpr->getQualifier();
16092 UnbridgedCasts.restore();
16093 } else {
16094 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16095 Qualifier = UnresExpr->getQualifier();
16096
16097 QualType ObjectType = UnresExpr->getBaseType();
16098 Expr::Classification ObjectClassification
16100 : UnresExpr->getBase()->Classify(Context);
16101
16102 // Add overload candidates
16103 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16105
16106 // FIXME: avoid copy.
16107 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16108 if (UnresExpr->hasExplicitTemplateArgs()) {
16109 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16110 TemplateArgs = &TemplateArgsBuffer;
16111 }
16112
16114 E = UnresExpr->decls_end(); I != E; ++I) {
16115
16116 QualType ExplicitObjectType = ObjectType;
16117
16118 NamedDecl *Func = *I;
16119 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16121 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16122
16123 bool HasExplicitParameter = false;
16124 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16125 M && M->hasCXXExplicitFunctionObjectParameter())
16126 HasExplicitParameter = true;
16127 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16128 M &&
16129 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16130 HasExplicitParameter = true;
16131
16132 if (HasExplicitParameter)
16133 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16134
16135 // Microsoft supports direct constructor calls.
16136 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16138 CandidateSet,
16139 /*SuppressUserConversions*/ false);
16140 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16141 // If explicit template arguments were provided, we can't call a
16142 // non-template member function.
16143 if (TemplateArgs)
16144 continue;
16145
16146 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16147 ObjectClassification, Args, CandidateSet,
16148 /*SuppressUserConversions=*/false);
16149 } else {
16151 I.getPair(), ActingDC, TemplateArgs,
16152 ExplicitObjectType, ObjectClassification,
16153 Args, CandidateSet,
16154 /*SuppressUserConversions=*/false);
16155 }
16156 }
16157
16158 HadMultipleCandidates = (CandidateSet.size() > 1);
16159
16160 DeclarationName DeclName = UnresExpr->getMemberName();
16161
16162 UnbridgedCasts.restore();
16163
16165 bool Succeeded = false;
16166 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16167 Best)) {
16168 case OR_Success:
16169 Method = cast<CXXMethodDecl>(Best->Function);
16170 FoundDecl = Best->FoundDecl;
16171 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16172 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16173 break;
16174 // If FoundDecl is different from Method (such as if one is a template
16175 // and the other a specialization), make sure DiagnoseUseOfDecl is
16176 // called on both.
16177 // FIXME: This would be more comprehensively addressed by modifying
16178 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16179 // being used.
16180 if (Method != FoundDecl.getDecl() &&
16182 break;
16183 Succeeded = true;
16184 break;
16185
16187 CandidateSet.NoteCandidates(
16189 UnresExpr->getMemberLoc(),
16190 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16191 << DeclName << MemExprE->getSourceRange()),
16192 *this, OCD_AllCandidates, Args);
16193 break;
16194 case OR_Ambiguous:
16195 CandidateSet.NoteCandidates(
16196 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16197 PDiag(diag::err_ovl_ambiguous_member_call)
16198 << DeclName << MemExprE->getSourceRange()),
16199 *this, OCD_AmbiguousCandidates, Args);
16200 break;
16201 case OR_Deleted:
16203 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16204 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16205 break;
16206 }
16207 // Overload resolution fails, try to recover.
16208 if (!Succeeded)
16209 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16210
16211 ExprResult Res =
16212 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16213 if (Res.isInvalid())
16214 return ExprError();
16215 MemExprE = Res.get();
16216
16217 // If overload resolution picked a static member
16218 // build a non-member call based on that function.
16219 if (Method->isStatic()) {
16220 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16221 ExecConfig, IsExecConfig);
16222 }
16223
16224 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16225 }
16226
16227 QualType ResultType = Method->getReturnType();
16229 ResultType = ResultType.getNonLValueExprType(Context);
16230
16231 assert(Method && "Member call to something that isn't a method?");
16232 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16233
16234 CallExpr *TheCall = nullptr;
16236 if (Method->isExplicitObjectMemberFunction()) {
16237 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16238 NewArgs))
16239 return ExprError();
16240
16241 // Build the actual expression node.
16242 ExprResult FnExpr =
16243 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16244 HadMultipleCandidates, MemExpr->getExprLoc());
16245 if (FnExpr.isInvalid())
16246 return ExprError();
16247
16248 TheCall =
16249 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16250 CurFPFeatureOverrides(), Proto->getNumParams());
16251 TheCall->setUsesMemberSyntax(true);
16252 } else {
16253 // Convert the object argument (for a non-static member function call).
16255 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16256 if (ObjectArg.isInvalid())
16257 return ExprError();
16258 MemExpr->setBase(ObjectArg.get());
16259 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16260 RParenLoc, CurFPFeatureOverrides(),
16261 Proto->getNumParams());
16262 }
16263
16264 // Check for a valid return type.
16265 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16266 TheCall, Method))
16267 return BuildRecoveryExpr(ResultType);
16268
16269 // Convert the rest of the arguments
16270 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16271 RParenLoc))
16272 return BuildRecoveryExpr(ResultType);
16273
16274 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16275
16276 if (CheckFunctionCall(Method, TheCall, Proto))
16277 return ExprError();
16278
16279 // In the case the method to call was not selected by the overloading
16280 // resolution process, we still need to handle the enable_if attribute. Do
16281 // that here, so it will not hide previous -- and more relevant -- errors.
16282 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16283 if (const EnableIfAttr *Attr =
16284 CheckEnableIf(Method, LParenLoc, Args, true)) {
16285 Diag(MemE->getMemberLoc(),
16286 diag::err_ovl_no_viable_member_function_in_call)
16287 << Method << Method->getSourceRange();
16288 Diag(Method->getLocation(),
16289 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16290 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16291 return ExprError();
16292 }
16293 }
16294
16296 TheCall->getDirectCallee()->isPureVirtual()) {
16297 const FunctionDecl *MD = TheCall->getDirectCallee();
16298
16299 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16301 Diag(MemExpr->getBeginLoc(),
16302 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16304 << MD->getParent();
16305
16306 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16307 if (getLangOpts().AppleKext)
16308 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16309 << MD->getParent() << MD->getDeclName();
16310 }
16311 }
16312
16313 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16314 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16315 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16316 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16317 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16318 MemExpr->getMemberLoc());
16319 }
16320
16322 TheCall->getDirectCallee());
16323}
16324
16327 SourceLocation LParenLoc,
16328 MultiExprArg Args,
16329 SourceLocation RParenLoc) {
16330 if (checkPlaceholderForOverload(*this, Obj))
16331 return ExprError();
16332 ExprResult Object = Obj;
16333
16334 UnbridgedCastsSet UnbridgedCasts;
16335 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16336 return ExprError();
16337
16338 assert(Object.get()->getType()->isRecordType() &&
16339 "Requires object type argument");
16340
16341 // C++ [over.call.object]p1:
16342 // If the primary-expression E in the function call syntax
16343 // evaluates to a class object of type "cv T", then the set of
16344 // candidate functions includes at least the function call
16345 // operators of T. The function call operators of T are obtained by
16346 // ordinary lookup of the name operator() in the context of
16347 // (E).operator().
16348 OverloadCandidateSet CandidateSet(LParenLoc,
16350 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16351
16352 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16353 diag::err_incomplete_object_call, Object.get()))
16354 return true;
16355
16356 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16357 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16360
16361 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16362 Oper != OperEnd; ++Oper) {
16363 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16364 Object.get()->Classify(Context), Args, CandidateSet,
16365 /*SuppressUserConversion=*/false);
16366 }
16367
16368 // When calling a lambda, both the call operator, and
16369 // the conversion operator to function pointer
16370 // are considered. But when constraint checking
16371 // on the call operator fails, it will also fail on the
16372 // conversion operator as the constraints are always the same.
16373 // As the user probably does not intend to perform a surrogate call,
16374 // we filter them out to produce better error diagnostics, ie to avoid
16375 // showing 2 failed overloads instead of one.
16376 bool IgnoreSurrogateFunctions = false;
16377 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16378 const OverloadCandidate &Candidate = *CandidateSet.begin();
16379 if (!Candidate.Viable &&
16381 IgnoreSurrogateFunctions = true;
16382 }
16383
16384 // C++ [over.call.object]p2:
16385 // In addition, for each (non-explicit in C++0x) conversion function
16386 // declared in T of the form
16387 //
16388 // operator conversion-type-id () cv-qualifier;
16389 //
16390 // where cv-qualifier is the same cv-qualification as, or a
16391 // greater cv-qualification than, cv, and where conversion-type-id
16392 // denotes the type "pointer to function of (P1,...,Pn) returning
16393 // R", or the type "reference to pointer to function of
16394 // (P1,...,Pn) returning R", or the type "reference to function
16395 // of (P1,...,Pn) returning R", a surrogate call function [...]
16396 // is also considered as a candidate function. Similarly,
16397 // surrogate call functions are added to the set of candidate
16398 // functions for each conversion function declared in an
16399 // accessible base class provided the function is not hidden
16400 // within T by another intervening declaration.
16401 const auto &Conversions = Record->getVisibleConversionFunctions();
16402 for (auto I = Conversions.begin(), E = Conversions.end();
16403 !IgnoreSurrogateFunctions && I != E; ++I) {
16404 NamedDecl *D = *I;
16405 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16406 if (isa<UsingShadowDecl>(D))
16407 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16408
16409 // Skip over templated conversion functions; they aren't
16410 // surrogates.
16412 continue;
16413
16415 if (!Conv->isExplicit()) {
16416 // Strip the reference type (if any) and then the pointer type (if
16417 // any) to get down to what might be a function type.
16418 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16419 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16420 ConvType = ConvPtrType->getPointeeType();
16421
16422 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16423 {
16424 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16425 Object.get(), Args, CandidateSet);
16426 }
16427 }
16428 }
16429
16430 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16431
16432 // Perform overload resolution.
16434 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16435 Best)) {
16436 case OR_Success:
16437 // Overload resolution succeeded; we'll build the appropriate call
16438 // below.
16439 break;
16440
16441 case OR_No_Viable_Function: {
16443 CandidateSet.empty()
16444 ? (PDiag(diag::err_ovl_no_oper)
16445 << Object.get()->getType() << /*call*/ 1
16446 << Object.get()->getSourceRange())
16447 : (PDiag(diag::err_ovl_no_viable_object_call)
16448 << Object.get()->getType() << Object.get()->getSourceRange());
16449 CandidateSet.NoteCandidates(
16450 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16451 OCD_AllCandidates, Args);
16452 break;
16453 }
16454 case OR_Ambiguous:
16455 if (!R.isAmbiguous())
16456 CandidateSet.NoteCandidates(
16457 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16458 PDiag(diag::err_ovl_ambiguous_object_call)
16459 << Object.get()->getType()
16460 << Object.get()->getSourceRange()),
16461 *this, OCD_AmbiguousCandidates, Args);
16462 break;
16463
16464 case OR_Deleted: {
16465 // FIXME: Is this diagnostic here really necessary? It seems that
16466 // 1. we don't have any tests for this diagnostic, and
16467 // 2. we already issue err_deleted_function_use for this later on anyway.
16468 StringLiteral *Msg = Best->Function->getDeletedMessage();
16469 CandidateSet.NoteCandidates(
16470 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16471 PDiag(diag::err_ovl_deleted_object_call)
16472 << Object.get()->getType() << (Msg != nullptr)
16473 << (Msg ? Msg->getString() : StringRef())
16474 << Object.get()->getSourceRange()),
16475 *this, OCD_AllCandidates, Args);
16476 break;
16477 }
16478 }
16479
16480 if (Best == CandidateSet.end())
16481 return true;
16482
16483 UnbridgedCasts.restore();
16484
16485 if (Best->Function == nullptr) {
16486 // Since there is no function declaration, this is one of the
16487 // surrogate candidates. Dig out the conversion function.
16488 CXXConversionDecl *Conv
16490 Best->Conversions[0].UserDefined.ConversionFunction);
16491
16492 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16493 Best->FoundDecl);
16494 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16495 return ExprError();
16496 assert(Conv == Best->FoundDecl.getDecl() &&
16497 "Found Decl & conversion-to-functionptr should be same, right?!");
16498 // We selected one of the surrogate functions that converts the
16499 // object parameter to a function pointer. Perform the conversion
16500 // on the object argument, then let BuildCallExpr finish the job.
16501
16502 // Create an implicit member expr to refer to the conversion operator.
16503 // and then call it.
16504 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16505 Conv, HadMultipleCandidates);
16506 if (Call.isInvalid())
16507 return ExprError();
16508 // Record usage of conversion in an implicit cast.
16510 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16511 nullptr, VK_PRValue, CurFPFeatureOverrides());
16512
16513 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16514 }
16515
16516 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16517
16518 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16519 // that calls this method, using Object for the implicit object
16520 // parameter and passing along the remaining arguments.
16521 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16522
16523 // An error diagnostic has already been printed when parsing the declaration.
16524 if (Method->isInvalidDecl())
16525 return ExprError();
16526
16527 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16528 unsigned NumParams = Proto->getNumParams();
16529
16530 DeclarationNameInfo OpLocInfo(
16531 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16532 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16533 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16534 Obj, HadMultipleCandidates,
16535 OpLocInfo.getLoc(),
16536 OpLocInfo.getInfo());
16537 if (NewFn.isInvalid())
16538 return true;
16539
16540 SmallVector<Expr *, 8> MethodArgs;
16541 MethodArgs.reserve(NumParams + 1);
16542
16543 bool IsError = false;
16544
16545 // Initialize the object parameter.
16547 if (Method->isExplicitObjectMemberFunction()) {
16548 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16549 } else {
16551 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16552 if (ObjRes.isInvalid())
16553 IsError = true;
16554 else
16555 Object = ObjRes;
16556 MethodArgs.push_back(Object.get());
16557 }
16558
16560 *this, MethodArgs, Method, Args, LParenLoc);
16561
16562 // If this is a variadic call, handle args passed through "...".
16563 if (Proto->isVariadic()) {
16564 // Promote the arguments (C99 6.5.2.2p7).
16565 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16567 Args[i], VariadicCallType::Method, nullptr);
16568 IsError |= Arg.isInvalid();
16569 MethodArgs.push_back(Arg.get());
16570 }
16571 }
16572
16573 if (IsError)
16574 return true;
16575
16576 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16577
16578 // Once we've built TheCall, all of the expressions are properly owned.
16579 QualType ResultTy = Method->getReturnType();
16581 ResultTy = ResultTy.getNonLValueExprType(Context);
16582
16584 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16586
16587 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16588 return true;
16589
16590 if (CheckFunctionCall(Method, TheCall, Proto))
16591 return true;
16592
16594}
16595
16597 SourceLocation OpLoc,
16598 bool *NoArrowOperatorFound) {
16599 assert(Base->getType()->isRecordType() &&
16600 "left-hand side must have class type");
16601
16603 return ExprError();
16604
16605 SourceLocation Loc = Base->getExprLoc();
16606
16607 // C++ [over.ref]p1:
16608 //
16609 // [...] An expression x->m is interpreted as (x.operator->())->m
16610 // for a class object x of type T if T::operator->() exists and if
16611 // the operator is selected as the best match function by the
16612 // overload resolution mechanism (13.3).
16613 DeclarationName OpName =
16614 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16616
16617 if (RequireCompleteType(Loc, Base->getType(),
16618 diag::err_typecheck_incomplete_tag, Base))
16619 return ExprError();
16620
16621 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16622 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16624
16625 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16626 Oper != OperEnd; ++Oper) {
16627 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16628 {}, CandidateSet,
16629 /*SuppressUserConversion=*/false);
16630 }
16631
16632 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16633
16634 // Perform overload resolution.
16636 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16637 case OR_Success:
16638 // Overload resolution succeeded; we'll build the call below.
16639 break;
16640
16641 case OR_No_Viable_Function: {
16642 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16643 if (CandidateSet.empty()) {
16644 QualType BaseType = Base->getType();
16645 if (NoArrowOperatorFound) {
16646 // Report this specific error to the caller instead of emitting a
16647 // diagnostic, as requested.
16648 *NoArrowOperatorFound = true;
16649 return ExprError();
16650 }
16651 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16652 << BaseType << Base->getSourceRange();
16653 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16654 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16655 << FixItHint::CreateReplacement(OpLoc, ".");
16656 }
16657 } else
16658 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16659 << "operator->" << Base->getSourceRange();
16660 CandidateSet.NoteCandidates(*this, Base, Cands);
16661 return ExprError();
16662 }
16663 case OR_Ambiguous:
16664 if (!R.isAmbiguous())
16665 CandidateSet.NoteCandidates(
16666 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16667 << "->" << Base->getType()
16668 << Base->getSourceRange()),
16670 return ExprError();
16671
16672 case OR_Deleted: {
16673 StringLiteral *Msg = Best->Function->getDeletedMessage();
16674 CandidateSet.NoteCandidates(
16675 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16676 << "->" << (Msg != nullptr)
16677 << (Msg ? Msg->getString() : StringRef())
16678 << Base->getSourceRange()),
16679 *this, OCD_AllCandidates, Base);
16680 return ExprError();
16681 }
16682 }
16683
16684 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16685
16686 // Convert the object parameter.
16687 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16688
16689 if (Method->isExplicitObjectMemberFunction()) {
16691 if (R.isInvalid())
16692 return ExprError();
16693 Base = R.get();
16694 } else {
16696 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16697 if (BaseResult.isInvalid())
16698 return ExprError();
16699 Base = BaseResult.get();
16700 }
16701
16702 // Build the operator call.
16703 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16704 Base, HadMultipleCandidates, OpLoc);
16705 if (FnExpr.isInvalid())
16706 return ExprError();
16707
16708 QualType ResultTy = Method->getReturnType();
16710 ResultTy = ResultTy.getNonLValueExprType(Context);
16711
16712 CallExpr *TheCall =
16713 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16714 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16715
16716 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16717 return ExprError();
16718
16719 if (CheckFunctionCall(Method, TheCall,
16720 Method->getType()->castAs<FunctionProtoType>()))
16721 return ExprError();
16722
16724}
16725
16727 DeclarationNameInfo &SuffixInfo,
16728 ArrayRef<Expr*> Args,
16729 SourceLocation LitEndLoc,
16730 TemplateArgumentListInfo *TemplateArgs) {
16731 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16732
16733 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16735 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16736 TemplateArgs);
16737
16738 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16739
16740 // Perform overload resolution. This will usually be trivial, but might need
16741 // to perform substitutions for a literal operator template.
16743 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16744 case OR_Success:
16745 case OR_Deleted:
16746 break;
16747
16749 CandidateSet.NoteCandidates(
16750 PartialDiagnosticAt(UDSuffixLoc,
16751 PDiag(diag::err_ovl_no_viable_function_in_call)
16752 << R.getLookupName()),
16753 *this, OCD_AllCandidates, Args);
16754 return ExprError();
16755
16756 case OR_Ambiguous:
16757 CandidateSet.NoteCandidates(
16758 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16759 << R.getLookupName()),
16760 *this, OCD_AmbiguousCandidates, Args);
16761 return ExprError();
16762 }
16763
16764 FunctionDecl *FD = Best->Function;
16765 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16766 nullptr, HadMultipleCandidates,
16767 SuffixInfo.getLoc(),
16768 SuffixInfo.getInfo());
16769 if (Fn.isInvalid())
16770 return true;
16771
16772 // Check the argument types. This should almost always be a no-op, except
16773 // that array-to-pointer decay is applied to string literals.
16774 Expr *ConvArgs[2];
16775 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16778 SourceLocation(), Args[ArgIdx]);
16779 if (InputInit.isInvalid())
16780 return true;
16781 ConvArgs[ArgIdx] = InputInit.get();
16782 }
16783
16784 QualType ResultTy = FD->getReturnType();
16786 ResultTy = ResultTy.getNonLValueExprType(Context);
16787
16789 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16790 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16791
16792 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16793 return ExprError();
16794
16795 if (CheckFunctionCall(FD, UDL, nullptr))
16796 return ExprError();
16797
16799}
16800
16803 SourceLocation RangeLoc,
16804 const DeclarationNameInfo &NameInfo,
16805 LookupResult &MemberLookup,
16806 OverloadCandidateSet *CandidateSet,
16807 Expr *Range, ExprResult *CallExpr) {
16808 Scope *S = nullptr;
16809
16811 if (!MemberLookup.empty()) {
16812 ExprResult MemberRef =
16813 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16814 /*IsPtr=*/false, CXXScopeSpec(),
16815 /*TemplateKWLoc=*/SourceLocation(),
16816 /*FirstQualifierInScope=*/nullptr,
16817 MemberLookup,
16818 /*TemplateArgs=*/nullptr, S);
16819 if (MemberRef.isInvalid()) {
16820 *CallExpr = ExprError();
16821 return FRS_DiagnosticIssued;
16822 }
16823 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16824 if (CallExpr->isInvalid()) {
16825 *CallExpr = ExprError();
16826 return FRS_DiagnosticIssued;
16827 }
16828 } else {
16829 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16831 NameInfo, UnresolvedSet<0>());
16832 if (FnR.isInvalid())
16833 return FRS_DiagnosticIssued;
16835
16836 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16837 CandidateSet, CallExpr);
16838 if (CandidateSet->empty() || CandidateSetError) {
16839 *CallExpr = ExprError();
16840 return FRS_NoViableFunction;
16841 }
16843 OverloadingResult OverloadResult =
16844 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16845
16846 if (OverloadResult == OR_No_Viable_Function) {
16847 *CallExpr = ExprError();
16848 return FRS_NoViableFunction;
16849 }
16850 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16851 Loc, nullptr, CandidateSet, &Best,
16852 OverloadResult,
16853 /*AllowTypoCorrection=*/false);
16854 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16855 *CallExpr = ExprError();
16856 return FRS_DiagnosticIssued;
16857 }
16858 }
16859 return FRS_Success;
16860}
16861
16863 FunctionDecl *Fn) {
16864 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16865 ExprResult SubExpr =
16866 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16867 if (SubExpr.isInvalid())
16868 return ExprError();
16869 if (SubExpr.get() == PE->getSubExpr())
16870 return PE;
16871
16872 return new (Context)
16873 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16874 }
16875
16876 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16877 ExprResult SubExpr =
16878 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16879 if (SubExpr.isInvalid())
16880 return ExprError();
16881 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16882 SubExpr.get()->getType()) &&
16883 "Implicit cast type cannot be determined from overload");
16884 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16885 if (SubExpr.get() == ICE->getSubExpr())
16886 return ICE;
16887
16888 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16889 SubExpr.get(), nullptr, ICE->getValueKind(),
16891 }
16892
16893 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16894 if (!GSE->isResultDependent()) {
16895 ExprResult SubExpr =
16896 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16897 if (SubExpr.isInvalid())
16898 return ExprError();
16899 if (SubExpr.get() == GSE->getResultExpr())
16900 return GSE;
16901
16902 // Replace the resulting type information before rebuilding the generic
16903 // selection expression.
16904 ArrayRef<Expr *> A = GSE->getAssocExprs();
16905 SmallVector<Expr *, 4> AssocExprs(A);
16906 unsigned ResultIdx = GSE->getResultIndex();
16907 AssocExprs[ResultIdx] = SubExpr.get();
16908
16909 if (GSE->isExprPredicate())
16911 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16912 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16913 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16914 ResultIdx);
16916 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16917 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16918 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16919 ResultIdx);
16920 }
16921 // Rather than fall through to the unreachable, return the original generic
16922 // selection expression.
16923 return GSE;
16924 }
16925
16926 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16927 assert(UnOp->getOpcode() == UO_AddrOf &&
16928 "Can only take the address of an overloaded function");
16929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16930 if (!Method->isImplicitObjectMemberFunction()) {
16931 // Do nothing: the address of static and
16932 // explicit object member functions is a (non-member) function pointer.
16933 } else {
16934 // Fix the subexpression, which really has to be an
16935 // UnresolvedLookupExpr holding an overloaded member function
16936 // or template.
16937 ExprResult SubExpr =
16938 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16939 if (SubExpr.isInvalid())
16940 return ExprError();
16941 if (SubExpr.get() == UnOp->getSubExpr())
16942 return UnOp;
16943
16944 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16945 SubExpr.get(), Method))
16946 return ExprError();
16947
16948 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16949 "fixed to something other than a decl ref");
16950 NestedNameSpecifier Qualifier =
16951 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
16952 assert(Qualifier &&
16953 "fixed to a member ref with no nested name qualifier");
16954
16955 // We have taken the address of a pointer to member
16956 // function. Perform the computation here so that we get the
16957 // appropriate pointer to member type.
16958 QualType MemPtrType = Context.getMemberPointerType(
16959 Fn->getType(), Qualifier,
16960 cast<CXXRecordDecl>(Method->getDeclContext()));
16961 // Under the MS ABI, lock down the inheritance model now.
16962 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16963 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16964
16965 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16966 MemPtrType, VK_PRValue, OK_Ordinary,
16967 UnOp->getOperatorLoc(), false,
16969 }
16970 }
16971 ExprResult SubExpr =
16972 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16973 if (SubExpr.isInvalid())
16974 return ExprError();
16975 if (SubExpr.get() == UnOp->getSubExpr())
16976 return UnOp;
16977
16978 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16979 SubExpr.get());
16980 }
16981
16982 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16983 if (Found.getAccess() == AS_none) {
16985 }
16986 // FIXME: avoid copy.
16987 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16988 if (ULE->hasExplicitTemplateArgs()) {
16989 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16990 TemplateArgs = &TemplateArgsBuffer;
16991 }
16992
16993 QualType Type = Fn->getType();
16994 ExprValueKind ValueKind =
16995 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16996 ? VK_LValue
16997 : VK_PRValue;
16998
16999 // FIXME: Duplicated from BuildDeclarationNameExpr.
17000 if (unsigned BID = Fn->getBuiltinID()) {
17001 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17002 Type = Context.BuiltinFnTy;
17003 ValueKind = VK_PRValue;
17004 }
17005 }
17006
17008 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17009 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17010 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17011 return DRE;
17012 }
17013
17014 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17015 // FIXME: avoid copy.
17016 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17017 if (MemExpr->hasExplicitTemplateArgs()) {
17018 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17019 TemplateArgs = &TemplateArgsBuffer;
17020 }
17021
17022 Expr *Base;
17023
17024 // If we're filling in a static method where we used to have an
17025 // implicit member access, rewrite to a simple decl ref.
17026 if (MemExpr->isImplicitAccess()) {
17027 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17029 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17030 MemExpr->getQualifierLoc(), Found.getDecl(),
17031 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17032 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17033 return DRE;
17034 } else {
17035 SourceLocation Loc = MemExpr->getMemberLoc();
17036 if (MemExpr->getQualifier())
17037 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17038 Base =
17039 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17040 }
17041 } else
17042 Base = MemExpr->getBase();
17043
17044 ExprValueKind valueKind;
17045 QualType type;
17046 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17047 valueKind = VK_LValue;
17048 type = Fn->getType();
17049 } else {
17050 valueKind = VK_PRValue;
17051 type = Context.BoundMemberTy;
17052 }
17053
17054 return BuildMemberExpr(
17055 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17056 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17057 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17058 type, valueKind, OK_Ordinary, TemplateArgs);
17059 }
17060
17061 llvm_unreachable("Invalid reference to overloaded function");
17062}
17063
17069
17070bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17072 if (!PartialOverloading || !Function)
17073 return true;
17074 if (Function->isVariadic())
17075 return false;
17076 if (const auto *Proto =
17077 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17078 if (Proto->isTemplateVariadic())
17079 return false;
17080 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17081 if (const auto *Proto =
17082 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17083 if (Proto->isTemplateVariadic())
17084 return false;
17085 return true;
17086}
17087
17089 DeclarationName Name,
17090 OverloadCandidateSet &CandidateSet,
17091 FunctionDecl *Fn, MultiExprArg Args,
17092 bool IsMember) {
17093 StringLiteral *Msg = Fn->getDeletedMessage();
17094 CandidateSet.NoteCandidates(
17095 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17096 << IsMember << Name << (Msg != nullptr)
17097 << (Msg ? Msg->getString() : StringRef())
17098 << Range),
17099 *this, OCD_AllCandidates, Args);
17100}
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:188
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:741
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:891
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:857
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:856
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:3890
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:3720
QualType getElementType() const
Definition TypeBase.h:3732
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8084
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:3540
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:3758
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:37
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:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:854
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:776
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:761
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:752
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:591
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:4265
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3157
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
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:139
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:102
Represents a function declaration or definition.
Definition Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4134
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
param_iterator param_end()
Definition Decl.h:2784
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3607
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
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:4205
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
param_iterator param_begin()
Definition Decl.h:2783
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:4270
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4198
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3810
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2469
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4071
bool isConsteval() const
Definition Decl.h:2481
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3651
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:2859
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:3656
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2682
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5768
unsigned getNumParams() const
Definition TypeBase.h:5542
Qualifiers getMethodQuals() const
Definition TypeBase.h:5690
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5704
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:4571
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4642
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4499
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
ExtInfo getExtInfo() const
Definition TypeBase.h:4816
CallingConv getCallConv() const
Definition TypeBase.h:4815
QualType getReturnType() const
Definition TypeBase.h:4800
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4828
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:3615
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:3651
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3683
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:3669
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:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
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:591
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:7847
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7903
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:7992
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7961
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7915
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7955
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:7967
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:3122
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3274
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3183
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3238
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3235
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3213
decls_iterator decls_begin() const
Definition ExprCXX.h:3215
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3226
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3248
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3244
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3336
decls_iterator decls_end() const
Definition ExprCXX.h:3218
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3232
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:1789
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:8369
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8363
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
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:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
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:8470
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
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:8439
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8406
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8331
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:8450
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8317
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8225
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8232
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:3633
Represents a struct/union/class.
Definition Decl.h:4309
field_range fields() const
Definition Decl.h:4512
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
QualType getPointeeType() const
Definition TypeBase.h:3589
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:12367
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12400
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.
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:12081
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.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
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:15331
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)
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:13799
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:15286
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...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
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:3535
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:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
bool isObjCBuiltinType() const
Definition TypeBase.h:8742
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:8629
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:8887
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:8554
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:8625
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9038
bool isArrayType() const
Definition TypeBase.h:8621
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:8946
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2337
bool isPointerType() const
Definition TypeBase.h:8522
bool isArrayParameterType() const
Definition TypeBase.h:8637
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
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:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8712
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:8996
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:8669
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8699
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:8550
bool isBitIntType() const
Definition TypeBase.h:8787
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:8657
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8934
bool isHalfType() const
Definition TypeBase.h:8882
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8860
bool isQueueT() const
Definition TypeBase.h:8768
bool isMemberPointerType() const
Definition TypeBase.h:8603
bool isObjCIdType() const
Definition TypeBase.h:8724
bool isMatrixType() const
Definition TypeBase.h:8679
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9014
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:8760
bool isBFloat16Type() const
Definition TypeBase.h:8899
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:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
bool isVectorType() const
Definition TypeBase.h:8661
bool isObjCClassType() const
Definition TypeBase.h:8730
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:8835
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:8530
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSamplerT() const
Definition TypeBase.h:8756
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
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:3384
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3453
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:4120
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4228
QualType getBaseType() const
Definition ExprCXX.h:4202
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4212
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4193
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4238
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4232
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:722
unsigned getNumElements() const
Definition TypeBase.h:4188
QualType getElementType() const
Definition TypeBase.h:4187
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:213
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:424
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:117
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:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:300
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:366
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:416
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:411
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:414
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:387
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:373
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:409
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:418
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:406
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:376
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:370
@ Success
Template argument deduction was successful.
Definition Sema.h:368
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:390
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:379
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:393
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:382
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:403
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:420
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:397
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:400
@ 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:5877
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:445
__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:87
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:88
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:5349
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5354
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:12961
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13049
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13087
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.