clang 22.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.h"
36#include "clang/Sema/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
167 };
168 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
169 return Rank[(int)Kind];
170}
171
190
191/// GetImplicitConversionName - Return the name of this kind of
192/// implicit conversion.
194 static const char *const Name[] = {
195 "No conversion",
196 "Lvalue-to-rvalue",
197 "Array-to-pointer",
198 "Function-to-pointer",
199 "Function pointer conversion",
200 "Qualification",
201 "Integral promotion",
202 "Floating point promotion",
203 "Complex promotion",
204 "Integral conversion",
205 "Floating conversion",
206 "Complex conversion",
207 "Floating-integral conversion",
208 "Pointer conversion",
209 "Pointer-to-member conversion",
210 "Boolean conversion",
211 "Compatible-types conversion",
212 "Derived-to-base conversion",
213 "Vector conversion",
214 "SVE Vector conversion",
215 "RVV Vector conversion",
216 "Vector splat",
217 "Complex-real conversion",
218 "Block Pointer conversion",
219 "Transparent Union Conversion",
220 "Writeback conversion",
221 "OpenCL Zero Event Conversion",
222 "OpenCL Zero Queue Conversion",
223 "C specific type conversion",
224 "Incompatible pointer conversion",
225 "Fixed point conversion",
226 "HLSL vector truncation",
227 "Non-decaying array conversion",
228 "HLSL vector splat",
229 };
230 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
231 return Name[Kind];
232}
233
234/// StandardConversionSequence - Set the standard conversion
235/// sequence to the identity conversion.
253
254/// getRank - Retrieve the rank of this standard conversion sequence
255/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
256/// implicit conversions.
269
270/// isPointerConversionToBool - Determines whether this conversion is
271/// a conversion of a pointer or pointer-to-member to bool. This is
272/// used as part of the ranking of standard conversion sequences
273/// (C++ 13.3.3.2p4).
275 // Note that FromType has not necessarily been transformed by the
276 // array-to-pointer or function-to-pointer implicit conversions, so
277 // check for their presence as well as checking whether FromType is
278 // a pointer.
279 if (getToType(1)->isBooleanType() &&
280 (getFromType()->isPointerType() ||
281 getFromType()->isMemberPointerType() ||
282 getFromType()->isObjCObjectPointerType() ||
283 getFromType()->isBlockPointerType() ||
285 return true;
286
287 return false;
288}
289
290/// isPointerConversionToVoidPointer - Determines whether this
291/// conversion is a conversion of a pointer to a void pointer. This is
292/// used as part of the ranking of standard conversion sequences (C++
293/// 13.3.3.2p4).
294bool
297 QualType FromType = getFromType();
298 QualType ToType = getToType(1);
299
300 // Note that FromType has not necessarily been transformed by the
301 // array-to-pointer implicit conversion, so check for its presence
302 // and redo the conversion to get a pointer.
304 FromType = Context.getArrayDecayedType(FromType);
305
306 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
307 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
308 return ToPtrType->getPointeeType()->isVoidType();
309
310 return false;
311}
312
313/// Skip any implicit casts which could be either part of a narrowing conversion
314/// or after one in an implicit conversion.
316 const Expr *Converted) {
317 // We can have cleanups wrapping the converted expression; these need to be
318 // preserved so that destructors run if necessary.
319 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
320 Expr *Inner =
321 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
322 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
323 EWC->getObjects());
324 }
325
326 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
327 switch (ICE->getCastKind()) {
328 case CK_NoOp:
329 case CK_IntegralCast:
330 case CK_IntegralToBoolean:
331 case CK_IntegralToFloating:
332 case CK_BooleanToSignedIntegral:
333 case CK_FloatingToIntegral:
334 case CK_FloatingToBoolean:
335 case CK_FloatingCast:
336 Converted = ICE->getSubExpr();
337 continue;
338
339 default:
340 return Converted;
341 }
342 }
343
344 return Converted;
345}
346
347/// Check if this standard conversion sequence represents a narrowing
348/// conversion, according to C++11 [dcl.init.list]p7.
349///
350/// \param Ctx The AST context.
351/// \param Converted The result of applying this standard conversion sequence.
352/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
353/// value of the expression prior to the narrowing conversion.
354/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
355/// type of the expression prior to the narrowing conversion.
356/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
357/// from floating point types to integral types should be ignored.
359 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
360 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
361 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
362 "narrowing check outside C++");
363
364 // C++11 [dcl.init.list]p7:
365 // A narrowing conversion is an implicit conversion ...
366 QualType FromType = getToType(0);
367 QualType ToType = getToType(1);
368
369 // A conversion to an enumeration type is narrowing if the conversion to
370 // the underlying type is narrowing. This only arises for expressions of
371 // the form 'Enum{init}'.
372 if (const auto *ED = ToType->getAsEnumDecl())
373 ToType = ED->getIntegerType();
374
375 switch (Second) {
376 // 'bool' is an integral type; dispatch to the right place to handle it.
378 if (FromType->isRealFloatingType())
379 goto FloatingIntegralConversion;
381 goto IntegralConversion;
382 // -- from a pointer type or pointer-to-member type to bool, or
383 return NK_Type_Narrowing;
384
385 // -- from a floating-point type to an integer type, or
386 //
387 // -- from an integer type or unscoped enumeration type to a floating-point
388 // type, except where the source is a constant expression and the actual
389 // value after conversion will fit into the target type and will produce
390 // the original value when converted back to the original type, or
392 FloatingIntegralConversion:
393 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
394 return NK_Type_Narrowing;
395 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
396 ToType->isRealFloatingType()) {
397 if (IgnoreFloatToIntegralConversion)
398 return NK_Not_Narrowing;
399 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
400 assert(Initializer && "Unknown conversion expression");
401
402 // If it's value-dependent, we can't tell whether it's narrowing.
403 if (Initializer->isValueDependent())
405
406 if (std::optional<llvm::APSInt> IntConstantValue =
407 Initializer->getIntegerConstantExpr(Ctx)) {
408 // Convert the integer to the floating type.
409 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
410 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
411 llvm::APFloat::rmNearestTiesToEven);
412 // And back.
413 llvm::APSInt ConvertedValue = *IntConstantValue;
414 bool ignored;
415 llvm::APFloat::opStatus Status = Result.convertToInteger(
416 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
417 // If the converted-back integer has unspecified value, or if the
418 // resulting value is different, this was a narrowing conversion.
419 if (Status == llvm::APFloat::opInvalidOp ||
420 *IntConstantValue != ConvertedValue) {
421 ConstantValue = APValue(*IntConstantValue);
422 ConstantType = Initializer->getType();
424 }
425 } else {
426 // Variables are always narrowings.
428 }
429 }
430 return NK_Not_Narrowing;
431
432 // -- from long double to double or float, or from double to float, except
433 // where the source is a constant expression and the actual value after
434 // conversion is within the range of values that can be represented (even
435 // if it cannot be represented exactly), or
437 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
438 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
439 // FromType is larger than ToType.
440 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
441
442 // If it's value-dependent, we can't tell whether it's narrowing.
443 if (Initializer->isValueDependent())
445
447 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
448 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
449 // Constant!
450 if (Ctx.getLangOpts().C23)
451 ConstantValue = R.Val;
452 assert(ConstantValue.isFloat());
453 llvm::APFloat FloatVal = ConstantValue.getFloat();
454 // Convert the source value into the target type.
455 bool ignored;
456 llvm::APFloat Converted = FloatVal;
457 llvm::APFloat::opStatus ConvertStatus =
458 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
459 llvm::APFloat::rmNearestTiesToEven, &ignored);
460 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
461 llvm::APFloat::rmNearestTiesToEven, &ignored);
462 if (Ctx.getLangOpts().C23) {
463 if (FloatVal.isNaN() && Converted.isNaN() &&
464 !FloatVal.isSignaling() && !Converted.isSignaling()) {
465 // Quiet NaNs are considered the same value, regardless of
466 // payloads.
467 return NK_Not_Narrowing;
468 }
469 // For normal values, check exact equality.
470 if (!Converted.bitwiseIsEqual(FloatVal)) {
471 ConstantType = Initializer->getType();
473 }
474 } else {
475 // If there was no overflow, the source value is within the range of
476 // values that can be represented.
477 if (ConvertStatus & llvm::APFloat::opOverflow) {
478 ConstantType = Initializer->getType();
480 }
481 }
482 } else {
484 }
485 }
486 return NK_Not_Narrowing;
487
488 // -- from an integer type or unscoped enumeration type to an integer type
489 // that cannot represent all the values of the original type, except where
490 // (CWG2627) -- the source is a bit-field whose width w is less than that
491 // of its type (or, for an enumeration type, its underlying type) and the
492 // target type can represent all the values of a hypothetical extended
493 // integer type with width w and with the same signedness as the original
494 // type or
495 // -- the source is a constant expression and the actual value after
496 // conversion will fit into the target type and will produce the original
497 // value when converted back to the original type.
499 IntegralConversion: {
500 assert(FromType->isIntegralOrUnscopedEnumerationType());
501 assert(ToType->isIntegralOrUnscopedEnumerationType());
502 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
503 unsigned FromWidth = Ctx.getIntWidth(FromType);
504 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
505 const unsigned ToWidth = Ctx.getIntWidth(ToType);
506
507 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
508 bool ToSigned, unsigned ToWidth) {
509 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
510 !(FromSigned && !ToSigned);
511 };
512
513 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
514 return NK_Not_Narrowing;
515
516 // Not all values of FromType can be represented in ToType.
517 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
518
519 bool DependentBitField = false;
520 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
521 if (BitField->getBitWidth()->isValueDependent())
522 DependentBitField = true;
523 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
524 BitFieldWidth < FromWidth) {
525 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // The initializer will be truncated to the bit-field width
529 FromWidth = BitFieldWidth;
530 }
531 }
532
533 // If it's value-dependent, we can't tell whether it's narrowing.
534 if (Initializer->isValueDependent())
536
537 std::optional<llvm::APSInt> OptInitializerValue =
538 Initializer->getIntegerConstantExpr(Ctx);
539 if (!OptInitializerValue) {
540 // If the bit-field width was dependent, it might end up being small
541 // enough to fit in the target type (unless the target type is unsigned
542 // and the source type is signed, in which case it will never fit)
543 if (DependentBitField && !(FromSigned && !ToSigned))
545
546 // Otherwise, such a conversion is always narrowing
548 }
549 llvm::APSInt &InitializerValue = *OptInitializerValue;
550 bool Narrowing = false;
551 if (FromWidth < ToWidth) {
552 // Negative -> unsigned is narrowing. Otherwise, more bits is never
553 // narrowing.
554 if (InitializerValue.isSigned() && InitializerValue.isNegative())
555 Narrowing = true;
556 } else {
557 // Add a bit to the InitializerValue so we don't have to worry about
558 // signed vs. unsigned comparisons.
559 InitializerValue =
560 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
561 // Convert the initializer to and from the target width and signed-ness.
562 llvm::APSInt ConvertedValue = InitializerValue;
563 ConvertedValue = ConvertedValue.trunc(ToWidth);
564 ConvertedValue.setIsSigned(ToSigned);
565 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
566 ConvertedValue.setIsSigned(InitializerValue.isSigned());
567 // If the result is different, this was a narrowing conversion.
568 if (ConvertedValue != InitializerValue)
569 Narrowing = true;
570 }
571 if (Narrowing) {
572 ConstantType = Initializer->getType();
573 ConstantValue = APValue(InitializerValue);
575 }
576
577 return NK_Not_Narrowing;
578 }
579 case ICK_Complex_Real:
580 if (FromType->isComplexType() && !ToType->isComplexType())
581 return NK_Type_Narrowing;
582 return NK_Not_Narrowing;
583
585 if (Ctx.getLangOpts().C23) {
586 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
588 if (Initializer->EvaluateAsRValue(R, Ctx)) {
589 ConstantValue = R.Val;
590 assert(ConstantValue.isFloat());
591 llvm::APFloat FloatVal = ConstantValue.getFloat();
592 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
593 // value, the unqualified versions of the type of the initializer and
594 // the corresponding real type of the object declared shall be
595 // compatible.
596 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
597 ConstantType = Initializer->getType();
599 }
600 }
601 }
602 return NK_Not_Narrowing;
603 default:
604 // Other kinds of conversions are not narrowings.
605 return NK_Not_Narrowing;
606 }
607}
608
609/// dump - Print this standard conversion sequence to standard
610/// error. Useful for debugging overloading issues.
611LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
612 raw_ostream &OS = llvm::errs();
613 bool PrintedSomething = false;
614 if (First != ICK_Identity) {
616 PrintedSomething = true;
617 }
618
619 if (Second != ICK_Identity) {
620 if (PrintedSomething) {
621 OS << " -> ";
622 }
624
625 if (CopyConstructor) {
626 OS << " (by copy constructor)";
627 } else if (DirectBinding) {
628 OS << " (direct reference binding)";
629 } else if (ReferenceBinding) {
630 OS << " (reference binding)";
631 }
632 PrintedSomething = true;
633 }
634
635 if (Third != ICK_Identity) {
636 if (PrintedSomething) {
637 OS << " -> ";
638 }
640 PrintedSomething = true;
641 }
642
643 if (!PrintedSomething) {
644 OS << "No conversions required";
645 }
646}
647
648/// dump - Print this user-defined conversion sequence to standard
649/// error. Useful for debugging overloading issues.
651 raw_ostream &OS = llvm::errs();
652 if (Before.First || Before.Second || Before.Third) {
653 Before.dump();
654 OS << " -> ";
655 }
657 OS << '\'' << *ConversionFunction << '\'';
658 else
659 OS << "aggregate initialization";
660 if (After.First || After.Second || After.Third) {
661 OS << " -> ";
662 After.dump();
663 }
664}
665
666/// dump - Print this implicit conversion sequence to standard
667/// error. Useful for debugging overloading issues.
669 raw_ostream &OS = llvm::errs();
671 OS << "Worst list element conversion: ";
672 switch (ConversionKind) {
674 OS << "Standard conversion: ";
675 Standard.dump();
676 break;
678 OS << "User-defined conversion: ";
679 UserDefined.dump();
680 break;
682 OS << "Ellipsis conversion";
683 break;
685 OS << "Ambiguous conversion";
686 break;
687 case BadConversion:
688 OS << "Bad conversion";
689 break;
690 }
691
692 OS << "\n";
693}
694
698
700 conversions().~ConversionSet();
701}
702
703void
709
710namespace {
711 // Structure used by DeductionFailureInfo to store
712 // template argument information.
713 struct DFIArguments {
714 TemplateArgument FirstArg;
715 TemplateArgument SecondArg;
716 };
717 // Structure used by DeductionFailureInfo to store
718 // template parameter and template argument information.
719 struct DFIParamWithArguments : DFIArguments {
720 TemplateParameter Param;
721 };
722 // Structure used by DeductionFailureInfo to store template argument
723 // information and the index of the problematic call argument.
724 struct DFIDeducedMismatchArgs : DFIArguments {
725 TemplateArgumentList *TemplateArgs;
726 unsigned CallArgIndex;
727 };
728 // Structure used by DeductionFailureInfo to store information about
729 // unsatisfied constraints.
730 struct CNSInfo {
731 TemplateArgumentList *TemplateArgs;
732 ConstraintSatisfaction Satisfaction;
733 };
734}
735
736/// Convert from Sema's representation of template deduction information
737/// to the form used in overload-candidate information.
741 TemplateDeductionInfo &Info) {
743 Result.Result = static_cast<unsigned>(TDK);
744 Result.HasDiagnostic = false;
745 switch (TDK) {
752 Result.Data = nullptr;
753 break;
754
757 Result.Data = Info.Param.getOpaqueValue();
758 break;
759
762 // FIXME: Should allocate from normal heap so that we can free this later.
763 auto *Saved = new (Context) DFIDeducedMismatchArgs;
764 Saved->FirstArg = Info.FirstArg;
765 Saved->SecondArg = Info.SecondArg;
766 Saved->TemplateArgs = Info.takeSugared();
767 Saved->CallArgIndex = Info.CallArgIndex;
768 Result.Data = Saved;
769 break;
770 }
771
773 // FIXME: Should allocate from normal heap so that we can free this later.
774 DFIArguments *Saved = new (Context) DFIArguments;
775 Saved->FirstArg = Info.FirstArg;
776 Saved->SecondArg = Info.SecondArg;
777 Result.Data = Saved;
778 break;
779 }
780
782 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
785 // FIXME: Should allocate from normal heap so that we can free this later.
786 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
787 Saved->Param = Info.Param;
788 Saved->FirstArg = Info.FirstArg;
789 Saved->SecondArg = Info.SecondArg;
790 Result.Data = Saved;
791 break;
792 }
793
795 Result.Data = Info.takeSugared();
796 if (Info.hasSFINAEDiagnostic()) {
800 Result.HasDiagnostic = true;
801 }
802 break;
803
805 CNSInfo *Saved = new (Context) CNSInfo;
806 Saved->TemplateArgs = Info.takeSugared();
807 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
808 Result.Data = Saved;
809 break;
810 }
811
815 llvm_unreachable("not a deduction failure");
816 }
817
818 return Result;
819}
820
822 switch (static_cast<TemplateDeductionResult>(Result)) {
832 break;
833
840 // FIXME: Destroy the data?
841 Data = nullptr;
842 break;
843
845 // FIXME: Destroy the template argument list?
846 Data = nullptr;
848 Diag->~PartialDiagnosticAt();
849 HasDiagnostic = false;
850 }
851 break;
852
854 // FIXME: Destroy the template argument list?
855 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
856 Data = nullptr;
858 Diag->~PartialDiagnosticAt();
859 HasDiagnostic = false;
860 }
861 break;
862
863 // Unhandled
866 break;
867 }
868}
869
871 if (HasDiagnostic)
872 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
873 return nullptr;
874}
875
909
945
977
1009
1011 switch (static_cast<TemplateDeductionResult>(Result)) {
1014 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1015
1016 default:
1017 return std::nullopt;
1018 }
1019}
1020
1022 const FunctionDecl *Y) {
1023 if (!X || !Y)
1024 return false;
1025 if (X->getNumParams() != Y->getNumParams())
1026 return false;
1027 // FIXME: when do rewritten comparison operators
1028 // with explicit object parameters correspond?
1029 // https://cplusplus.github.io/CWG/issues/2797.html
1030 for (unsigned I = 0; I < X->getNumParams(); ++I)
1031 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1032 Y->getParamDecl(I)->getType()))
1033 return false;
1034 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1035 auto *FTY = Y->getDescribedFunctionTemplate();
1036 if (!FTY)
1037 return false;
1038 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1039 FTY->getTemplateParameters()))
1040 return false;
1041 }
1042 return true;
1043}
1044
1046 Expr *FirstOperand, FunctionDecl *EqFD) {
1047 assert(EqFD->getOverloadedOperator() ==
1048 OverloadedOperatorKind::OO_EqualEqual);
1049 // C++2a [over.match.oper]p4:
1050 // A non-template function or function template F named operator== is a
1051 // rewrite target with first operand o unless a search for the name operator!=
1052 // in the scope S from the instantiation context of the operator expression
1053 // finds a function or function template that would correspond
1054 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1055 // scope of the class type of o if F is a class member, and the namespace
1056 // scope of which F is a member otherwise. A function template specialization
1057 // named operator== is a rewrite target if its function template is a rewrite
1058 // target.
1060 OverloadedOperatorKind::OO_ExclaimEqual);
1061 if (isa<CXXMethodDecl>(EqFD)) {
1062 // If F is a class member, search scope is class type of first operand.
1063 QualType RHS = FirstOperand->getType();
1064 auto *RHSRec = RHS->getAsCXXRecordDecl();
1065 if (!RHSRec)
1066 return true;
1067 LookupResult Members(S, NotEqOp, OpLoc,
1069 S.LookupQualifiedName(Members, RHSRec);
1070 Members.suppressAccessDiagnostics();
1071 for (NamedDecl *Op : Members)
1072 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1073 return false;
1074 return true;
1075 }
1076 // Otherwise the search scope is the namespace scope of which F is a member.
1077 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1078 auto *NotEqFD = Op->getAsFunction();
1079 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1080 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1081 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1083 cast<Decl>(Op->getLexicalDeclContext())))
1084 return false;
1085 }
1086 return true;
1087}
1088
1090 OverloadedOperatorKind Op) const {
1092 return false;
1093 return Op == OO_EqualEqual || Op == OO_Spaceship;
1094}
1095
1097 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1098 auto Op = FD->getOverloadedOperator();
1099 if (!allowsReversed(Op))
1100 return false;
1101 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1102 assert(OriginalArgs.size() == 2);
1104 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1105 return false;
1106 }
1107 // Don't bother adding a reversed candidate that can never be a better
1108 // match than the non-reversed version.
1109 return FD->getNumNonObjectParams() != 2 ||
1111 FD->getParamDecl(1)->getType()) ||
1112 FD->hasAttr<EnableIfAttr>();
1113}
1114
1115void OverloadCandidateSet::destroyCandidates() {
1116 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1117 for (auto &C : i->Conversions)
1118 C.~ImplicitConversionSequence();
1119 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1120 i->DeductionFailure.Destroy();
1121 }
1122}
1123
1125 destroyCandidates();
1126 SlabAllocator.Reset();
1127 NumInlineBytesUsed = 0;
1128 Candidates.clear();
1129 Functions.clear();
1130 Kind = CSK;
1131 FirstDeferredCandidate = nullptr;
1132 DeferredCandidatesCount = 0;
1133 HasDeferredTemplateConstructors = false;
1134 ResolutionByPerfectCandidateIsDisabled = false;
1135}
1136
1137namespace {
1138 class UnbridgedCastsSet {
1139 struct Entry {
1140 Expr **Addr;
1141 Expr *Saved;
1142 };
1143 SmallVector<Entry, 2> Entries;
1144
1145 public:
1146 void save(Sema &S, Expr *&E) {
1147 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1148 Entry entry = { &E, E };
1149 Entries.push_back(entry);
1150 E = S.ObjC().stripARCUnbridgedCast(E);
1151 }
1152
1153 void restore() {
1154 for (SmallVectorImpl<Entry>::iterator
1155 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1156 *i->Addr = i->Saved;
1157 }
1158 };
1159}
1160
1161/// checkPlaceholderForOverload - Do any interesting placeholder-like
1162/// preprocessing on the given expression.
1163///
1164/// \param unbridgedCasts a collection to which to add unbridged casts;
1165/// without this, they will be immediately diagnosed as errors
1166///
1167/// Return true on unrecoverable error.
1168static bool
1170 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1171 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1172 // We can't handle overloaded expressions here because overload
1173 // resolution might reasonably tweak them.
1174 if (placeholder->getKind() == BuiltinType::Overload) return false;
1175
1176 // If the context potentially accepts unbridged ARC casts, strip
1177 // the unbridged cast and add it to the collection for later restoration.
1178 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1179 unbridgedCasts) {
1180 unbridgedCasts->save(S, E);
1181 return false;
1182 }
1183
1184 // Go ahead and check everything else.
1185 ExprResult result = S.CheckPlaceholderExpr(E);
1186 if (result.isInvalid())
1187 return true;
1188
1189 E = result.get();
1190 return false;
1191 }
1192
1193 // Nothing to do.
1194 return false;
1195}
1196
1197/// checkArgPlaceholdersForOverload - Check a set of call operands for
1198/// placeholders.
1200 UnbridgedCastsSet &unbridged) {
1201 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1202 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1203 return true;
1204
1205 return false;
1206}
1207
1209 const LookupResult &Old, NamedDecl *&Match,
1210 bool NewIsUsingDecl) {
1211 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1212 I != E; ++I) {
1213 NamedDecl *OldD = *I;
1214
1215 bool OldIsUsingDecl = false;
1216 if (isa<UsingShadowDecl>(OldD)) {
1217 OldIsUsingDecl = true;
1218
1219 // We can always introduce two using declarations into the same
1220 // context, even if they have identical signatures.
1221 if (NewIsUsingDecl) continue;
1222
1223 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1224 }
1225
1226 // A using-declaration does not conflict with another declaration
1227 // if one of them is hidden.
1228 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1229 continue;
1230
1231 // If either declaration was introduced by a using declaration,
1232 // we'll need to use slightly different rules for matching.
1233 // Essentially, these rules are the normal rules, except that
1234 // function templates hide function templates with different
1235 // return types or template parameter lists.
1236 bool UseMemberUsingDeclRules =
1237 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1238 !New->getFriendObjectKind();
1239
1240 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1241 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1242 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1244 continue;
1245 }
1246
1247 if (!isa<FunctionTemplateDecl>(OldD) &&
1248 !shouldLinkPossiblyHiddenDecl(*I, New))
1249 continue;
1250
1251 Match = *I;
1252 return OverloadKind::Match;
1253 }
1254
1255 // Builtins that have custom typechecking or have a reference should
1256 // not be overloadable or redeclarable.
1257 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1258 Match = *I;
1260 }
1261 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1262 // We can overload with these, which can show up when doing
1263 // redeclaration checks for UsingDecls.
1264 assert(Old.getLookupKind() == LookupUsingDeclName);
1265 } else if (isa<TagDecl>(OldD)) {
1266 // We can always overload with tags by hiding them.
1267 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1268 // Optimistically assume that an unresolved using decl will
1269 // overload; if it doesn't, we'll have to diagnose during
1270 // template instantiation.
1271 //
1272 // Exception: if the scope is dependent and this is not a class
1273 // member, the using declaration can only introduce an enumerator.
1274 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1275 Match = *I;
1277 }
1278 } else {
1279 // (C++ 13p1):
1280 // Only function declarations can be overloaded; object and type
1281 // declarations cannot be overloaded.
1282 Match = *I;
1284 }
1285 }
1286
1287 // C++ [temp.friend]p1:
1288 // For a friend function declaration that is not a template declaration:
1289 // -- if the name of the friend is a qualified or unqualified template-id,
1290 // [...], otherwise
1291 // -- if the name of the friend is a qualified-id and a matching
1292 // non-template function is found in the specified class or namespace,
1293 // the friend declaration refers to that function, otherwise,
1294 // -- if the name of the friend is a qualified-id and a matching function
1295 // template is found in the specified class or namespace, the friend
1296 // declaration refers to the deduced specialization of that function
1297 // template, otherwise
1298 // -- the name shall be an unqualified-id [...]
1299 // If we get here for a qualified friend declaration, we've just reached the
1300 // third bullet. If the type of the friend is dependent, skip this lookup
1301 // until instantiation.
1302 if (New->getFriendObjectKind() && New->getQualifier() &&
1303 !New->getDescribedFunctionTemplate() &&
1304 !New->getDependentSpecializationInfo() &&
1305 !New->getType()->isDependentType()) {
1306 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1307 TemplateSpecResult.addAllDecls(Old);
1308 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1309 /*QualifiedFriend*/true)) {
1310 New->setInvalidDecl();
1312 }
1313
1314 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1315 return OverloadKind::Match;
1316 }
1317
1319}
1320
1321template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1322 assert(D && "function decl should not be null");
1323 if (auto *A = D->getAttr<AttrT>())
1324 return !A->isImplicit();
1325 return false;
1326}
1327
1329 FunctionDecl *Old,
1330 bool UseMemberUsingDeclRules,
1331 bool ConsiderCudaAttrs,
1332 bool UseOverrideRules = false) {
1333 // C++ [basic.start.main]p2: This function shall not be overloaded.
1334 if (New->isMain())
1335 return false;
1336
1337 // MSVCRT user defined entry points cannot be overloaded.
1338 if (New->isMSVCRTEntryPoint())
1339 return false;
1340
1341 NamedDecl *OldDecl = Old;
1342 NamedDecl *NewDecl = New;
1344 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1345
1346 // C++ [temp.fct]p2:
1347 // A function template can be overloaded with other function templates
1348 // and with normal (non-template) functions.
1349 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1350 return true;
1351
1352 // Is the function New an overload of the function Old?
1353 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1354 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1355
1356 // Compare the signatures (C++ 1.3.10) of the two functions to
1357 // determine whether they are overloads. If we find any mismatch
1358 // in the signature, they are overloads.
1359
1360 // If either of these functions is a K&R-style function (no
1361 // prototype), then we consider them to have matching signatures.
1362 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1364 return false;
1365
1366 const auto *OldType = cast<FunctionProtoType>(OldQType);
1367 const auto *NewType = cast<FunctionProtoType>(NewQType);
1368
1369 // The signature of a function includes the types of its
1370 // parameters (C++ 1.3.10), which includes the presence or absence
1371 // of the ellipsis; see C++ DR 357).
1372 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1373 return true;
1374
1375 // For member-like friends, the enclosing class is part of the signature.
1376 if ((New->isMemberLikeConstrainedFriend() ||
1378 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1379 return true;
1380
1381 // Compare the parameter lists.
1382 // This can only be done once we have establish that friend functions
1383 // inhabit the same context, otherwise we might tried to instantiate
1384 // references to non-instantiated entities during constraint substitution.
1385 // GH78101.
1386 if (NewTemplate) {
1387 OldDecl = OldTemplate;
1388 NewDecl = NewTemplate;
1389 // C++ [temp.over.link]p4:
1390 // The signature of a function template consists of its function
1391 // signature, its return type and its template parameter list. The names
1392 // of the template parameters are significant only for establishing the
1393 // relationship between the template parameters and the rest of the
1394 // signature.
1395 //
1396 // We check the return type and template parameter lists for function
1397 // templates first; the remaining checks follow.
1398 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1399 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1400 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1401 bool SameReturnType = SemaRef.Context.hasSameType(
1402 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1403 // FIXME(GH58571): Match template parameter list even for non-constrained
1404 // template heads. This currently ensures that the code prior to C++20 is
1405 // not newly broken.
1406 bool ConstraintsInTemplateHead =
1409 // C++ [namespace.udecl]p11:
1410 // The set of declarations named by a using-declarator that inhabits a
1411 // class C does not include member functions and member function
1412 // templates of a base class that "correspond" to (and thus would
1413 // conflict with) a declaration of a function or function template in
1414 // C.
1415 // Comparing return types is not required for the "correspond" check to
1416 // decide whether a member introduced by a shadow declaration is hidden.
1417 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1418 !SameTemplateParameterList)
1419 return true;
1420 if (!UseMemberUsingDeclRules &&
1421 (!SameTemplateParameterList || !SameReturnType))
1422 return true;
1423 }
1424
1425 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1426 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1427
1428 int OldParamsOffset = 0;
1429 int NewParamsOffset = 0;
1430
1431 // When determining if a method is an overload from a base class, act as if
1432 // the implicit object parameter are of the same type.
1433
1434 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1436 auto ThisType = M->getFunctionObjectParameterReferenceType();
1437 if (ThisType.isConstQualified())
1438 Q.removeConst();
1439 return Q;
1440 }
1441
1442 // We do not allow overloading based off of '__restrict'.
1443 Q.removeRestrict();
1444
1445 // We may not have applied the implicit const for a constexpr member
1446 // function yet (because we haven't yet resolved whether this is a static
1447 // or non-static member function). Add it now, on the assumption that this
1448 // is a redeclaration of OldMethod.
1449 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1450 (M->isConstexpr() || M->isConsteval()) &&
1451 !isa<CXXConstructorDecl>(NewMethod))
1452 Q.addConst();
1453 return Q;
1454 };
1455
1456 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1457 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1458 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1459
1460 if (OldMethod->isExplicitObjectMemberFunction()) {
1461 BS.Quals.removeVolatile();
1462 DS.Quals.removeVolatile();
1463 }
1464
1465 return BS.Quals == DS.Quals;
1466 };
1467
1468 auto CompareType = [&](QualType Base, QualType D) {
1469 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1470 auto DS = D.getNonReferenceType().getCanonicalType().split();
1471
1472 if (!AreQualifiersEqual(BS, DS))
1473 return false;
1474
1475 if (OldMethod->isImplicitObjectMemberFunction() &&
1476 OldMethod->getParent() != NewMethod->getParent()) {
1477 CanQualType ParentType =
1478 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1479 if (ParentType.getTypePtr() != BS.Ty)
1480 return false;
1481 BS.Ty = DS.Ty;
1482 }
1483
1484 // FIXME: should we ignore some type attributes here?
1485 if (BS.Ty != DS.Ty)
1486 return false;
1487
1488 if (Base->isLValueReferenceType())
1489 return D->isLValueReferenceType();
1490 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1491 };
1492
1493 // If the function is a class member, its signature includes the
1494 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1495 auto DiagnoseInconsistentRefQualifiers = [&]() {
1496 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1497 return false;
1498 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1499 return false;
1500 if (OldMethod->isExplicitObjectMemberFunction() ||
1501 NewMethod->isExplicitObjectMemberFunction())
1502 return false;
1503 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1504 NewMethod->getRefQualifier() == RQ_None)) {
1505 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1506 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1507 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1508 return true;
1509 }
1510 return false;
1511 };
1512
1513 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1514 OldParamsOffset++;
1515 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1516 NewParamsOffset++;
1517
1518 if (OldType->getNumParams() - OldParamsOffset !=
1519 NewType->getNumParams() - NewParamsOffset ||
1521 {OldType->param_type_begin() + OldParamsOffset,
1522 OldType->param_type_end()},
1523 {NewType->param_type_begin() + NewParamsOffset,
1524 NewType->param_type_end()},
1525 nullptr)) {
1526 return true;
1527 }
1528
1529 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1530 !NewMethod->isStatic()) {
1531 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1532 const CXXMethodDecl *New) {
1533 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1534 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1535
1536 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1537 return F->getRefQualifier() == RQ_None &&
1538 !F->isExplicitObjectMemberFunction();
1539 };
1540
1541 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1542 CompareType(OldObjectType.getNonReferenceType(),
1543 NewObjectType.getNonReferenceType()))
1544 return true;
1545 return CompareType(OldObjectType, NewObjectType);
1546 }(OldMethod, NewMethod);
1547
1548 if (!HaveCorrespondingObjectParameters) {
1549 if (DiagnoseInconsistentRefQualifiers())
1550 return true;
1551 // CWG2554
1552 // and, if at least one is an explicit object member function, ignoring
1553 // object parameters
1554 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1555 !OldMethod->isExplicitObjectMemberFunction()))
1556 return true;
1557 }
1558 }
1559
1560 if (!UseOverrideRules &&
1561 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1562 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1563 OldRC = Old->getTrailingRequiresClause();
1564 if (!NewRC != !OldRC)
1565 return true;
1566 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1567 return true;
1568 if (NewRC &&
1569 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1570 NewDecl, NewRC.ConstraintExpr))
1571 return true;
1572 }
1573
1574 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1575 NewMethod->isImplicitObjectMemberFunction()) {
1576 if (DiagnoseInconsistentRefQualifiers())
1577 return true;
1578 }
1579
1580 // Though pass_object_size is placed on parameters and takes an argument, we
1581 // consider it to be a function-level modifier for the sake of function
1582 // identity. Either the function has one or more parameters with
1583 // pass_object_size or it doesn't.
1586 return true;
1587
1588 // enable_if attributes are an order-sensitive part of the signature.
1590 NewI = New->specific_attr_begin<EnableIfAttr>(),
1591 NewE = New->specific_attr_end<EnableIfAttr>(),
1592 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1593 OldE = Old->specific_attr_end<EnableIfAttr>();
1594 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1595 if (NewI == NewE || OldI == OldE)
1596 return true;
1597 llvm::FoldingSetNodeID NewID, OldID;
1598 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1599 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1600 if (NewID != OldID)
1601 return true;
1602 }
1603
1604 // At this point, it is known that the two functions have the same signature.
1605 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1606 // Don't allow overloading of destructors. (In theory we could, but it
1607 // would be a giant change to clang.)
1609 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1610 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1611 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1612 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1613 "Unexpected invalid target.");
1614
1615 // Allow overloading of functions with same signature and different CUDA
1616 // target attributes.
1617 if (NewTarget != OldTarget) {
1618 // Special case: non-constexpr function is allowed to override
1619 // constexpr virtual function
1620 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1621 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1626 return false;
1627 }
1628 return true;
1629 }
1630 }
1631 }
1632 }
1633
1634 // The signatures match; this is not an overload.
1635 return false;
1636}
1637
1639 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1640 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1641 ConsiderCudaAttrs);
1642}
1643
1645 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1646 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1647 /*UseMemberUsingDeclRules=*/false,
1648 /*ConsiderCudaAttrs=*/true,
1649 /*UseOverrideRules=*/true);
1650}
1651
1652/// Tries a user-defined conversion from From to ToType.
1653///
1654/// Produces an implicit conversion sequence for when a standard conversion
1655/// is not an option. See TryImplicitConversion for more information.
1658 bool SuppressUserConversions,
1659 AllowedExplicit AllowExplicit,
1660 bool InOverloadResolution,
1661 bool CStyle,
1662 bool AllowObjCWritebackConversion,
1663 bool AllowObjCConversionOnExplicit) {
1665
1666 if (SuppressUserConversions) {
1667 // We're not in the case above, so there is no conversion that
1668 // we can perform.
1670 return ICS;
1671 }
1672
1673 // Attempt user-defined conversion.
1674 OverloadCandidateSet Conversions(From->getExprLoc(),
1676 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1677 Conversions, AllowExplicit,
1678 AllowObjCConversionOnExplicit)) {
1679 case OR_Success:
1680 case OR_Deleted:
1681 ICS.setUserDefined();
1682 // C++ [over.ics.user]p4:
1683 // A conversion of an expression of class type to the same class
1684 // type is given Exact Match rank, and a conversion of an
1685 // expression of class type to a base class of that type is
1686 // given Conversion rank, in spite of the fact that a copy
1687 // constructor (i.e., a user-defined conversion function) is
1688 // called for those cases.
1690 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1691 QualType FromType;
1692 SourceLocation FromLoc;
1693 // C++11 [over.ics.list]p6, per DR2137:
1694 // C++17 [over.ics.list]p6:
1695 // If C is not an initializer-list constructor and the initializer list
1696 // has a single element of type cv U, where U is X or a class derived
1697 // from X, the implicit conversion sequence has Exact Match rank if U is
1698 // X, or Conversion rank if U is derived from X.
1699 bool FromListInit = false;
1700 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1701 InitList && InitList->getNumInits() == 1 &&
1703 const Expr *SingleInit = InitList->getInit(0);
1704 FromType = SingleInit->getType();
1705 FromLoc = SingleInit->getBeginLoc();
1706 FromListInit = true;
1707 } else {
1708 FromType = From->getType();
1709 FromLoc = From->getBeginLoc();
1710 }
1711 QualType FromCanon =
1713 QualType ToCanon
1715 if ((FromCanon == ToCanon ||
1716 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1717 // Turn this into a "standard" conversion sequence, so that it
1718 // gets ranked with standard conversion sequences.
1720 ICS.setStandard();
1722 ICS.Standard.setFromType(FromType);
1723 ICS.Standard.setAllToTypes(ToType);
1724 ICS.Standard.FromBracedInitList = FromListInit;
1727 if (ToCanon != FromCanon)
1729 }
1730 }
1731 break;
1732
1733 case OR_Ambiguous:
1734 ICS.setAmbiguous();
1735 ICS.Ambiguous.setFromType(From->getType());
1736 ICS.Ambiguous.setToType(ToType);
1737 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1738 Cand != Conversions.end(); ++Cand)
1739 if (Cand->Best)
1740 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1741 break;
1742
1743 // Fall through.
1746 break;
1747 }
1748
1749 return ICS;
1750}
1751
1752/// TryImplicitConversion - Attempt to perform an implicit conversion
1753/// from the given expression (Expr) to the given type (ToType). This
1754/// function returns an implicit conversion sequence that can be used
1755/// to perform the initialization. Given
1756///
1757/// void f(float f);
1758/// void g(int i) { f(i); }
1759///
1760/// this routine would produce an implicit conversion sequence to
1761/// describe the initialization of f from i, which will be a standard
1762/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1763/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1764//
1765/// Note that this routine only determines how the conversion can be
1766/// performed; it does not actually perform the conversion. As such,
1767/// it will not produce any diagnostics if no conversion is available,
1768/// but will instead return an implicit conversion sequence of kind
1769/// "BadConversion".
1770///
1771/// If @p SuppressUserConversions, then user-defined conversions are
1772/// not permitted.
1773/// If @p AllowExplicit, then explicit user-defined conversions are
1774/// permitted.
1775///
1776/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1777/// writeback conversion, which allows __autoreleasing id* parameters to
1778/// be initialized with __strong id* or __weak id* arguments.
1779static ImplicitConversionSequence
1781 bool SuppressUserConversions,
1782 AllowedExplicit AllowExplicit,
1783 bool InOverloadResolution,
1784 bool CStyle,
1785 bool AllowObjCWritebackConversion,
1786 bool AllowObjCConversionOnExplicit) {
1788 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1789 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1790 ICS.setStandard();
1791 return ICS;
1792 }
1793
1794 if (!S.getLangOpts().CPlusPlus) {
1796 return ICS;
1797 }
1798
1799 // C++ [over.ics.user]p4:
1800 // A conversion of an expression of class type to the same class
1801 // type is given Exact Match rank, and a conversion of an
1802 // expression of class type to a base class of that type is
1803 // given Conversion rank, in spite of the fact that a copy/move
1804 // constructor (i.e., a user-defined conversion function) is
1805 // called for those cases.
1806 QualType FromType = From->getType();
1807 if (ToType->isRecordType() &&
1808 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1809 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1810 ICS.setStandard();
1812 ICS.Standard.setFromType(FromType);
1813 ICS.Standard.setAllToTypes(ToType);
1814
1815 // We don't actually check at this point whether there is a valid
1816 // copy/move constructor, since overloading just assumes that it
1817 // exists. When we actually perform initialization, we'll find the
1818 // appropriate constructor to copy the returned object, if needed.
1819 ICS.Standard.CopyConstructor = nullptr;
1820
1821 // Determine whether this is considered a derived-to-base conversion.
1822 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1824
1825 return ICS;
1826 }
1827
1828 if (S.getLangOpts().HLSL) {
1829 // Handle conversion of the HLSL resource types.
1830 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1831 if (FromTy->isHLSLAttributedResourceType()) {
1832 // Attributed resource types can convert to other attributed
1833 // resource types with the same attributes and contained types,
1834 // or to __hlsl_resource_t without any attributes.
1835 bool CanConvert = false;
1836 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1837 if (ToTy->isHLSLAttributedResourceType()) {
1838 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1839 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1840 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1841 FromResType->getWrappedType()) &&
1842 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1843 FromResType->getContainedType()) &&
1844 ToResType->getAttrs() == FromResType->getAttrs())
1845 CanConvert = true;
1846 } else if (ToTy->isHLSLResourceType()) {
1847 CanConvert = true;
1848 }
1849 if (CanConvert) {
1850 ICS.setStandard();
1852 ICS.Standard.setFromType(FromType);
1853 ICS.Standard.setAllToTypes(ToType);
1854 return ICS;
1855 }
1856 }
1857 }
1858
1859 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1860 AllowExplicit, InOverloadResolution, CStyle,
1861 AllowObjCWritebackConversion,
1862 AllowObjCConversionOnExplicit);
1863}
1864
1865ImplicitConversionSequence
1867 bool SuppressUserConversions,
1868 AllowedExplicit AllowExplicit,
1869 bool InOverloadResolution,
1870 bool CStyle,
1871 bool AllowObjCWritebackConversion) {
1872 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1873 AllowExplicit, InOverloadResolution, CStyle,
1874 AllowObjCWritebackConversion,
1875 /*AllowObjCConversionOnExplicit=*/false);
1876}
1877
1879 AssignmentAction Action,
1880 bool AllowExplicit) {
1881 if (checkPlaceholderForOverload(*this, From))
1882 return ExprError();
1883
1884 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1885 bool AllowObjCWritebackConversion =
1886 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1887 Action == AssignmentAction::Sending);
1888 if (getLangOpts().ObjC)
1889 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1890 From->getType(), From);
1892 *this, From, ToType,
1893 /*SuppressUserConversions=*/false,
1894 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1895 /*InOverloadResolution=*/false,
1896 /*CStyle=*/false, AllowObjCWritebackConversion,
1897 /*AllowObjCConversionOnExplicit=*/false);
1898 return PerformImplicitConversion(From, ToType, ICS, Action);
1899}
1900
1902 QualType &ResultTy) const {
1903 bool Changed = IsFunctionConversion(FromType, ToType);
1904 if (Changed)
1905 ResultTy = ToType;
1906 return Changed;
1907}
1908
1909bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1910 if (Context.hasSameUnqualifiedType(FromType, ToType))
1911 return false;
1912
1913 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1914 // or F(t noexcept) -> F(t)
1915 // where F adds one of the following at most once:
1916 // - a pointer
1917 // - a member pointer
1918 // - a block pointer
1919 // Changes here need matching changes in FindCompositePointerType.
1920 CanQualType CanTo = Context.getCanonicalType(ToType);
1921 CanQualType CanFrom = Context.getCanonicalType(FromType);
1922 Type::TypeClass TyClass = CanTo->getTypeClass();
1923 if (TyClass != CanFrom->getTypeClass()) return false;
1924 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1925 if (TyClass == Type::Pointer) {
1926 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1927 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1928 } else if (TyClass == Type::BlockPointer) {
1929 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1930 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1931 } else if (TyClass == Type::MemberPointer) {
1932 auto ToMPT = CanTo.castAs<MemberPointerType>();
1933 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1934 // A function pointer conversion cannot change the class of the function.
1935 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1936 FromMPT->getMostRecentCXXRecordDecl()))
1937 return false;
1938 CanTo = ToMPT->getPointeeType();
1939 CanFrom = FromMPT->getPointeeType();
1940 } else {
1941 return false;
1942 }
1943
1944 TyClass = CanTo->getTypeClass();
1945 if (TyClass != CanFrom->getTypeClass()) return false;
1946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1947 return false;
1948 }
1949
1950 const auto *FromFn = cast<FunctionType>(CanFrom);
1951 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1952
1953 const auto *ToFn = cast<FunctionType>(CanTo);
1954 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1955
1956 bool Changed = false;
1957
1958 // Drop 'noreturn' if not present in target type.
1959 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1960 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1961 Changed = true;
1962 }
1963
1964 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1965 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1966
1967 if (FromFPT && ToFPT) {
1968 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1969 QualType NewTy = Context.getFunctionType(
1970 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1971 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1972 ToFPT->hasCFIUncheckedCallee()));
1973 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1974 FromFn = FromFPT;
1975 Changed = true;
1976 }
1977 }
1978
1979 // Drop 'noexcept' if not present in target type.
1980 if (FromFPT && ToFPT) {
1981 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1982 FromFn = cast<FunctionType>(
1983 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1984 EST_None)
1985 .getTypePtr());
1986 Changed = true;
1987 }
1988
1989 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1990 // only if the ExtParameterInfo lists of the two function prototypes can be
1991 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1993 bool CanUseToFPT, CanUseFromFPT;
1994 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1995 CanUseFromFPT, NewParamInfos) &&
1996 CanUseToFPT && !CanUseFromFPT) {
1997 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1998 ExtInfo.ExtParameterInfos =
1999 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2000 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2001 FromFPT->getParamTypes(), ExtInfo);
2002 FromFn = QT->getAs<FunctionType>();
2003 Changed = true;
2004 }
2005
2006 if (Context.hasAnyFunctionEffects()) {
2007 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2008
2009 // Transparently add/drop effects; here we are concerned with
2010 // language rules/canonicalization. Adding/dropping effects is a warning.
2011 const auto FromFX = FromFPT->getFunctionEffects();
2012 const auto ToFX = ToFPT->getFunctionEffects();
2013 if (FromFX != ToFX) {
2014 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2015 ExtInfo.FunctionEffects = ToFX;
2016 QualType QT = Context.getFunctionType(
2017 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2018 FromFn = QT->getAs<FunctionType>();
2019 Changed = true;
2020 }
2021 }
2022 }
2023
2024 if (!Changed)
2025 return false;
2026
2027 assert(QualType(FromFn, 0).isCanonical());
2028 if (QualType(FromFn, 0) != CanTo) return false;
2029
2030 return true;
2031}
2032
2033/// Determine whether the conversion from FromType to ToType is a valid
2034/// floating point conversion.
2035///
2036static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2037 QualType ToType) {
2038 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2039 return false;
2040 // FIXME: disable conversions between long double, __ibm128 and __float128
2041 // if their representation is different until there is back end support
2042 // We of course allow this conversion if long double is really double.
2043
2044 // Conversions between bfloat16 and float16 are currently not supported.
2045 if ((FromType->isBFloat16Type() &&
2046 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2047 (ToType->isBFloat16Type() &&
2048 (FromType->isFloat16Type() || FromType->isHalfType())))
2049 return false;
2050
2051 // Conversions between IEEE-quad and IBM-extended semantics are not
2052 // permitted.
2053 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2054 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2055 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2056 &ToSem == &llvm::APFloat::IEEEquad()) ||
2057 (&FromSem == &llvm::APFloat::IEEEquad() &&
2058 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2059 return false;
2060 return true;
2061}
2062
2063static bool IsVectorElementConversion(Sema &S, QualType FromType,
2064 QualType ToType,
2065 ImplicitConversionKind &ICK, Expr *From) {
2066 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2067 return true;
2068
2069 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2071 return true;
2072 }
2073
2074 if (IsFloatingPointConversion(S, FromType, ToType)) {
2076 return true;
2077 }
2078
2079 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2081 return true;
2082 }
2083
2084 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2086 ToType->isRealFloatingType())) {
2088 return true;
2089 }
2090
2091 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2093 return true;
2094 }
2095
2096 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2097 ToType->isIntegralType(S.Context)) {
2099 return true;
2100 }
2101
2102 return false;
2103}
2104
2105/// Determine whether the conversion from FromType to ToType is a valid
2106/// vector conversion.
2107///
2108/// \param ICK Will be set to the vector conversion kind, if this is a vector
2109/// conversion.
2110static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2112 ImplicitConversionKind &ElConv, Expr *From,
2113 bool InOverloadResolution, bool CStyle) {
2114 // We need at least one of these types to be a vector type to have a vector
2115 // conversion.
2116 if (!ToType->isVectorType() && !FromType->isVectorType())
2117 return false;
2118
2119 // Identical types require no conversions.
2120 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2121 return false;
2122
2123 // HLSL allows implicit truncation of vector types.
2124 if (S.getLangOpts().HLSL) {
2125 auto *ToExtType = ToType->getAs<ExtVectorType>();
2126 auto *FromExtType = FromType->getAs<ExtVectorType>();
2127
2128 // If both arguments are vectors, handle possible vector truncation and
2129 // element conversion.
2130 if (ToExtType && FromExtType) {
2131 unsigned FromElts = FromExtType->getNumElements();
2132 unsigned ToElts = ToExtType->getNumElements();
2133 if (FromElts < ToElts)
2134 return false;
2135 if (FromElts == ToElts)
2136 ElConv = ICK_Identity;
2137 else
2139
2140 QualType FromElTy = FromExtType->getElementType();
2141 QualType ToElTy = ToExtType->getElementType();
2142 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2143 return true;
2144 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2145 }
2146 if (FromExtType && !ToExtType) {
2148 QualType FromElTy = FromExtType->getElementType();
2149 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2150 return true;
2151 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2152 }
2153 // Fallthrough for the case where ToType is a vector and FromType is not.
2154 }
2155
2156 // There are no conversions between extended vector types, only identity.
2157 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2158 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2159 // Implicit conversions require the same number of elements.
2160 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2161 return false;
2162
2163 // Permit implicit conversions from integral values to boolean vectors.
2164 if (ToType->isExtVectorBoolType() &&
2165 FromExtType->getElementType()->isIntegerType()) {
2167 return true;
2168 }
2169 // There are no other conversions between extended vector types.
2170 return false;
2171 }
2172
2173 // Vector splat from any arithmetic type to a vector.
2174 if (FromType->isArithmeticType()) {
2175 if (S.getLangOpts().HLSL) {
2176 ElConv = ICK_HLSL_Vector_Splat;
2177 QualType ToElTy = ToExtType->getElementType();
2178 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2179 }
2180 ICK = ICK_Vector_Splat;
2181 return true;
2182 }
2183 }
2184
2185 if (ToType->isSVESizelessBuiltinType() ||
2186 FromType->isSVESizelessBuiltinType())
2187 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2188 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2190 return true;
2191 }
2192
2193 if (ToType->isRVVSizelessBuiltinType() ||
2194 FromType->isRVVSizelessBuiltinType())
2195 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2196 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2198 return true;
2199 }
2200
2201 // We can perform the conversion between vector types in the following cases:
2202 // 1)vector types are equivalent AltiVec and GCC vector types
2203 // 2)lax vector conversions are permitted and the vector types are of the
2204 // same size
2205 // 3)the destination type does not have the ARM MVE strict-polymorphism
2206 // attribute, which inhibits lax vector conversion for overload resolution
2207 // only
2208 if (ToType->isVectorType() && FromType->isVectorType()) {
2209 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2210 (S.isLaxVectorConversion(FromType, ToType) &&
2211 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2212 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2213 S.isLaxVectorConversion(FromType, ToType) &&
2214 S.anyAltivecTypes(FromType, ToType) &&
2215 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2216 !InOverloadResolution && !CStyle) {
2217 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2218 << FromType << ToType;
2219 }
2221 return true;
2222 }
2223 }
2224
2225 return false;
2226}
2227
2228static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2229 bool InOverloadResolution,
2230 StandardConversionSequence &SCS,
2231 bool CStyle);
2232
2233/// IsStandardConversion - Determines whether there is a standard
2234/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2235/// expression From to the type ToType. Standard conversion sequences
2236/// only consider non-class types; for conversions that involve class
2237/// types, use TryImplicitConversion. If a conversion exists, SCS will
2238/// contain the standard conversion sequence required to perform this
2239/// conversion and this routine will return true. Otherwise, this
2240/// routine will return false and the value of SCS is unspecified.
2241static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2242 bool InOverloadResolution,
2244 bool CStyle,
2245 bool AllowObjCWritebackConversion) {
2246 QualType FromType = From->getType();
2247
2248 // Standard conversions (C++ [conv])
2250 SCS.IncompatibleObjC = false;
2251 SCS.setFromType(FromType);
2252 SCS.CopyConstructor = nullptr;
2253
2254 // There are no standard conversions for class types in C++, so
2255 // abort early. When overloading in C, however, we do permit them.
2256 if (S.getLangOpts().CPlusPlus &&
2257 (FromType->isRecordType() || ToType->isRecordType()))
2258 return false;
2259
2260 // The first conversion can be an lvalue-to-rvalue conversion,
2261 // array-to-pointer conversion, or function-to-pointer conversion
2262 // (C++ 4p1).
2263
2264 if (FromType == S.Context.OverloadTy) {
2265 DeclAccessPair AccessPair;
2266 if (FunctionDecl *Fn
2267 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2268 AccessPair)) {
2269 // We were able to resolve the address of the overloaded function,
2270 // so we can convert to the type of that function.
2271 FromType = Fn->getType();
2272 SCS.setFromType(FromType);
2273
2274 // we can sometimes resolve &foo<int> regardless of ToType, so check
2275 // if the type matches (identity) or we are converting to bool
2277 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2278 // if the function type matches except for [[noreturn]], it's ok
2279 if (!S.IsFunctionConversion(FromType,
2281 // otherwise, only a boolean conversion is standard
2282 if (!ToType->isBooleanType())
2283 return false;
2284 }
2285
2286 // Check if the "from" expression is taking the address of an overloaded
2287 // function and recompute the FromType accordingly. Take advantage of the
2288 // fact that non-static member functions *must* have such an address-of
2289 // expression.
2290 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2291 if (Method && !Method->isStatic() &&
2292 !Method->isExplicitObjectMemberFunction()) {
2293 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2294 "Non-unary operator on non-static member address");
2295 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2296 == UO_AddrOf &&
2297 "Non-address-of operator on non-static member address");
2298 FromType = S.Context.getMemberPointerType(
2299 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2300 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2301 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2302 UO_AddrOf &&
2303 "Non-address-of operator for overloaded function expression");
2304 FromType = S.Context.getPointerType(FromType);
2305 }
2306 } else {
2307 return false;
2308 }
2309 }
2310
2311 bool argIsLValue = From->isGLValue();
2312 // To handle conversion from ArrayParameterType to ConstantArrayType
2313 // this block must be above the one below because Array parameters
2314 // do not decay and when handling HLSLOutArgExprs and
2315 // the From expression is an LValue.
2316 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2317 ToType->isConstantArrayType()) {
2318 // HLSL constant array parameters do not decay, so if the argument is a
2319 // constant array and the parameter is an ArrayParameterType we have special
2320 // handling here.
2321 if (ToType->isArrayParameterType()) {
2322 FromType = S.Context.getArrayParameterType(FromType);
2323 } else if (FromType->isArrayParameterType()) {
2324 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2325 FromType = APT->getConstantArrayType(S.Context);
2326 }
2327
2329
2330 // Don't consider qualifiers, which include things like address spaces
2331 if (FromType.getCanonicalType().getUnqualifiedType() !=
2333 return false;
2334
2335 SCS.setAllToTypes(ToType);
2336 return true;
2337 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2338 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2339 // Lvalue-to-rvalue conversion (C++11 4.1):
2340 // A glvalue (3.10) of a non-function, non-array type T can
2341 // be converted to a prvalue.
2342
2344
2345 // C11 6.3.2.1p2:
2346 // ... if the lvalue has atomic type, the value has the non-atomic version
2347 // of the type of the lvalue ...
2348 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2349 FromType = Atomic->getValueType();
2350
2351 // If T is a non-class type, the type of the rvalue is the
2352 // cv-unqualified version of T. Otherwise, the type of the rvalue
2353 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2354 // just strip the qualifiers because they don't matter.
2355 FromType = FromType.getUnqualifiedType();
2356 } else if (FromType->isArrayType()) {
2357 // Array-to-pointer conversion (C++ 4.2)
2359
2360 // An lvalue or rvalue of type "array of N T" or "array of unknown
2361 // bound of T" can be converted to an rvalue of type "pointer to
2362 // T" (C++ 4.2p1).
2363 FromType = S.Context.getArrayDecayedType(FromType);
2364
2365 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2366 // This conversion is deprecated in C++03 (D.4)
2368
2369 // For the purpose of ranking in overload resolution
2370 // (13.3.3.1.1), this conversion is considered an
2371 // array-to-pointer conversion followed by a qualification
2372 // conversion (4.4). (C++ 4.2p2)
2373 SCS.Second = ICK_Identity;
2376 SCS.setAllToTypes(FromType);
2377 return true;
2378 }
2379 } else if (FromType->isFunctionType() && argIsLValue) {
2380 // Function-to-pointer conversion (C++ 4.3).
2382
2383 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2384 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2386 return false;
2387
2388 // An lvalue of function type T can be converted to an rvalue of
2389 // type "pointer to T." The result is a pointer to the
2390 // function. (C++ 4.3p1).
2391 FromType = S.Context.getPointerType(FromType);
2392 } else {
2393 // We don't require any conversions for the first step.
2394 SCS.First = ICK_Identity;
2395 }
2396 SCS.setToType(0, FromType);
2397
2398 // The second conversion can be an integral promotion, floating
2399 // point promotion, integral conversion, floating point conversion,
2400 // floating-integral conversion, pointer conversion,
2401 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2402 // For overloading in C, this can also be a "compatible-type"
2403 // conversion.
2404 bool IncompatibleObjC = false;
2406 ImplicitConversionKind DimensionICK = ICK_Identity;
2407 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2408 // The unqualified versions of the types are the same: there's no
2409 // conversion to do.
2410 SCS.Second = ICK_Identity;
2411 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2412 // Integral promotion (C++ 4.5).
2414 FromType = ToType.getUnqualifiedType();
2415 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2416 // Floating point promotion (C++ 4.6).
2418 FromType = ToType.getUnqualifiedType();
2419 } else if (S.IsComplexPromotion(FromType, ToType)) {
2420 // Complex promotion (Clang extension)
2422 FromType = ToType.getUnqualifiedType();
2423 } else if (ToType->isBooleanType() &&
2424 (FromType->isArithmeticType() ||
2425 FromType->isAnyPointerType() ||
2426 FromType->isBlockPointerType() ||
2427 FromType->isMemberPointerType())) {
2428 // Boolean conversions (C++ 4.12).
2430 FromType = S.Context.BoolTy;
2431 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2432 ToType->isIntegralType(S.Context)) {
2433 // Integral conversions (C++ 4.7).
2435 FromType = ToType.getUnqualifiedType();
2436 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2437 // Complex conversions (C99 6.3.1.6)
2439 FromType = ToType.getUnqualifiedType();
2440 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2441 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2442 // Complex-real conversions (C99 6.3.1.7)
2444 FromType = ToType.getUnqualifiedType();
2445 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2446 // Floating point conversions (C++ 4.8).
2448 FromType = ToType.getUnqualifiedType();
2449 } else if ((FromType->isRealFloatingType() &&
2450 ToType->isIntegralType(S.Context)) ||
2452 ToType->isRealFloatingType())) {
2453
2454 // Floating-integral conversions (C++ 4.9).
2456 FromType = ToType.getUnqualifiedType();
2457 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2459 } else if (AllowObjCWritebackConversion &&
2460 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2462 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2463 FromType, IncompatibleObjC)) {
2464 // Pointer conversions (C++ 4.10).
2466 SCS.IncompatibleObjC = IncompatibleObjC;
2467 FromType = FromType.getUnqualifiedType();
2468 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2469 InOverloadResolution, FromType)) {
2470 // Pointer to member conversions (4.11).
2472 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2473 From, InOverloadResolution, CStyle)) {
2474 SCS.Second = SecondICK;
2475 SCS.Dimension = DimensionICK;
2476 FromType = ToType.getUnqualifiedType();
2477 } else if (!S.getLangOpts().CPlusPlus &&
2478 S.Context.typesAreCompatible(ToType, FromType)) {
2479 // Compatible conversions (Clang extension for C function overloading)
2481 FromType = ToType.getUnqualifiedType();
2483 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2485 FromType = ToType;
2486 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2487 CStyle)) {
2488 // tryAtomicConversion has updated the standard conversion sequence
2489 // appropriately.
2490 return true;
2491 } else if (ToType->isEventT() &&
2493 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2495 FromType = ToType;
2496 } else if (ToType->isQueueT() &&
2498 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2500 FromType = ToType;
2501 } else if (ToType->isSamplerT() &&
2504 FromType = ToType;
2505 } else if ((ToType->isFixedPointType() &&
2506 FromType->isConvertibleToFixedPointType()) ||
2507 (FromType->isFixedPointType() &&
2508 ToType->isConvertibleToFixedPointType())) {
2510 FromType = ToType;
2511 } else {
2512 // No second conversion required.
2513 SCS.Second = ICK_Identity;
2514 }
2515 SCS.setToType(1, FromType);
2516
2517 // The third conversion can be a function pointer conversion or a
2518 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2519 bool ObjCLifetimeConversion;
2520 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2521 // Function pointer conversions (removing 'noexcept') including removal of
2522 // 'noreturn' (Clang extension).
2524 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2525 ObjCLifetimeConversion)) {
2527 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2528 FromType = ToType;
2529 } else {
2530 // No conversion required
2531 SCS.Third = ICK_Identity;
2532 }
2533
2534 // C++ [over.best.ics]p6:
2535 // [...] Any difference in top-level cv-qualification is
2536 // subsumed by the initialization itself and does not constitute
2537 // a conversion. [...]
2538 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2539 QualType CanonTo = S.Context.getCanonicalType(ToType);
2540 if (CanonFrom.getLocalUnqualifiedType()
2541 == CanonTo.getLocalUnqualifiedType() &&
2542 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2543 FromType = ToType;
2544 CanonFrom = CanonTo;
2545 }
2546
2547 SCS.setToType(2, FromType);
2548
2549 if (CanonFrom == CanonTo)
2550 return true;
2551
2552 // If we have not converted the argument type to the parameter type,
2553 // this is a bad conversion sequence, unless we're resolving an overload in C.
2554 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2555 return false;
2556
2557 ExprResult ER = ExprResult{From};
2558 AssignConvertType Conv =
2560 /*Diagnose=*/false,
2561 /*DiagnoseCFAudited=*/false,
2562 /*ConvertRHS=*/false);
2563 ImplicitConversionKind SecondConv;
2564 switch (Conv) {
2566 case AssignConvertType::
2567 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2568 SecondConv = ICK_C_Only_Conversion;
2569 break;
2570 // For our purposes, discarding qualifiers is just as bad as using an
2571 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2572 // qualifiers, as well.
2577 break;
2578 default:
2579 return false;
2580 }
2581
2582 // First can only be an lvalue conversion, so we pretend that this was the
2583 // second conversion. First should already be valid from earlier in the
2584 // function.
2585 SCS.Second = SecondConv;
2586 SCS.setToType(1, ToType);
2587
2588 // Third is Identity, because Second should rank us worse than any other
2589 // conversion. This could also be ICK_Qualification, but it's simpler to just
2590 // lump everything in with the second conversion, and we don't gain anything
2591 // from making this ICK_Qualification.
2592 SCS.Third = ICK_Identity;
2593 SCS.setToType(2, ToType);
2594 return true;
2595}
2596
2597static bool
2599 QualType &ToType,
2600 bool InOverloadResolution,
2602 bool CStyle) {
2603
2604 const RecordType *UT = ToType->getAsUnionType();
2605 if (!UT)
2606 return false;
2607 // The field to initialize within the transparent union.
2608 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2609 if (!UD->hasAttr<TransparentUnionAttr>())
2610 return false;
2611 // It's compatible if the expression matches any of the fields.
2612 for (const auto *it : UD->fields()) {
2613 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2614 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2615 ToType = it->getType();
2616 return true;
2617 }
2618 }
2619 return false;
2620}
2621
2622bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2623 const BuiltinType *To = ToType->getAs<BuiltinType>();
2624 // All integers are built-in.
2625 if (!To) {
2626 return false;
2627 }
2628
2629 // An rvalue of type char, signed char, unsigned char, short int, or
2630 // unsigned short int can be converted to an rvalue of type int if
2631 // int can represent all the values of the source type; otherwise,
2632 // the source rvalue can be converted to an rvalue of type unsigned
2633 // int (C++ 4.5p1).
2634 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2635 !FromType->isEnumeralType()) {
2636 if ( // We can promote any signed, promotable integer type to an int
2637 (FromType->isSignedIntegerType() ||
2638 // We can promote any unsigned integer type whose size is
2639 // less than int to an int.
2640 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2641 return To->getKind() == BuiltinType::Int;
2642 }
2643
2644 return To->getKind() == BuiltinType::UInt;
2645 }
2646
2647 // C++11 [conv.prom]p3:
2648 // A prvalue of an unscoped enumeration type whose underlying type is not
2649 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2650 // following types that can represent all the values of the enumeration
2651 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2652 // unsigned int, long int, unsigned long int, long long int, or unsigned
2653 // long long int. If none of the types in that list can represent all the
2654 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2655 // type can be converted to an rvalue a prvalue of the extended integer type
2656 // with lowest integer conversion rank (4.13) greater than the rank of long
2657 // long in which all the values of the enumeration can be represented. If
2658 // there are two such extended types, the signed one is chosen.
2659 // C++11 [conv.prom]p4:
2660 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2661 // can be converted to a prvalue of its underlying type. Moreover, if
2662 // integral promotion can be applied to its underlying type, a prvalue of an
2663 // unscoped enumeration type whose underlying type is fixed can also be
2664 // converted to a prvalue of the promoted underlying type.
2665 if (const auto *FromED = FromType->getAsEnumDecl()) {
2666 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2667 // provided for a scoped enumeration.
2668 if (FromED->isScoped())
2669 return false;
2670
2671 // We can perform an integral promotion to the underlying type of the enum,
2672 // even if that's not the promoted type. Note that the check for promoting
2673 // the underlying type is based on the type alone, and does not consider
2674 // the bitfield-ness of the actual source expression.
2675 if (FromED->isFixed()) {
2676 QualType Underlying = FromED->getIntegerType();
2677 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2678 IsIntegralPromotion(nullptr, Underlying, ToType);
2679 }
2680
2681 // We have already pre-calculated the promotion type, so this is trivial.
2682 if (ToType->isIntegerType() &&
2683 isCompleteType(From->getBeginLoc(), FromType))
2684 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2685
2686 // C++ [conv.prom]p5:
2687 // If the bit-field has an enumerated type, it is treated as any other
2688 // value of that type for promotion purposes.
2689 //
2690 // ... so do not fall through into the bit-field checks below in C++.
2691 if (getLangOpts().CPlusPlus)
2692 return false;
2693 }
2694
2695 // C++0x [conv.prom]p2:
2696 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2697 // to an rvalue a prvalue of the first of the following types that can
2698 // represent all the values of its underlying type: int, unsigned int,
2699 // long int, unsigned long int, long long int, or unsigned long long int.
2700 // If none of the types in that list can represent all the values of its
2701 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2702 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2703 // type.
2704 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2705 ToType->isIntegerType()) {
2706 // Determine whether the type we're converting from is signed or
2707 // unsigned.
2708 bool FromIsSigned = FromType->isSignedIntegerType();
2709 uint64_t FromSize = Context.getTypeSize(FromType);
2710
2711 // The types we'll try to promote to, in the appropriate
2712 // order. Try each of these types.
2713 QualType PromoteTypes[6] = {
2714 Context.IntTy, Context.UnsignedIntTy,
2715 Context.LongTy, Context.UnsignedLongTy ,
2716 Context.LongLongTy, Context.UnsignedLongLongTy
2717 };
2718 for (int Idx = 0; Idx < 6; ++Idx) {
2719 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2720 if (FromSize < ToSize ||
2721 (FromSize == ToSize &&
2722 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2723 // We found the type that we can promote to. If this is the
2724 // type we wanted, we have a promotion. Otherwise, no
2725 // promotion.
2726 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2727 }
2728 }
2729 }
2730
2731 // An rvalue for an integral bit-field (9.6) can be converted to an
2732 // rvalue of type int if int can represent all the values of the
2733 // bit-field; otherwise, it can be converted to unsigned int if
2734 // unsigned int can represent all the values of the bit-field. If
2735 // the bit-field is larger yet, no integral promotion applies to
2736 // it. If the bit-field has an enumerated type, it is treated as any
2737 // other value of that type for promotion purposes (C++ 4.5p3).
2738 // FIXME: We should delay checking of bit-fields until we actually perform the
2739 // conversion.
2740 //
2741 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2742 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2743 // bit-fields and those whose underlying type is larger than int) for GCC
2744 // compatibility.
2745 if (From) {
2746 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2747 std::optional<llvm::APSInt> BitWidth;
2748 if (FromType->isIntegralType(Context) &&
2749 (BitWidth =
2750 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2751 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2752 ToSize = Context.getTypeSize(ToType);
2753
2754 // Are we promoting to an int from a bitfield that fits in an int?
2755 if (*BitWidth < ToSize ||
2756 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2757 return To->getKind() == BuiltinType::Int;
2758 }
2759
2760 // Are we promoting to an unsigned int from an unsigned bitfield
2761 // that fits into an unsigned int?
2762 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2763 return To->getKind() == BuiltinType::UInt;
2764 }
2765
2766 return false;
2767 }
2768 }
2769 }
2770
2771 // An rvalue of type bool can be converted to an rvalue of type int,
2772 // with false becoming zero and true becoming one (C++ 4.5p4).
2773 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2774 return true;
2775 }
2776
2777 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2778 // integral type.
2779 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2780 ToType->isIntegerType())
2781 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2782
2783 return false;
2784}
2785
2787 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2788 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2789 /// An rvalue of type float can be converted to an rvalue of type
2790 /// double. (C++ 4.6p1).
2791 if (FromBuiltin->getKind() == BuiltinType::Float &&
2792 ToBuiltin->getKind() == BuiltinType::Double)
2793 return true;
2794
2795 // C99 6.3.1.5p1:
2796 // When a float is promoted to double or long double, or a
2797 // double is promoted to long double [...].
2798 if (!getLangOpts().CPlusPlus &&
2799 (FromBuiltin->getKind() == BuiltinType::Float ||
2800 FromBuiltin->getKind() == BuiltinType::Double) &&
2801 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2802 ToBuiltin->getKind() == BuiltinType::Float128 ||
2803 ToBuiltin->getKind() == BuiltinType::Ibm128))
2804 return true;
2805
2806 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2807 // or not native half types are enabled.
2808 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2809 (ToBuiltin->getKind() == BuiltinType::Float ||
2810 ToBuiltin->getKind() == BuiltinType::Double))
2811 return true;
2812
2813 // Half can be promoted to float.
2814 if (!getLangOpts().NativeHalfType &&
2815 FromBuiltin->getKind() == BuiltinType::Half &&
2816 ToBuiltin->getKind() == BuiltinType::Float)
2817 return true;
2818 }
2819
2820 return false;
2821}
2822
2824 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2825 if (!FromComplex)
2826 return false;
2827
2828 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2829 if (!ToComplex)
2830 return false;
2831
2832 return IsFloatingPointPromotion(FromComplex->getElementType(),
2833 ToComplex->getElementType()) ||
2834 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2835 ToComplex->getElementType());
2836}
2837
2838/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2839/// the pointer type FromPtr to a pointer to type ToPointee, with the
2840/// same type qualifiers as FromPtr has on its pointee type. ToType,
2841/// if non-empty, will be a pointer to ToType that may or may not have
2842/// the right set of qualifiers on its pointee.
2843///
2844static QualType
2846 QualType ToPointee, QualType ToType,
2847 ASTContext &Context,
2848 bool StripObjCLifetime = false) {
2849 assert((FromPtr->getTypeClass() == Type::Pointer ||
2850 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2851 "Invalid similarly-qualified pointer type");
2852
2853 /// Conversions to 'id' subsume cv-qualifier conversions.
2854 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2855 return ToType.getUnqualifiedType();
2856
2857 QualType CanonFromPointee
2858 = Context.getCanonicalType(FromPtr->getPointeeType());
2859 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2860 Qualifiers Quals = CanonFromPointee.getQualifiers();
2861
2862 if (StripObjCLifetime)
2863 Quals.removeObjCLifetime();
2864
2865 // Exact qualifier match -> return the pointer type we're converting to.
2866 if (CanonToPointee.getLocalQualifiers() == Quals) {
2867 // ToType is exactly what we need. Return it.
2868 if (!ToType.isNull())
2869 return ToType.getUnqualifiedType();
2870
2871 // Build a pointer to ToPointee. It has the right qualifiers
2872 // already.
2873 if (isa<ObjCObjectPointerType>(ToType))
2874 return Context.getObjCObjectPointerType(ToPointee);
2875 return Context.getPointerType(ToPointee);
2876 }
2877
2878 // Just build a canonical type that has the right qualifiers.
2879 QualType QualifiedCanonToPointee
2880 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2881
2882 if (isa<ObjCObjectPointerType>(ToType))
2883 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2884 return Context.getPointerType(QualifiedCanonToPointee);
2885}
2886
2888 bool InOverloadResolution,
2889 ASTContext &Context) {
2890 // Handle value-dependent integral null pointer constants correctly.
2891 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2892 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2894 return !InOverloadResolution;
2895
2896 return Expr->isNullPointerConstant(Context,
2897 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2899}
2900
2902 bool InOverloadResolution,
2903 QualType& ConvertedType,
2904 bool &IncompatibleObjC) {
2905 IncompatibleObjC = false;
2906 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2907 IncompatibleObjC))
2908 return true;
2909
2910 // Conversion from a null pointer constant to any Objective-C pointer type.
2911 if (ToType->isObjCObjectPointerType() &&
2912 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2913 ConvertedType = ToType;
2914 return true;
2915 }
2916
2917 // Blocks: Block pointers can be converted to void*.
2918 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2919 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2920 ConvertedType = ToType;
2921 return true;
2922 }
2923 // Blocks: A null pointer constant can be converted to a block
2924 // pointer type.
2925 if (ToType->isBlockPointerType() &&
2926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2927 ConvertedType = ToType;
2928 return true;
2929 }
2930
2931 // If the left-hand-side is nullptr_t, the right side can be a null
2932 // pointer constant.
2933 if (ToType->isNullPtrType() &&
2934 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2935 ConvertedType = ToType;
2936 return true;
2937 }
2938
2939 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2940 if (!ToTypePtr)
2941 return false;
2942
2943 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2944 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2945 ConvertedType = ToType;
2946 return true;
2947 }
2948
2949 // Beyond this point, both types need to be pointers
2950 // , including objective-c pointers.
2951 QualType ToPointeeType = ToTypePtr->getPointeeType();
2952 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2953 !getLangOpts().ObjCAutoRefCount) {
2954 ConvertedType = BuildSimilarlyQualifiedPointerType(
2955 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2956 Context);
2957 return true;
2958 }
2959 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2960 if (!FromTypePtr)
2961 return false;
2962
2963 QualType FromPointeeType = FromTypePtr->getPointeeType();
2964
2965 // If the unqualified pointee types are the same, this can't be a
2966 // pointer conversion, so don't do all of the work below.
2967 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2968 return false;
2969
2970 // An rvalue of type "pointer to cv T," where T is an object type,
2971 // can be converted to an rvalue of type "pointer to cv void" (C++
2972 // 4.10p2).
2973 if (FromPointeeType->isIncompleteOrObjectType() &&
2974 ToPointeeType->isVoidType()) {
2975 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2976 ToPointeeType,
2977 ToType, Context,
2978 /*StripObjCLifetime=*/true);
2979 return true;
2980 }
2981
2982 // MSVC allows implicit function to void* type conversion.
2983 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2984 ToPointeeType->isVoidType()) {
2985 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2986 ToPointeeType,
2987 ToType, Context);
2988 return true;
2989 }
2990
2991 // When we're overloading in C, we allow a special kind of pointer
2992 // conversion for compatible-but-not-identical pointee types.
2993 if (!getLangOpts().CPlusPlus &&
2994 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2995 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2996 ToPointeeType,
2997 ToType, Context);
2998 return true;
2999 }
3000
3001 // C++ [conv.ptr]p3:
3002 //
3003 // An rvalue of type "pointer to cv D," where D is a class type,
3004 // can be converted to an rvalue of type "pointer to cv B," where
3005 // B is a base class (clause 10) of D. If B is an inaccessible
3006 // (clause 11) or ambiguous (10.2) base class of D, a program that
3007 // necessitates this conversion is ill-formed. The result of the
3008 // conversion is a pointer to the base class sub-object of the
3009 // derived class object. The null pointer value is converted to
3010 // the null pointer value of the destination type.
3011 //
3012 // Note that we do not check for ambiguity or inaccessibility
3013 // here. That is handled by CheckPointerConversion.
3014 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3015 ToPointeeType->isRecordType() &&
3016 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3017 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3018 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3019 ToPointeeType,
3020 ToType, Context);
3021 return true;
3022 }
3023
3024 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3025 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3026 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3027 ToPointeeType,
3028 ToType, Context);
3029 return true;
3030 }
3031
3032 return false;
3033}
3034
3035/// Adopt the given qualifiers for the given type.
3037 Qualifiers TQs = T.getQualifiers();
3038
3039 // Check whether qualifiers already match.
3040 if (TQs == Qs)
3041 return T;
3042
3043 if (Qs.compatiblyIncludes(TQs, Context))
3044 return Context.getQualifiedType(T, Qs);
3045
3046 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3047}
3048
3050 QualType& ConvertedType,
3051 bool &IncompatibleObjC) {
3052 if (!getLangOpts().ObjC)
3053 return false;
3054
3055 // The set of qualifiers on the type we're converting from.
3056 Qualifiers FromQualifiers = FromType.getQualifiers();
3057
3058 // First, we handle all conversions on ObjC object pointer types.
3059 const ObjCObjectPointerType* ToObjCPtr =
3060 ToType->getAs<ObjCObjectPointerType>();
3061 const ObjCObjectPointerType *FromObjCPtr =
3062 FromType->getAs<ObjCObjectPointerType>();
3063
3064 if (ToObjCPtr && FromObjCPtr) {
3065 // If the pointee types are the same (ignoring qualifications),
3066 // then this is not a pointer conversion.
3067 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3068 FromObjCPtr->getPointeeType()))
3069 return false;
3070
3071 // Conversion between Objective-C pointers.
3072 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3073 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3074 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3075 if (getLangOpts().CPlusPlus && LHS && RHS &&
3077 FromObjCPtr->getPointeeType(), getASTContext()))
3078 return false;
3079 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3080 ToObjCPtr->getPointeeType(),
3081 ToType, Context);
3082 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3083 return true;
3084 }
3085
3086 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3087 // Okay: this is some kind of implicit downcast of Objective-C
3088 // interfaces, which is permitted. However, we're going to
3089 // complain about it.
3090 IncompatibleObjC = true;
3091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3092 ToObjCPtr->getPointeeType(),
3093 ToType, Context);
3094 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3095 return true;
3096 }
3097 }
3098 // Beyond this point, both types need to be C pointers or block pointers.
3099 QualType ToPointeeType;
3100 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3101 ToPointeeType = ToCPtr->getPointeeType();
3102 else if (const BlockPointerType *ToBlockPtr =
3103 ToType->getAs<BlockPointerType>()) {
3104 // Objective C++: We're able to convert from a pointer to any object
3105 // to a block pointer type.
3106 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3107 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3108 return true;
3109 }
3110 ToPointeeType = ToBlockPtr->getPointeeType();
3111 }
3112 else if (FromType->getAs<BlockPointerType>() &&
3113 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3114 // Objective C++: We're able to convert from a block pointer type to a
3115 // pointer to any object.
3116 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3117 return true;
3118 }
3119 else
3120 return false;
3121
3122 QualType FromPointeeType;
3123 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3124 FromPointeeType = FromCPtr->getPointeeType();
3125 else if (const BlockPointerType *FromBlockPtr =
3126 FromType->getAs<BlockPointerType>())
3127 FromPointeeType = FromBlockPtr->getPointeeType();
3128 else
3129 return false;
3130
3131 // If we have pointers to pointers, recursively check whether this
3132 // is an Objective-C conversion.
3133 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3134 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3135 IncompatibleObjC)) {
3136 // We always complain about this conversion.
3137 IncompatibleObjC = true;
3138 ConvertedType = Context.getPointerType(ConvertedType);
3139 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3140 return true;
3141 }
3142 // Allow conversion of pointee being objective-c pointer to another one;
3143 // as in I* to id.
3144 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3145 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3146 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3147 IncompatibleObjC)) {
3148
3149 ConvertedType = Context.getPointerType(ConvertedType);
3150 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3151 return true;
3152 }
3153
3154 // If we have pointers to functions or blocks, check whether the only
3155 // differences in the argument and result types are in Objective-C
3156 // pointer conversions. If so, we permit the conversion (but
3157 // complain about it).
3158 const FunctionProtoType *FromFunctionType
3159 = FromPointeeType->getAs<FunctionProtoType>();
3160 const FunctionProtoType *ToFunctionType
3161 = ToPointeeType->getAs<FunctionProtoType>();
3162 if (FromFunctionType && ToFunctionType) {
3163 // If the function types are exactly the same, this isn't an
3164 // Objective-C pointer conversion.
3165 if (Context.getCanonicalType(FromPointeeType)
3166 == Context.getCanonicalType(ToPointeeType))
3167 return false;
3168
3169 // Perform the quick checks that will tell us whether these
3170 // function types are obviously different.
3171 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3172 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3173 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3174 return false;
3175
3176 bool HasObjCConversion = false;
3177 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3178 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3179 // Okay, the types match exactly. Nothing to do.
3180 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3181 ToFunctionType->getReturnType(),
3182 ConvertedType, IncompatibleObjC)) {
3183 // Okay, we have an Objective-C pointer conversion.
3184 HasObjCConversion = true;
3185 } else {
3186 // Function types are too different. Abort.
3187 return false;
3188 }
3189
3190 // Check argument types.
3191 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3192 ArgIdx != NumArgs; ++ArgIdx) {
3193 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3194 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3195 if (Context.getCanonicalType(FromArgType)
3196 == Context.getCanonicalType(ToArgType)) {
3197 // Okay, the types match exactly. Nothing to do.
3198 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3199 ConvertedType, IncompatibleObjC)) {
3200 // Okay, we have an Objective-C pointer conversion.
3201 HasObjCConversion = true;
3202 } else {
3203 // Argument types are too different. Abort.
3204 return false;
3205 }
3206 }
3207
3208 if (HasObjCConversion) {
3209 // We had an Objective-C conversion. Allow this pointer
3210 // conversion, but complain about it.
3211 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3212 IncompatibleObjC = true;
3213 return true;
3214 }
3215 }
3216
3217 return false;
3218}
3219
3221 QualType& ConvertedType) {
3222 QualType ToPointeeType;
3223 if (const BlockPointerType *ToBlockPtr =
3224 ToType->getAs<BlockPointerType>())
3225 ToPointeeType = ToBlockPtr->getPointeeType();
3226 else
3227 return false;
3228
3229 QualType FromPointeeType;
3230 if (const BlockPointerType *FromBlockPtr =
3231 FromType->getAs<BlockPointerType>())
3232 FromPointeeType = FromBlockPtr->getPointeeType();
3233 else
3234 return false;
3235 // We have pointer to blocks, check whether the only
3236 // differences in the argument and result types are in Objective-C
3237 // pointer conversions. If so, we permit the conversion.
3238
3239 const FunctionProtoType *FromFunctionType
3240 = FromPointeeType->getAs<FunctionProtoType>();
3241 const FunctionProtoType *ToFunctionType
3242 = ToPointeeType->getAs<FunctionProtoType>();
3243
3244 if (!FromFunctionType || !ToFunctionType)
3245 return false;
3246
3247 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3248 return true;
3249
3250 // Perform the quick checks that will tell us whether these
3251 // function types are obviously different.
3252 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3253 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3254 return false;
3255
3256 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3257 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3258 if (FromEInfo != ToEInfo)
3259 return false;
3260
3261 bool IncompatibleObjC = false;
3262 if (Context.hasSameType(FromFunctionType->getReturnType(),
3263 ToFunctionType->getReturnType())) {
3264 // Okay, the types match exactly. Nothing to do.
3265 } else {
3266 QualType RHS = FromFunctionType->getReturnType();
3267 QualType LHS = ToFunctionType->getReturnType();
3268 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3269 !RHS.hasQualifiers() && LHS.hasQualifiers())
3270 LHS = LHS.getUnqualifiedType();
3271
3272 if (Context.hasSameType(RHS,LHS)) {
3273 // OK exact match.
3274 } else if (isObjCPointerConversion(RHS, LHS,
3275 ConvertedType, IncompatibleObjC)) {
3276 if (IncompatibleObjC)
3277 return false;
3278 // Okay, we have an Objective-C pointer conversion.
3279 }
3280 else
3281 return false;
3282 }
3283
3284 // Check argument types.
3285 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3286 ArgIdx != NumArgs; ++ArgIdx) {
3287 IncompatibleObjC = false;
3288 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3289 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3290 if (Context.hasSameType(FromArgType, ToArgType)) {
3291 // Okay, the types match exactly. Nothing to do.
3292 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3293 ConvertedType, IncompatibleObjC)) {
3294 if (IncompatibleObjC)
3295 return false;
3296 // Okay, we have an Objective-C pointer conversion.
3297 } else
3298 // Argument types are too different. Abort.
3299 return false;
3300 }
3301
3303 bool CanUseToFPT, CanUseFromFPT;
3304 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3305 CanUseToFPT, CanUseFromFPT,
3306 NewParamInfos))
3307 return false;
3308
3309 ConvertedType = ToType;
3310 return true;
3311}
3312
3313enum {
3321};
3322
3323/// Attempts to get the FunctionProtoType from a Type. Handles
3324/// MemberFunctionPointers properly.
3326 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3327 return FPT;
3328
3329 if (auto *MPT = FromType->getAs<MemberPointerType>())
3330 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3331
3332 return nullptr;
3333}
3334
3336 QualType FromType, QualType ToType) {
3337 // If either type is not valid, include no extra info.
3338 if (FromType.isNull() || ToType.isNull()) {
3339 PDiag << ft_default;
3340 return;
3341 }
3342
3343 // Get the function type from the pointers.
3344 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3345 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3346 *ToMember = ToType->castAs<MemberPointerType>();
3347 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3348 ToMember->getMostRecentCXXRecordDecl())) {
3350 if (ToMember->isSugared())
3351 PDiag << Context.getCanonicalTagType(
3352 ToMember->getMostRecentCXXRecordDecl());
3353 else
3354 PDiag << ToMember->getQualifier();
3355 if (FromMember->isSugared())
3356 PDiag << Context.getCanonicalTagType(
3357 FromMember->getMostRecentCXXRecordDecl());
3358 else
3359 PDiag << FromMember->getQualifier();
3360 return;
3361 }
3362 FromType = FromMember->getPointeeType();
3363 ToType = ToMember->getPointeeType();
3364 }
3365
3366 if (FromType->isPointerType())
3367 FromType = FromType->getPointeeType();
3368 if (ToType->isPointerType())
3369 ToType = ToType->getPointeeType();
3370
3371 // Remove references.
3372 FromType = FromType.getNonReferenceType();
3373 ToType = ToType.getNonReferenceType();
3374
3375 // Don't print extra info for non-specialized template functions.
3376 if (FromType->isInstantiationDependentType() &&
3377 !FromType->getAs<TemplateSpecializationType>()) {
3378 PDiag << ft_default;
3379 return;
3380 }
3381
3382 // No extra info for same types.
3383 if (Context.hasSameType(FromType, ToType)) {
3384 PDiag << ft_default;
3385 return;
3386 }
3387
3388 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3389 *ToFunction = tryGetFunctionProtoType(ToType);
3390
3391 // Both types need to be function types.
3392 if (!FromFunction || !ToFunction) {
3393 PDiag << ft_default;
3394 return;
3395 }
3396
3397 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3398 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3399 << FromFunction->getNumParams();
3400 return;
3401 }
3402
3403 // Handle different parameter types.
3404 unsigned ArgPos;
3405 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3406 PDiag << ft_parameter_mismatch << ArgPos + 1
3407 << ToFunction->getParamType(ArgPos)
3408 << FromFunction->getParamType(ArgPos);
3409 return;
3410 }
3411
3412 // Handle different return type.
3413 if (!Context.hasSameType(FromFunction->getReturnType(),
3414 ToFunction->getReturnType())) {
3415 PDiag << ft_return_type << ToFunction->getReturnType()
3416 << FromFunction->getReturnType();
3417 return;
3418 }
3419
3420 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3421 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3422 << FromFunction->getMethodQuals();
3423 return;
3424 }
3425
3426 // Handle exception specification differences on canonical type (in C++17
3427 // onwards).
3429 ->isNothrow() !=
3430 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3431 ->isNothrow()) {
3432 PDiag << ft_noexcept;
3433 return;
3434 }
3435
3436 // Unable to find a difference, so add no extra info.
3437 PDiag << ft_default;
3438}
3439
3441 ArrayRef<QualType> New, unsigned *ArgPos,
3442 bool Reversed) {
3443 assert(llvm::size(Old) == llvm::size(New) &&
3444 "Can't compare parameters of functions with different number of "
3445 "parameters!");
3446
3447 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3448 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3449 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3450
3451 // Ignore address spaces in pointee type. This is to disallow overloading
3452 // on __ptr32/__ptr64 address spaces.
3453 QualType OldType =
3454 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3455 QualType NewType =
3456 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3457
3458 if (!Context.hasSameType(OldType, NewType)) {
3459 if (ArgPos)
3460 *ArgPos = Idx;
3461 return false;
3462 }
3463 }
3464 return true;
3465}
3466
3468 const FunctionProtoType *NewType,
3469 unsigned *ArgPos, bool Reversed) {
3470 return FunctionParamTypesAreEqual(OldType->param_types(),
3471 NewType->param_types(), ArgPos, Reversed);
3472}
3473
3475 const FunctionDecl *NewFunction,
3476 unsigned *ArgPos,
3477 bool Reversed) {
3478
3479 if (OldFunction->getNumNonObjectParams() !=
3480 NewFunction->getNumNonObjectParams())
3481 return false;
3482
3483 unsigned OldIgnore =
3485 unsigned NewIgnore =
3487
3488 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3489 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3490
3491 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3492 NewPT->param_types().slice(NewIgnore),
3493 ArgPos, Reversed);
3494}
3495
3497 CastKind &Kind,
3498 CXXCastPath& BasePath,
3499 bool IgnoreBaseAccess,
3500 bool Diagnose) {
3501 QualType FromType = From->getType();
3502 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3503
3504 Kind = CK_BitCast;
3505
3506 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3509 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3510 DiagRuntimeBehavior(From->getExprLoc(), From,
3511 PDiag(diag::warn_impcast_bool_to_null_pointer)
3512 << ToType << From->getSourceRange());
3513 else if (!isUnevaluatedContext())
3514 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3515 << ToType << From->getSourceRange();
3516 }
3517 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3518 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3519 QualType FromPointeeType = FromPtrType->getPointeeType(),
3520 ToPointeeType = ToPtrType->getPointeeType();
3521
3522 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3523 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3524 // We must have a derived-to-base conversion. Check an
3525 // ambiguous or inaccessible conversion.
3526 unsigned InaccessibleID = 0;
3527 unsigned AmbiguousID = 0;
3528 if (Diagnose) {
3529 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3530 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3531 }
3533 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3534 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3535 &BasePath, IgnoreBaseAccess))
3536 return true;
3537
3538 // The conversion was successful.
3539 Kind = CK_DerivedToBase;
3540 }
3541
3542 if (Diagnose && !IsCStyleOrFunctionalCast &&
3543 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3544 assert(getLangOpts().MSVCCompat &&
3545 "this should only be possible with MSVCCompat!");
3546 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3547 << From->getSourceRange();
3548 }
3549 }
3550 } else if (const ObjCObjectPointerType *ToPtrType =
3551 ToType->getAs<ObjCObjectPointerType>()) {
3552 if (const ObjCObjectPointerType *FromPtrType =
3553 FromType->getAs<ObjCObjectPointerType>()) {
3554 // Objective-C++ conversions are always okay.
3555 // FIXME: We should have a different class of conversions for the
3556 // Objective-C++ implicit conversions.
3557 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3558 return false;
3559 } else if (FromType->isBlockPointerType()) {
3560 Kind = CK_BlockPointerToObjCPointerCast;
3561 } else {
3562 Kind = CK_CPointerToObjCPointerCast;
3563 }
3564 } else if (ToType->isBlockPointerType()) {
3565 if (!FromType->isBlockPointerType())
3566 Kind = CK_AnyPointerToBlockPointerCast;
3567 }
3568
3569 // We shouldn't fall into this case unless it's valid for other
3570 // reasons.
3572 Kind = CK_NullToPointer;
3573
3574 return false;
3575}
3576
3578 QualType ToType,
3579 bool InOverloadResolution,
3580 QualType &ConvertedType) {
3581 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3582 if (!ToTypePtr)
3583 return false;
3584
3585 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3587 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3589 ConvertedType = ToType;
3590 return true;
3591 }
3592
3593 // Otherwise, both types have to be member pointers.
3594 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3595 if (!FromTypePtr)
3596 return false;
3597
3598 // A pointer to member of B can be converted to a pointer to member of D,
3599 // where D is derived from B (C++ 4.11p2).
3600 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3601 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3602
3603 if (!declaresSameEntity(FromClass, ToClass) &&
3604 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3605 ConvertedType = Context.getMemberPointerType(
3606 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3607 return true;
3608 }
3609
3610 return false;
3611}
3612
3614 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3615 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3616 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3617 // Lock down the inheritance model right now in MS ABI, whether or not the
3618 // pointee types are the same.
3619 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3620 (void)isCompleteType(CheckLoc, FromType);
3621 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3622 }
3623
3624 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3625 if (!FromPtrType) {
3626 // This must be a null pointer to member pointer conversion
3627 Kind = CK_NullToMemberPointer;
3629 }
3630
3631 // T == T, modulo cv
3633 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3634 ToPtrType->getPointeeType()))
3636
3637 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3638 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3639
3640 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3641 const CXXRecordDecl *Cls) {
3642 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3643 PD << Qual;
3644 else
3645 PD << Context.getCanonicalTagType(Cls);
3646 };
3647 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3648 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3649 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3650 return PD;
3651 };
3652
3653 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3655 std::swap(Base, Derived);
3656
3657 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3658 /*DetectVirtual=*/true);
3659 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3661
3662 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3663 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3664 PD << int(Direction);
3665 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3666 Diag(CheckLoc, PD);
3668 }
3669
3670 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3671 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3672 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3673 Diag(CheckLoc, PD);
3675 }
3676
3677 // Must be a base to derived member conversion.
3678 BuildBasePathArray(Paths, BasePath);
3680 ? CK_DerivedToBaseMemberPointer
3681 : CK_BaseToDerivedMemberPointer;
3682
3683 if (!IgnoreBaseAccess)
3684 switch (CheckBaseClassAccess(
3685 CheckLoc, Base, Derived, Paths.front(),
3687 ? diag::err_upcast_to_inaccessible_base
3688 : diag::err_downcast_from_inaccessible_base,
3689 [&](PartialDiagnostic &PD) {
3690 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3691 DerivedQual = ToPtrType->getQualifier();
3692 if (Direction == MemberPointerConversionDirection::Upcast)
3693 std::swap(BaseQual, DerivedQual);
3694 DiagCls(PD, DerivedQual, Derived);
3695 DiagCls(PD, BaseQual, Base);
3696 })) {
3698 case Sema::AR_delayed:
3699 case Sema::AR_dependent:
3700 // Optimistically assume that the delayed and dependent cases
3701 // will work out.
3702 break;
3703
3706 }
3707
3709}
3710
3711/// Determine whether the lifetime conversion between the two given
3712/// qualifiers sets is nontrivial.
3714 Qualifiers ToQuals) {
3715 // Converting anything to const __unsafe_unretained is trivial.
3716 if (ToQuals.hasConst() &&
3718 return false;
3719
3720 return true;
3721}
3722
3723/// Perform a single iteration of the loop for checking if a qualification
3724/// conversion is valid.
3725///
3726/// Specifically, check whether any change between the qualifiers of \p
3727/// FromType and \p ToType is permissible, given knowledge about whether every
3728/// outer layer is const-qualified.
3730 bool CStyle, bool IsTopLevel,
3731 bool &PreviousToQualsIncludeConst,
3732 bool &ObjCLifetimeConversion,
3733 const ASTContext &Ctx) {
3734 Qualifiers FromQuals = FromType.getQualifiers();
3735 Qualifiers ToQuals = ToType.getQualifiers();
3736
3737 // Ignore __unaligned qualifier.
3738 FromQuals.removeUnaligned();
3739
3740 // Objective-C ARC:
3741 // Check Objective-C lifetime conversions.
3742 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3743 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3744 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3745 ObjCLifetimeConversion = true;
3746 FromQuals.removeObjCLifetime();
3747 ToQuals.removeObjCLifetime();
3748 } else {
3749 // Qualification conversions cannot cast between different
3750 // Objective-C lifetime qualifiers.
3751 return false;
3752 }
3753 }
3754
3755 // Allow addition/removal of GC attributes but not changing GC attributes.
3756 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3757 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3758 FromQuals.removeObjCGCAttr();
3759 ToQuals.removeObjCGCAttr();
3760 }
3761
3762 // __ptrauth qualifiers must match exactly.
3763 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3764 return false;
3765
3766 // -- for every j > 0, if const is in cv 1,j then const is in cv
3767 // 2,j, and similarly for volatile.
3768 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3769 return false;
3770
3771 // If address spaces mismatch:
3772 // - in top level it is only valid to convert to addr space that is a
3773 // superset in all cases apart from C-style casts where we allow
3774 // conversions between overlapping address spaces.
3775 // - in non-top levels it is not a valid conversion.
3776 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3777 (!IsTopLevel ||
3778 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3779 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3780 return false;
3781
3782 // -- if the cv 1,j and cv 2,j are different, then const is in
3783 // every cv for 0 < k < j.
3784 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3785 !PreviousToQualsIncludeConst)
3786 return false;
3787
3788 // The following wording is from C++20, where the result of the conversion
3789 // is T3, not T2.
3790 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3791 // "array of unknown bound of"
3792 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3793 return false;
3794
3795 // -- if the resulting P3,i is different from P1,i [...], then const is
3796 // added to every cv 3_k for 0 < k < i.
3797 if (!CStyle && FromType->isConstantArrayType() &&
3798 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3799 return false;
3800
3801 // Keep track of whether all prior cv-qualifiers in the "to" type
3802 // include const.
3803 PreviousToQualsIncludeConst =
3804 PreviousToQualsIncludeConst && ToQuals.hasConst();
3805 return true;
3806}
3807
3808bool
3810 bool CStyle, bool &ObjCLifetimeConversion) {
3811 FromType = Context.getCanonicalType(FromType);
3812 ToType = Context.getCanonicalType(ToType);
3813 ObjCLifetimeConversion = false;
3814
3815 // If FromType and ToType are the same type, this is not a
3816 // qualification conversion.
3817 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3818 return false;
3819
3820 // (C++ 4.4p4):
3821 // A conversion can add cv-qualifiers at levels other than the first
3822 // in multi-level pointers, subject to the following rules: [...]
3823 bool PreviousToQualsIncludeConst = true;
3824 bool UnwrappedAnyPointer = false;
3825 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3826 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3827 !UnwrappedAnyPointer,
3828 PreviousToQualsIncludeConst,
3829 ObjCLifetimeConversion, getASTContext()))
3830 return false;
3831 UnwrappedAnyPointer = true;
3832 }
3833
3834 // We are left with FromType and ToType being the pointee types
3835 // after unwrapping the original FromType and ToType the same number
3836 // of times. If we unwrapped any pointers, and if FromType and
3837 // ToType have the same unqualified type (since we checked
3838 // qualifiers above), then this is a qualification conversion.
3839 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3840}
3841
3842/// - Determine whether this is a conversion from a scalar type to an
3843/// atomic type.
3844///
3845/// If successful, updates \c SCS's second and third steps in the conversion
3846/// sequence to finish the conversion.
3847static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3848 bool InOverloadResolution,
3850 bool CStyle) {
3851 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3852 if (!ToAtomic)
3853 return false;
3854
3856 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3857 InOverloadResolution, InnerSCS,
3858 CStyle, /*AllowObjCWritebackConversion=*/false))
3859 return false;
3860
3861 SCS.Second = InnerSCS.Second;
3862 SCS.setToType(1, InnerSCS.getToType(1));
3863 SCS.Third = InnerSCS.Third;
3866 SCS.setToType(2, InnerSCS.getToType(2));
3867 return true;
3868}
3869
3872 QualType Type) {
3873 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3874 if (CtorType->getNumParams() > 0) {
3875 QualType FirstArg = CtorType->getParamType(0);
3876 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3877 return true;
3878 }
3879 return false;
3880}
3881
3882static OverloadingResult
3884 CXXRecordDecl *To,
3886 OverloadCandidateSet &CandidateSet,
3887 bool AllowExplicit) {
3889 for (auto *D : S.LookupConstructors(To)) {
3890 auto Info = getConstructorInfo(D);
3891 if (!Info)
3892 continue;
3893
3894 bool Usable = !Info.Constructor->isInvalidDecl() &&
3895 S.isInitListConstructor(Info.Constructor);
3896 if (Usable) {
3897 bool SuppressUserConversions = false;
3898 if (Info.ConstructorTmpl)
3899 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3900 /*ExplicitArgs*/ nullptr, From,
3901 CandidateSet, SuppressUserConversions,
3902 /*PartialOverloading*/ false,
3903 AllowExplicit);
3904 else
3905 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3906 CandidateSet, SuppressUserConversions,
3907 /*PartialOverloading*/ false, AllowExplicit);
3908 }
3909 }
3910
3911 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3912
3914 switch (auto Result =
3915 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3916 case OR_Deleted:
3917 case OR_Success: {
3918 // Record the standard conversion we used and the conversion function.
3920 QualType ThisType = Constructor->getFunctionObjectParameterType();
3921 // Initializer lists don't have conversions as such.
3923 User.HadMultipleCandidates = HadMultipleCandidates;
3925 User.FoundConversionFunction = Best->FoundDecl;
3927 User.After.setFromType(ThisType);
3928 User.After.setAllToTypes(ToType);
3929 return Result;
3930 }
3931
3933 return OR_No_Viable_Function;
3934 case OR_Ambiguous:
3935 return OR_Ambiguous;
3936 }
3937
3938 llvm_unreachable("Invalid OverloadResult!");
3939}
3940
3941/// Determines whether there is a user-defined conversion sequence
3942/// (C++ [over.ics.user]) that converts expression From to the type
3943/// ToType. If such a conversion exists, User will contain the
3944/// user-defined conversion sequence that performs such a conversion
3945/// and this routine will return true. Otherwise, this routine returns
3946/// false and User is unspecified.
3947///
3948/// \param AllowExplicit true if the conversion should consider C++0x
3949/// "explicit" conversion functions as well as non-explicit conversion
3950/// functions (C++0x [class.conv.fct]p2).
3951///
3952/// \param AllowObjCConversionOnExplicit true if the conversion should
3953/// allow an extra Objective-C pointer conversion on uses of explicit
3954/// constructors. Requires \c AllowExplicit to also be set.
3955static OverloadingResult
3958 OverloadCandidateSet &CandidateSet,
3959 AllowedExplicit AllowExplicit,
3960 bool AllowObjCConversionOnExplicit) {
3961 assert(AllowExplicit != AllowedExplicit::None ||
3962 !AllowObjCConversionOnExplicit);
3964
3965 // Whether we will only visit constructors.
3966 bool ConstructorsOnly = false;
3967
3968 // If the type we are conversion to is a class type, enumerate its
3969 // constructors.
3970 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
3971 // C++ [over.match.ctor]p1:
3972 // When objects of class type are direct-initialized (8.5), or
3973 // copy-initialized from an expression of the same or a
3974 // derived class type (8.5), overload resolution selects the
3975 // constructor. [...] For copy-initialization, the candidate
3976 // functions are all the converting constructors (12.3.1) of
3977 // that class. The argument list is the expression-list within
3978 // the parentheses of the initializer.
3979 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3980 (From->getType()->isRecordType() &&
3981 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3982 ConstructorsOnly = true;
3983
3984 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3985 // We're not going to find any constructors.
3986 } else if (auto *ToRecordDecl =
3987 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3988 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
3989
3990 Expr **Args = &From;
3991 unsigned NumArgs = 1;
3992 bool ListInitializing = false;
3993 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3994 // But first, see if there is an init-list-constructor that will work.
3996 S, From, ToType, ToRecordDecl, User, CandidateSet,
3997 AllowExplicit == AllowedExplicit::All);
3998 if (Result != OR_No_Viable_Function)
3999 return Result;
4000 // Never mind.
4001 CandidateSet.clear(
4003
4004 // If we're list-initializing, we pass the individual elements as
4005 // arguments, not the entire list.
4006 Args = InitList->getInits();
4007 NumArgs = InitList->getNumInits();
4008 ListInitializing = true;
4009 }
4010
4011 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4012 auto Info = getConstructorInfo(D);
4013 if (!Info)
4014 continue;
4015
4016 bool Usable = !Info.Constructor->isInvalidDecl();
4017 if (!ListInitializing)
4018 Usable = Usable && Info.Constructor->isConvertingConstructor(
4019 /*AllowExplicit*/ true);
4020 if (Usable) {
4021 bool SuppressUserConversions = !ConstructorsOnly;
4022 // C++20 [over.best.ics.general]/4.5:
4023 // if the target is the first parameter of a constructor [of class
4024 // X] and the constructor [...] is a candidate by [...] the second
4025 // phase of [over.match.list] when the initializer list has exactly
4026 // one element that is itself an initializer list, [...] and the
4027 // conversion is to X or reference to cv X, user-defined conversion
4028 // sequences are not considered.
4029 if (SuppressUserConversions && ListInitializing) {
4030 SuppressUserConversions =
4031 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4032 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4033 ToType);
4034 }
4035 if (Info.ConstructorTmpl)
4037 Info.ConstructorTmpl, Info.FoundDecl,
4038 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4039 CandidateSet, SuppressUserConversions,
4040 /*PartialOverloading*/ false,
4041 AllowExplicit == AllowedExplicit::All);
4042 else
4043 // Allow one user-defined conversion when user specifies a
4044 // From->ToType conversion via an static cast (c-style, etc).
4045 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4046 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4047 SuppressUserConversions,
4048 /*PartialOverloading*/ false,
4049 AllowExplicit == AllowedExplicit::All);
4050 }
4051 }
4052 }
4053 }
4054
4055 // Enumerate conversion functions, if we're allowed to.
4056 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4057 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4058 // No conversion functions from incomplete types.
4059 } else if (const RecordType *FromRecordType =
4060 From->getType()->getAsCanonical<RecordType>()) {
4061 if (auto *FromRecordDecl =
4062 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4063 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4064 // Add all of the conversion functions as candidates.
4065 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4066 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4067 DeclAccessPair FoundDecl = I.getPair();
4068 NamedDecl *D = FoundDecl.getDecl();
4069 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4070 if (isa<UsingShadowDecl>(D))
4071 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4072
4073 CXXConversionDecl *Conv;
4074 FunctionTemplateDecl *ConvTemplate;
4075 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4076 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4077 else
4078 Conv = cast<CXXConversionDecl>(D);
4079
4080 if (ConvTemplate)
4082 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4083 CandidateSet, AllowObjCConversionOnExplicit,
4084 AllowExplicit != AllowedExplicit::None);
4085 else
4086 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4087 CandidateSet, AllowObjCConversionOnExplicit,
4088 AllowExplicit != AllowedExplicit::None);
4089 }
4090 }
4091 }
4092
4093 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4094
4096 switch (auto Result =
4097 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4098 case OR_Success:
4099 case OR_Deleted:
4100 // Record the standard conversion we used and the conversion function.
4102 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4103 // C++ [over.ics.user]p1:
4104 // If the user-defined conversion is specified by a
4105 // constructor (12.3.1), the initial standard conversion
4106 // sequence converts the source type to the type required by
4107 // the argument of the constructor.
4108 //
4109 if (isa<InitListExpr>(From)) {
4110 // Initializer lists don't have conversions as such.
4112 User.Before.FromBracedInitList = true;
4113 } else {
4114 if (Best->Conversions[0].isEllipsis())
4115 User.EllipsisConversion = true;
4116 else {
4117 User.Before = Best->Conversions[0].Standard;
4118 User.EllipsisConversion = false;
4119 }
4120 }
4121 User.HadMultipleCandidates = HadMultipleCandidates;
4123 User.FoundConversionFunction = Best->FoundDecl;
4125 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4126 User.After.setAllToTypes(ToType);
4127 return Result;
4128 }
4129 if (CXXConversionDecl *Conversion
4130 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4131
4132 assert(Best->HasFinalConversion);
4133
4134 // C++ [over.ics.user]p1:
4135 //
4136 // [...] If the user-defined conversion is specified by a
4137 // conversion function (12.3.2), the initial standard
4138 // conversion sequence converts the source type to the
4139 // implicit object parameter of the conversion function.
4140 User.Before = Best->Conversions[0].Standard;
4141 User.HadMultipleCandidates = HadMultipleCandidates;
4142 User.ConversionFunction = Conversion;
4143 User.FoundConversionFunction = Best->FoundDecl;
4144 User.EllipsisConversion = false;
4145
4146 // C++ [over.ics.user]p2:
4147 // The second standard conversion sequence converts the
4148 // result of the user-defined conversion to the target type
4149 // for the sequence. Since an implicit conversion sequence
4150 // is an initialization, the special rules for
4151 // initialization by user-defined conversion apply when
4152 // selecting the best user-defined conversion for a
4153 // user-defined conversion sequence (see 13.3.3 and
4154 // 13.3.3.1).
4155 User.After = Best->FinalConversion;
4156 return Result;
4157 }
4158 llvm_unreachable("Not a constructor or conversion function?");
4159
4161 return OR_No_Viable_Function;
4162
4163 case OR_Ambiguous:
4164 return OR_Ambiguous;
4165 }
4166
4167 llvm_unreachable("Invalid OverloadResult!");
4168}
4169
4170bool
4173 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4175 OverloadingResult OvResult =
4176 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4177 CandidateSet, AllowedExplicit::None, false);
4178
4179 if (!(OvResult == OR_Ambiguous ||
4180 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4181 return false;
4182
4183 auto Cands = CandidateSet.CompleteCandidates(
4184 *this,
4186 From);
4187 if (OvResult == OR_Ambiguous)
4188 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4189 << From->getType() << ToType << From->getSourceRange();
4190 else { // OR_No_Viable_Function && !CandidateSet.empty()
4191 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4192 diag::err_typecheck_nonviable_condition_incomplete,
4193 From->getType(), From->getSourceRange()))
4194 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4195 << false << From->getType() << From->getSourceRange() << ToType;
4196 }
4197
4198 CandidateSet.NoteCandidates(
4199 *this, From, Cands);
4200 return true;
4201}
4202
4203// Helper for compareConversionFunctions that gets the FunctionType that the
4204// conversion-operator return value 'points' to, or nullptr.
4205static const FunctionType *
4207 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4208 const PointerType *RetPtrTy =
4209 ConvFuncTy->getReturnType()->getAs<PointerType>();
4210
4211 if (!RetPtrTy)
4212 return nullptr;
4213
4214 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4215}
4216
4217/// Compare the user-defined conversion functions or constructors
4218/// of two user-defined conversion sequences to determine whether any ordering
4219/// is possible.
4222 FunctionDecl *Function2) {
4223 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4224 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4225 if (!Conv1 || !Conv2)
4227
4228 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4230
4231 // Objective-C++:
4232 // If both conversion functions are implicitly-declared conversions from
4233 // a lambda closure type to a function pointer and a block pointer,
4234 // respectively, always prefer the conversion to a function pointer,
4235 // because the function pointer is more lightweight and is more likely
4236 // to keep code working.
4237 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4238 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4239 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4240 if (Block1 != Block2)
4241 return Block1 ? ImplicitConversionSequence::Worse
4243 }
4244
4245 // In order to support multiple calling conventions for the lambda conversion
4246 // operator (such as when the free and member function calling convention is
4247 // different), prefer the 'free' mechanism, followed by the calling-convention
4248 // of operator(). The latter is in place to support the MSVC-like solution of
4249 // defining ALL of the possible conversions in regards to calling-convention.
4250 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4251 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4252
4253 if (Conv1FuncRet && Conv2FuncRet &&
4254 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4255 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4256 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4257
4258 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4259 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4260
4261 CallingConv CallOpCC =
4262 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4264 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4266 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4267
4268 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4269 for (CallingConv CC : PrefOrder) {
4270 if (Conv1CC == CC)
4272 if (Conv2CC == CC)
4274 }
4275 }
4276
4278}
4279
4286
4287/// CompareImplicitConversionSequences - Compare two implicit
4288/// conversion sequences to determine whether one is better than the
4289/// other or if they are indistinguishable (C++ 13.3.3.2).
4292 const ImplicitConversionSequence& ICS1,
4293 const ImplicitConversionSequence& ICS2)
4294{
4295 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4296 // conversion sequences (as defined in 13.3.3.1)
4297 // -- a standard conversion sequence (13.3.3.1.1) is a better
4298 // conversion sequence than a user-defined conversion sequence or
4299 // an ellipsis conversion sequence, and
4300 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4301 // conversion sequence than an ellipsis conversion sequence
4302 // (13.3.3.1.3).
4303 //
4304 // C++0x [over.best.ics]p10:
4305 // For the purpose of ranking implicit conversion sequences as
4306 // described in 13.3.3.2, the ambiguous conversion sequence is
4307 // treated as a user-defined sequence that is indistinguishable
4308 // from any other user-defined conversion sequence.
4309
4310 // String literal to 'char *' conversion has been deprecated in C++03. It has
4311 // been removed from C++11. We still accept this conversion, if it happens at
4312 // the best viable function. Otherwise, this conversion is considered worse
4313 // than ellipsis conversion. Consider this as an extension; this is not in the
4314 // standard. For example:
4315 //
4316 // int &f(...); // #1
4317 // void f(char*); // #2
4318 // void g() { int &r = f("foo"); }
4319 //
4320 // In C++03, we pick #2 as the best viable function.
4321 // In C++11, we pick #1 as the best viable function, because ellipsis
4322 // conversion is better than string-literal to char* conversion (since there
4323 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4324 // convert arguments, #2 would be the best viable function in C++11.
4325 // If the best viable function has this conversion, a warning will be issued
4326 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4327
4328 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4331 // Ill-formedness must not differ
4332 ICS1.isBad() == ICS2.isBad())
4336
4337 if (ICS1.getKindRank() < ICS2.getKindRank())
4339 if (ICS2.getKindRank() < ICS1.getKindRank())
4341
4342 // The following checks require both conversion sequences to be of
4343 // the same kind.
4344 if (ICS1.getKind() != ICS2.getKind())
4346
4349
4350 // Two implicit conversion sequences of the same form are
4351 // indistinguishable conversion sequences unless one of the
4352 // following rules apply: (C++ 13.3.3.2p3):
4353
4354 // List-initialization sequence L1 is a better conversion sequence than
4355 // list-initialization sequence L2 if:
4356 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4357 // if not that,
4358 // — L1 and L2 convert to arrays of the same element type, and either the
4359 // number of elements n_1 initialized by L1 is less than the number of
4360 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4361 // an array of unknown bound and L1 does not,
4362 // even if one of the other rules in this paragraph would otherwise apply.
4363 if (!ICS1.isBad()) {
4364 bool StdInit1 = false, StdInit2 = false;
4367 nullptr);
4370 nullptr);
4371 if (StdInit1 != StdInit2)
4372 return StdInit1 ? ImplicitConversionSequence::Better
4374
4377 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4379 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4381 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4382 CAT2->getElementType())) {
4383 // Both to arrays of the same element type
4384 if (CAT1->getSize() != CAT2->getSize())
4385 // Different sized, the smaller wins
4386 return CAT1->getSize().ult(CAT2->getSize())
4391 // One is incomplete, it loses
4395 }
4396 }
4397 }
4398
4399 if (ICS1.isStandard())
4400 // Standard conversion sequence S1 is a better conversion sequence than
4401 // standard conversion sequence S2 if [...]
4402 Result = CompareStandardConversionSequences(S, Loc,
4403 ICS1.Standard, ICS2.Standard);
4404 else if (ICS1.isUserDefined()) {
4405 // With lazy template loading, it is possible to find non-canonical
4406 // FunctionDecls, depending on when redecl chains are completed. Make sure
4407 // to compare the canonical decls of conversion functions. This avoids
4408 // ambiguity problems for templated conversion operators.
4409 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4410 if (ConvFunc1)
4411 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4412 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4413 if (ConvFunc2)
4414 ConvFunc2 = ConvFunc2->getCanonicalDecl();
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).
4421 if (ConvFunc1 == ConvFunc2)
4422 Result = CompareStandardConversionSequences(S, Loc,
4423 ICS1.UserDefined.After,
4424 ICS2.UserDefined.After);
4425 else
4426 Result = compareConversionFunctions(S,
4429 }
4430
4431 return Result;
4432}
4433
4434// Per 13.3.3.2p3, compare the given standard conversion sequences to
4435// determine if one is a proper subset of the other.
4438 const StandardConversionSequence& SCS1,
4439 const StandardConversionSequence& SCS2) {
4442
4443 // the identity conversion sequence is considered to be a subsequence of
4444 // any non-identity conversion sequence
4445 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4447 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4449
4450 if (SCS1.Second != SCS2.Second) {
4451 if (SCS1.Second == ICK_Identity)
4453 else if (SCS2.Second == ICK_Identity)
4455 else
4457 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4459
4460 if (SCS1.Third == SCS2.Third) {
4461 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4463 }
4464
4465 if (SCS1.Third == ICK_Identity)
4466 return Result == ImplicitConversionSequence::Worse
4469
4470 if (SCS2.Third == ICK_Identity)
4471 return Result == ImplicitConversionSequence::Better
4474
4476}
4477
4478/// Determine whether one of the given reference bindings is better
4479/// than the other based on what kind of bindings they are.
4480static bool
4482 const StandardConversionSequence &SCS2) {
4483 // C++0x [over.ics.rank]p3b4:
4484 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4485 // implicit object parameter of a non-static member function declared
4486 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4487 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4488 // lvalue reference to a function lvalue and S2 binds an rvalue
4489 // reference*.
4490 //
4491 // FIXME: Rvalue references. We're going rogue with the above edits,
4492 // because the semantics in the current C++0x working paper (N3225 at the
4493 // time of this writing) break the standard definition of std::forward
4494 // and std::reference_wrapper when dealing with references to functions.
4495 // Proposed wording changes submitted to CWG for consideration.
4498 return false;
4499
4500 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4501 SCS2.IsLvalueReference) ||
4504}
4505
4511
4512/// Returns kind of fixed enum promotion the \a SCS uses.
4513static FixedEnumPromotion
4515
4516 if (SCS.Second != ICK_Integral_Promotion)
4518
4519 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4520 if (!Enum)
4522
4523 if (!Enum->isFixed())
4525
4526 QualType UnderlyingType = Enum->getIntegerType();
4527 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4529
4531}
4532
4533/// CompareStandardConversionSequences - Compare two standard
4534/// conversion sequences to determine whether one is better than the
4535/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4538 const StandardConversionSequence& SCS1,
4539 const StandardConversionSequence& SCS2)
4540{
4541 // Standard conversion sequence S1 is a better conversion sequence
4542 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4543
4544 // -- S1 is a proper subsequence of S2 (comparing the conversion
4545 // sequences in the canonical form defined by 13.3.3.1.1,
4546 // excluding any Lvalue Transformation; the identity conversion
4547 // sequence is considered to be a subsequence of any
4548 // non-identity conversion sequence) or, if not that,
4551 return CK;
4552
4553 // -- the rank of S1 is better than the rank of S2 (by the rules
4554 // defined below), or, if not that,
4555 ImplicitConversionRank Rank1 = SCS1.getRank();
4556 ImplicitConversionRank Rank2 = SCS2.getRank();
4557 if (Rank1 < Rank2)
4559 else if (Rank2 < Rank1)
4561
4562 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4563 // are indistinguishable unless one of the following rules
4564 // applies:
4565
4566 // A conversion that is not a conversion of a pointer, or
4567 // pointer to member, to bool is better than another conversion
4568 // that is such a conversion.
4570 return SCS2.isPointerConversionToBool()
4573
4574 // C++14 [over.ics.rank]p4b2:
4575 // This is retroactively applied to C++11 by CWG 1601.
4576 //
4577 // A conversion that promotes an enumeration whose underlying type is fixed
4578 // to its underlying type is better than one that promotes to the promoted
4579 // underlying type, if the two are different.
4582 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4583 FEP1 != FEP2)
4587
4588 // C++ [over.ics.rank]p4b2:
4589 //
4590 // If class B is derived directly or indirectly from class A,
4591 // conversion of B* to A* is better than conversion of B* to
4592 // void*, and conversion of A* to void* is better than conversion
4593 // of B* to void*.
4594 bool SCS1ConvertsToVoid
4596 bool SCS2ConvertsToVoid
4598 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4599 // Exactly one of the conversion sequences is a conversion to
4600 // a void pointer; it's the worse conversion.
4601 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4603 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4604 // Neither conversion sequence converts to a void pointer; compare
4605 // their derived-to-base conversions.
4607 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4608 return DerivedCK;
4609 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4610 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4611 // Both conversion sequences are conversions to void
4612 // pointers. Compare the source types to determine if there's an
4613 // inheritance relationship in their sources.
4614 QualType FromType1 = SCS1.getFromType();
4615 QualType FromType2 = SCS2.getFromType();
4616
4617 // Adjust the types we're converting from via the array-to-pointer
4618 // conversion, if we need to.
4619 if (SCS1.First == ICK_Array_To_Pointer)
4620 FromType1 = S.Context.getArrayDecayedType(FromType1);
4621 if (SCS2.First == ICK_Array_To_Pointer)
4622 FromType2 = S.Context.getArrayDecayedType(FromType2);
4623
4624 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4625 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4626
4627 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4629 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4631
4632 // Objective-C++: If one interface is more specific than the
4633 // other, it is the better one.
4634 const ObjCObjectPointerType* FromObjCPtr1
4635 = FromType1->getAs<ObjCObjectPointerType>();
4636 const ObjCObjectPointerType* FromObjCPtr2
4637 = FromType2->getAs<ObjCObjectPointerType>();
4638 if (FromObjCPtr1 && FromObjCPtr2) {
4639 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4640 FromObjCPtr2);
4641 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4642 FromObjCPtr1);
4643 if (AssignLeft != AssignRight) {
4644 return AssignLeft? ImplicitConversionSequence::Better
4646 }
4647 }
4648 }
4649
4650 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4651 // Check for a better reference binding based on the kind of bindings.
4652 if (isBetterReferenceBindingKind(SCS1, SCS2))
4654 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4656 }
4657
4658 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4659 // bullet 3).
4661 = CompareQualificationConversions(S, SCS1, SCS2))
4662 return QualCK;
4663
4664 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4665 // C++ [over.ics.rank]p3b4:
4666 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4667 // which the references refer are the same type except for
4668 // top-level cv-qualifiers, and the type to which the reference
4669 // initialized by S2 refers is more cv-qualified than the type
4670 // to which the reference initialized by S1 refers.
4671 QualType T1 = SCS1.getToType(2);
4672 QualType T2 = SCS2.getToType(2);
4673 T1 = S.Context.getCanonicalType(T1);
4674 T2 = S.Context.getCanonicalType(T2);
4675 Qualifiers T1Quals, T2Quals;
4676 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4677 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4678 if (UnqualT1 == UnqualT2) {
4679 // Objective-C++ ARC: If the references refer to objects with different
4680 // lifetimes, prefer bindings that don't change lifetime.
4686 }
4687
4688 // If the type is an array type, promote the element qualifiers to the
4689 // type for comparison.
4690 if (isa<ArrayType>(T1) && T1Quals)
4691 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4692 if (isa<ArrayType>(T2) && T2Quals)
4693 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4694 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4696 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4698 }
4699 }
4700
4701 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4702 // floating-to-integral conversion if the integral conversion
4703 // is between types of the same size.
4704 // For example:
4705 // void f(float);
4706 // void f(int);
4707 // int main {
4708 // long a;
4709 // f(a);
4710 // }
4711 // Here, MSVC will call f(int) instead of generating a compile error
4712 // as clang will do in standard mode.
4713 if (S.getLangOpts().MSVCCompat &&
4716 SCS2.Second == ICK_Floating_Integral &&
4717 S.Context.getTypeSize(SCS1.getFromType()) ==
4718 S.Context.getTypeSize(SCS1.getToType(2)))
4720
4721 // Prefer a compatible vector conversion over a lax vector conversion
4722 // For example:
4723 //
4724 // typedef float __v4sf __attribute__((__vector_size__(16)));
4725 // void f(vector float);
4726 // void f(vector signed int);
4727 // int main() {
4728 // __v4sf a;
4729 // f(a);
4730 // }
4731 // Here, we'd like to choose f(vector float) and not
4732 // report an ambiguous call error
4733 if (SCS1.Second == ICK_Vector_Conversion &&
4734 SCS2.Second == ICK_Vector_Conversion) {
4735 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4736 SCS1.getFromType(), SCS1.getToType(2));
4737 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4738 SCS2.getFromType(), SCS2.getToType(2));
4739
4740 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4741 return SCS1IsCompatibleVectorConversion
4744 }
4745
4746 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4748 bool SCS1IsCompatibleSVEVectorConversion =
4749 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4750 bool SCS2IsCompatibleSVEVectorConversion =
4751 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4752
4753 if (SCS1IsCompatibleSVEVectorConversion !=
4754 SCS2IsCompatibleSVEVectorConversion)
4755 return SCS1IsCompatibleSVEVectorConversion
4758 }
4759
4760 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4762 bool SCS1IsCompatibleRVVVectorConversion =
4764 bool SCS2IsCompatibleRVVVectorConversion =
4766
4767 if (SCS1IsCompatibleRVVVectorConversion !=
4768 SCS2IsCompatibleRVVVectorConversion)
4769 return SCS1IsCompatibleRVVVectorConversion
4772 }
4774}
4775
4776/// CompareQualificationConversions - Compares two standard conversion
4777/// sequences to determine whether they can be ranked based on their
4778/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4781 const StandardConversionSequence& SCS1,
4782 const StandardConversionSequence& SCS2) {
4783 // C++ [over.ics.rank]p3:
4784 // -- S1 and S2 differ only in their qualification conversion and
4785 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4786 // [C++98]
4787 // [...] and the cv-qualification signature of type T1 is a proper subset
4788 // of the cv-qualification signature of type T2, and S1 is not the
4789 // deprecated string literal array-to-pointer conversion (4.2).
4790 // [C++2a]
4791 // [...] where T1 can be converted to T2 by a qualification conversion.
4792 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4793 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4795
4796 // FIXME: the example in the standard doesn't use a qualification
4797 // conversion (!)
4798 QualType T1 = SCS1.getToType(2);
4799 QualType T2 = SCS2.getToType(2);
4800 T1 = S.Context.getCanonicalType(T1);
4801 T2 = S.Context.getCanonicalType(T2);
4802 assert(!T1->isReferenceType() && !T2->isReferenceType());
4803 Qualifiers T1Quals, T2Quals;
4804 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4805 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4806
4807 // If the types are the same, we won't learn anything by unwrapping
4808 // them.
4809 if (UnqualT1 == UnqualT2)
4811
4812 // Don't ever prefer a standard conversion sequence that uses the deprecated
4813 // string literal array to pointer conversion.
4814 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4815 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4816
4817 // Objective-C++ ARC:
4818 // Prefer qualification conversions not involving a change in lifetime
4819 // to qualification conversions that do change lifetime.
4822 CanPick1 = false;
4825 CanPick2 = false;
4826
4827 bool ObjCLifetimeConversion;
4828 if (CanPick1 &&
4829 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4830 CanPick1 = false;
4831 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4832 // directions, so we can't short-cut this second check in general.
4833 if (CanPick2 &&
4834 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4835 CanPick2 = false;
4836
4837 if (CanPick1 != CanPick2)
4838 return CanPick1 ? ImplicitConversionSequence::Better
4841}
4842
4843/// CompareDerivedToBaseConversions - Compares two standard conversion
4844/// sequences to determine whether they can be ranked based on their
4845/// various kinds of derived-to-base conversions (C++
4846/// [over.ics.rank]p4b3). As part of these checks, we also look at
4847/// conversions between Objective-C interface types.
4850 const StandardConversionSequence& SCS1,
4851 const StandardConversionSequence& SCS2) {
4852 QualType FromType1 = SCS1.getFromType();
4853 QualType ToType1 = SCS1.getToType(1);
4854 QualType FromType2 = SCS2.getFromType();
4855 QualType ToType2 = SCS2.getToType(1);
4856
4857 // Adjust the types we're converting from via the array-to-pointer
4858 // conversion, if we need to.
4859 if (SCS1.First == ICK_Array_To_Pointer)
4860 FromType1 = S.Context.getArrayDecayedType(FromType1);
4861 if (SCS2.First == ICK_Array_To_Pointer)
4862 FromType2 = S.Context.getArrayDecayedType(FromType2);
4863
4864 // Canonicalize all of the types.
4865 FromType1 = S.Context.getCanonicalType(FromType1);
4866 ToType1 = S.Context.getCanonicalType(ToType1);
4867 FromType2 = S.Context.getCanonicalType(FromType2);
4868 ToType2 = S.Context.getCanonicalType(ToType2);
4869
4870 // C++ [over.ics.rank]p4b3:
4871 //
4872 // If class B is derived directly or indirectly from class A and
4873 // class C is derived directly or indirectly from B,
4874 //
4875 // Compare based on pointer conversions.
4876 if (SCS1.Second == ICK_Pointer_Conversion &&
4878 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4879 FromType1->isPointerType() && FromType2->isPointerType() &&
4880 ToType1->isPointerType() && ToType2->isPointerType()) {
4881 QualType FromPointee1 =
4883 QualType ToPointee1 =
4885 QualType FromPointee2 =
4887 QualType ToPointee2 =
4889
4890 // -- conversion of C* to B* is better than conversion of C* to A*,
4891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4892 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4894 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4896 }
4897
4898 // -- conversion of B* to A* is better than conversion of C* to A*,
4899 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4900 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4902 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4904 }
4905 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4907 const ObjCObjectPointerType *FromPtr1
4908 = FromType1->getAs<ObjCObjectPointerType>();
4909 const ObjCObjectPointerType *FromPtr2
4910 = FromType2->getAs<ObjCObjectPointerType>();
4911 const ObjCObjectPointerType *ToPtr1
4912 = ToType1->getAs<ObjCObjectPointerType>();
4913 const ObjCObjectPointerType *ToPtr2
4914 = ToType2->getAs<ObjCObjectPointerType>();
4915
4916 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4917 // Apply the same conversion ranking rules for Objective-C pointer types
4918 // that we do for C++ pointers to class types. However, we employ the
4919 // Objective-C pseudo-subtyping relationship used for assignment of
4920 // Objective-C pointer types.
4921 bool FromAssignLeft
4922 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4923 bool FromAssignRight
4924 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4925 bool ToAssignLeft
4926 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4927 bool ToAssignRight
4928 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4929
4930 // A conversion to an a non-id object pointer type or qualified 'id'
4931 // type is better than a conversion to 'id'.
4932 if (ToPtr1->isObjCIdType() &&
4933 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4935 if (ToPtr2->isObjCIdType() &&
4936 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4938
4939 // A conversion to a non-id object pointer type is better than a
4940 // conversion to a qualified 'id' type
4941 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4943 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4945
4946 // A conversion to an a non-Class object pointer type or qualified 'Class'
4947 // type is better than a conversion to 'Class'.
4948 if (ToPtr1->isObjCClassType() &&
4949 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4951 if (ToPtr2->isObjCClassType() &&
4952 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4954
4955 // A conversion to a non-Class object pointer type is better than a
4956 // conversion to a qualified 'Class' type.
4957 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4959 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4961
4962 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4963 if (S.Context.hasSameType(FromType1, FromType2) &&
4964 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4965 (ToAssignLeft != ToAssignRight)) {
4966 if (FromPtr1->isSpecialized()) {
4967 // "conversion of B<A> * to B * is better than conversion of B * to
4968 // C *.
4969 bool IsFirstSame =
4970 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4971 bool IsSecondSame =
4972 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4973 if (IsFirstSame) {
4974 if (!IsSecondSame)
4976 } else if (IsSecondSame)
4978 }
4979 return ToAssignLeft? ImplicitConversionSequence::Worse
4981 }
4982
4983 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4984 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4985 (FromAssignLeft != FromAssignRight))
4986 return FromAssignLeft? ImplicitConversionSequence::Better
4988 }
4989 }
4990
4991 // Ranking of member-pointer types.
4992 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4993 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4994 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4995 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4996 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4997 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4998 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4999 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5000 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5001 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5002 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5003 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5004 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5005 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5007 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5009 }
5010 // conversion of B::* to C::* is better than conversion of A::* to C::*
5011 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5012 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5014 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5016 }
5017 }
5018
5019 if (SCS1.Second == ICK_Derived_To_Base) {
5020 // -- conversion of C to B is better than conversion of C to A,
5021 // -- binding of an expression of type C to a reference of type
5022 // B& is better than binding an expression of type C to a
5023 // reference of type A&,
5024 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5025 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5026 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5028 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5030 }
5031
5032 // -- conversion of B to A is better than conversion of C to A.
5033 // -- binding of an expression of type B to a reference of type
5034 // A& is better than binding an expression of type C to a
5035 // reference of type A&,
5036 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5037 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5038 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5040 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5042 }
5043 }
5044
5046}
5047
5049 if (!T.getQualifiers().hasUnaligned())
5050 return T;
5051
5052 Qualifiers Q;
5053 T = Ctx.getUnqualifiedArrayType(T, Q);
5054 Q.removeUnaligned();
5055 return Ctx.getQualifiedType(T, Q);
5056}
5057
5060 QualType OrigT1, QualType OrigT2,
5061 ReferenceConversions *ConvOut) {
5062 assert(!OrigT1->isReferenceType() &&
5063 "T1 must be the pointee type of the reference type");
5064 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5065
5066 QualType T1 = Context.getCanonicalType(OrigT1);
5067 QualType T2 = Context.getCanonicalType(OrigT2);
5068 Qualifiers T1Quals, T2Quals;
5069 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5070 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5071
5072 ReferenceConversions ConvTmp;
5073 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5074 Conv = ReferenceConversions();
5075
5076 // C++2a [dcl.init.ref]p4:
5077 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5078 // reference-related to "cv2 T2" if T1 is similar to T2, or
5079 // T1 is a base class of T2.
5080 // "cv1 T1" is reference-compatible with "cv2 T2" if
5081 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5082 // "pointer to cv1 T1" via a standard conversion sequence.
5083
5084 // Check for standard conversions we can apply to pointers: derived-to-base
5085 // conversions, ObjC pointer conversions, and function pointer conversions.
5086 // (Qualification conversions are checked last.)
5087 if (UnqualT1 == UnqualT2) {
5088 // Nothing to do.
5089 } else if (isCompleteType(Loc, OrigT2) &&
5090 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5091 Conv |= ReferenceConversions::DerivedToBase;
5092 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5093 UnqualT2->isObjCObjectOrInterfaceType() &&
5094 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5095 Conv |= ReferenceConversions::ObjC;
5096 else if (UnqualT2->isFunctionType() &&
5097 IsFunctionConversion(UnqualT2, UnqualT1)) {
5098 Conv |= ReferenceConversions::Function;
5099 // No need to check qualifiers; function types don't have them.
5100 return Ref_Compatible;
5101 }
5102 bool ConvertedReferent = Conv != 0;
5103
5104 // We can have a qualification conversion. Compute whether the types are
5105 // similar at the same time.
5106 bool PreviousToQualsIncludeConst = true;
5107 bool TopLevel = true;
5108 do {
5109 if (T1 == T2)
5110 break;
5111
5112 // We will need a qualification conversion.
5113 Conv |= ReferenceConversions::Qualification;
5114
5115 // Track whether we performed a qualification conversion anywhere other
5116 // than the top level. This matters for ranking reference bindings in
5117 // overload resolution.
5118 if (!TopLevel)
5119 Conv |= ReferenceConversions::NestedQualification;
5120
5121 // MS compiler ignores __unaligned qualifier for references; do the same.
5122 T1 = withoutUnaligned(Context, T1);
5123 T2 = withoutUnaligned(Context, T2);
5124
5125 // If we find a qualifier mismatch, the types are not reference-compatible,
5126 // but are still be reference-related if they're similar.
5127 bool ObjCLifetimeConversion = false;
5128 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5129 PreviousToQualsIncludeConst,
5130 ObjCLifetimeConversion, getASTContext()))
5131 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5132 ? Ref_Related
5134
5135 // FIXME: Should we track this for any level other than the first?
5136 if (ObjCLifetimeConversion)
5137 Conv |= ReferenceConversions::ObjCLifetime;
5138
5139 TopLevel = false;
5140 } while (Context.UnwrapSimilarTypes(T1, T2));
5141
5142 // At this point, if the types are reference-related, we must either have the
5143 // same inner type (ignoring qualifiers), or must have already worked out how
5144 // to convert the referent.
5145 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5148}
5149
5150/// Look for a user-defined conversion to a value reference-compatible
5151/// with DeclType. Return true if something definite is found.
5152static bool
5154 QualType DeclType, SourceLocation DeclLoc,
5155 Expr *Init, QualType T2, bool AllowRvalues,
5156 bool AllowExplicit) {
5157 assert(T2->isRecordType() && "Can only find conversions of record types.");
5158 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5159 OverloadCandidateSet CandidateSet(
5161 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5162 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5163 NamedDecl *D = *I;
5165 if (isa<UsingShadowDecl>(D))
5166 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5167
5168 FunctionTemplateDecl *ConvTemplate
5169 = dyn_cast<FunctionTemplateDecl>(D);
5170 CXXConversionDecl *Conv;
5171 if (ConvTemplate)
5172 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5173 else
5174 Conv = cast<CXXConversionDecl>(D);
5175
5176 if (AllowRvalues) {
5177 // If we are initializing an rvalue reference, don't permit conversion
5178 // functions that return lvalues.
5179 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5180 const ReferenceType *RefType
5182 if (RefType && !RefType->getPointeeType()->isFunctionType())
5183 continue;
5184 }
5185
5186 if (!ConvTemplate &&
5188 DeclLoc,
5189 Conv->getConversionType()
5194 continue;
5195 } else {
5196 // If the conversion function doesn't return a reference type,
5197 // it can't be considered for this conversion. An rvalue reference
5198 // is only acceptable if its referencee is a function type.
5199
5200 const ReferenceType *RefType =
5202 if (!RefType ||
5203 (!RefType->isLValueReferenceType() &&
5204 !RefType->getPointeeType()->isFunctionType()))
5205 continue;
5206 }
5207
5208 if (ConvTemplate)
5210 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5211 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5212 else
5214 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5215 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5216 }
5217
5218 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5219
5221 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5222 case OR_Success:
5223
5224 assert(Best->HasFinalConversion);
5225
5226 // C++ [over.ics.ref]p1:
5227 //
5228 // [...] If the parameter binds directly to the result of
5229 // applying a conversion function to the argument
5230 // expression, the implicit conversion sequence is a
5231 // user-defined conversion sequence (13.3.3.1.2), with the
5232 // second standard conversion sequence either an identity
5233 // conversion or, if the conversion function returns an
5234 // entity of a type that is a derived class of the parameter
5235 // type, a derived-to-base Conversion.
5236 if (!Best->FinalConversion.DirectBinding)
5237 return false;
5238
5239 ICS.setUserDefined();
5240 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5241 ICS.UserDefined.After = Best->FinalConversion;
5242 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5243 ICS.UserDefined.ConversionFunction = Best->Function;
5244 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5245 ICS.UserDefined.EllipsisConversion = false;
5246 assert(ICS.UserDefined.After.ReferenceBinding &&
5248 "Expected a direct reference binding!");
5249 return true;
5250
5251 case OR_Ambiguous:
5252 ICS.setAmbiguous();
5253 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5254 Cand != CandidateSet.end(); ++Cand)
5255 if (Cand->Best)
5256 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5257 return true;
5258
5260 case OR_Deleted:
5261 // There was no suitable conversion, or we found a deleted
5262 // conversion; continue with other checks.
5263 return false;
5264 }
5265
5266 llvm_unreachable("Invalid OverloadResult!");
5267}
5268
5269/// Compute an implicit conversion sequence for reference
5270/// initialization.
5271static ImplicitConversionSequence
5273 SourceLocation DeclLoc,
5274 bool SuppressUserConversions,
5275 bool AllowExplicit) {
5276 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5277
5278 // Most paths end in a failed conversion.
5281
5282 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5283 QualType T2 = Init->getType();
5284
5285 // If the initializer is the address of an overloaded function, try
5286 // to resolve the overloaded function. If all goes well, T2 is the
5287 // type of the resulting function.
5288 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5291 false, Found))
5292 T2 = Fn->getType();
5293 }
5294
5295 // Compute some basic properties of the types and the initializer.
5296 bool isRValRef = DeclType->isRValueReferenceType();
5297 Expr::Classification InitCategory = Init->Classify(S.Context);
5298
5300 Sema::ReferenceCompareResult RefRelationship =
5301 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5302
5303 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5304 ICS.setStandard();
5306 // FIXME: A reference binding can be a function conversion too. We should
5307 // consider that when ordering reference-to-function bindings.
5308 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5310 : (RefConv & Sema::ReferenceConversions::ObjC)
5312 : ICK_Identity;
5314 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5315 // a reference binding that performs a non-top-level qualification
5316 // conversion as a qualification conversion, not as an identity conversion.
5317 ICS.Standard.Third = (RefConv &
5318 Sema::ReferenceConversions::NestedQualification)
5320 : ICK_Identity;
5321 ICS.Standard.setFromType(T2);
5322 ICS.Standard.setToType(0, T2);
5323 ICS.Standard.setToType(1, T1);
5324 ICS.Standard.setToType(2, T1);
5325 ICS.Standard.ReferenceBinding = true;
5326 ICS.Standard.DirectBinding = BindsDirectly;
5327 ICS.Standard.IsLvalueReference = !isRValRef;
5329 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5332 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5333 ICS.Standard.FromBracedInitList = false;
5334 ICS.Standard.CopyConstructor = nullptr;
5336 };
5337
5338 // C++0x [dcl.init.ref]p5:
5339 // A reference to type "cv1 T1" is initialized by an expression
5340 // of type "cv2 T2" as follows:
5341
5342 // -- If reference is an lvalue reference and the initializer expression
5343 if (!isRValRef) {
5344 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5345 // reference-compatible with "cv2 T2," or
5346 //
5347 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5348 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5349 // C++ [over.ics.ref]p1:
5350 // When a parameter of reference type binds directly (8.5.3)
5351 // to an argument expression, the implicit conversion sequence
5352 // is the identity conversion, unless the argument expression
5353 // has a type that is a derived class of the parameter type,
5354 // in which case the implicit conversion sequence is a
5355 // derived-to-base Conversion (13.3.3.1).
5356 SetAsReferenceBinding(/*BindsDirectly=*/true);
5357
5358 // Nothing more to do: the inaccessibility/ambiguity check for
5359 // derived-to-base conversions is suppressed when we're
5360 // computing the implicit conversion sequence (C++
5361 // [over.best.ics]p2).
5362 return ICS;
5363 }
5364
5365 // -- has a class type (i.e., T2 is a class type), where T1 is
5366 // not reference-related to T2, and can be implicitly
5367 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5368 // is reference-compatible with "cv3 T3" 92) (this
5369 // conversion is selected by enumerating the applicable
5370 // conversion functions (13.3.1.6) and choosing the best
5371 // one through overload resolution (13.3)),
5372 if (!SuppressUserConversions && T2->isRecordType() &&
5373 S.isCompleteType(DeclLoc, T2) &&
5374 RefRelationship == Sema::Ref_Incompatible) {
5375 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5376 Init, T2, /*AllowRvalues=*/false,
5377 AllowExplicit))
5378 return ICS;
5379 }
5380 }
5381
5382 // -- Otherwise, the reference shall be an lvalue reference to a
5383 // non-volatile const type (i.e., cv1 shall be const), or the reference
5384 // shall be an rvalue reference.
5385 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5386 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5388 return ICS;
5389 }
5390
5391 // -- If the initializer expression
5392 //
5393 // -- is an xvalue, class prvalue, array prvalue or function
5394 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5395 if (RefRelationship == Sema::Ref_Compatible &&
5396 (InitCategory.isXValue() ||
5397 (InitCategory.isPRValue() &&
5398 (T2->isRecordType() || T2->isArrayType())) ||
5399 (InitCategory.isLValue() && T2->isFunctionType()))) {
5400 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5401 // binding unless we're binding to a class prvalue.
5402 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5403 // allow the use of rvalue references in C++98/03 for the benefit of
5404 // standard library implementors; therefore, we need the xvalue check here.
5405 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5406 !(InitCategory.isPRValue() || T2->isRecordType()));
5407 return ICS;
5408 }
5409
5410 // -- has a class type (i.e., T2 is a class type), where T1 is not
5411 // reference-related to T2, and can be implicitly converted to
5412 // an xvalue, class prvalue, or function lvalue of type
5413 // "cv3 T3", where "cv1 T1" is reference-compatible with
5414 // "cv3 T3",
5415 //
5416 // then the reference is bound to the value of the initializer
5417 // expression in the first case and to the result of the conversion
5418 // in the second case (or, in either case, to an appropriate base
5419 // class subobject).
5420 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5421 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5422 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5423 Init, T2, /*AllowRvalues=*/true,
5424 AllowExplicit)) {
5425 // In the second case, if the reference is an rvalue reference
5426 // and the second standard conversion sequence of the
5427 // user-defined conversion sequence includes an lvalue-to-rvalue
5428 // conversion, the program is ill-formed.
5429 if (ICS.isUserDefined() && isRValRef &&
5432
5433 return ICS;
5434 }
5435
5436 // A temporary of function type cannot be created; don't even try.
5437 if (T1->isFunctionType())
5438 return ICS;
5439
5440 // -- Otherwise, a temporary of type "cv1 T1" is created and
5441 // initialized from the initializer expression using the
5442 // rules for a non-reference copy initialization (8.5). The
5443 // reference is then bound to the temporary. If T1 is
5444 // reference-related to T2, cv1 must be the same
5445 // cv-qualification as, or greater cv-qualification than,
5446 // cv2; otherwise, the program is ill-formed.
5447 if (RefRelationship == Sema::Ref_Related) {
5448 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5449 // we would be reference-compatible or reference-compatible with
5450 // added qualification. But that wasn't the case, so the reference
5451 // initialization fails.
5452 //
5453 // Note that we only want to check address spaces and cvr-qualifiers here.
5454 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5455 Qualifiers T1Quals = T1.getQualifiers();
5456 Qualifiers T2Quals = T2.getQualifiers();
5457 T1Quals.removeObjCGCAttr();
5458 T1Quals.removeObjCLifetime();
5459 T2Quals.removeObjCGCAttr();
5460 T2Quals.removeObjCLifetime();
5461 // MS compiler ignores __unaligned qualifier for references; do the same.
5462 T1Quals.removeUnaligned();
5463 T2Quals.removeUnaligned();
5464 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5465 return ICS;
5466 }
5467
5468 // If at least one of the types is a class type, the types are not
5469 // related, and we aren't allowed any user conversions, the
5470 // reference binding fails. This case is important for breaking
5471 // recursion, since TryImplicitConversion below will attempt to
5472 // create a temporary through the use of a copy constructor.
5473 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5474 (T1->isRecordType() || T2->isRecordType()))
5475 return ICS;
5476
5477 // If T1 is reference-related to T2 and the reference is an rvalue
5478 // reference, the initializer expression shall not be an lvalue.
5479 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5480 Init->Classify(S.Context).isLValue()) {
5482 return ICS;
5483 }
5484
5485 // C++ [over.ics.ref]p2:
5486 // When a parameter of reference type is not bound directly to
5487 // an argument expression, the conversion sequence is the one
5488 // required to convert the argument expression to the
5489 // underlying type of the reference according to
5490 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5491 // to copy-initializing a temporary of the underlying type with
5492 // the argument expression. Any difference in top-level
5493 // cv-qualification is subsumed by the initialization itself
5494 // and does not constitute a conversion.
5495 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5496 AllowedExplicit::None,
5497 /*InOverloadResolution=*/false,
5498 /*CStyle=*/false,
5499 /*AllowObjCWritebackConversion=*/false,
5500 /*AllowObjCConversionOnExplicit=*/false);
5501
5502 // Of course, that's still a reference binding.
5503 if (ICS.isStandard()) {
5504 ICS.Standard.ReferenceBinding = true;
5505 ICS.Standard.IsLvalueReference = !isRValRef;
5506 ICS.Standard.BindsToFunctionLvalue = false;
5507 ICS.Standard.BindsToRvalue = true;
5510 } else if (ICS.isUserDefined()) {
5511 const ReferenceType *LValRefType =
5514
5515 // C++ [over.ics.ref]p3:
5516 // Except for an implicit object parameter, for which see 13.3.1, a
5517 // standard conversion sequence cannot be formed if it requires [...]
5518 // binding an rvalue reference to an lvalue other than a function
5519 // lvalue.
5520 // Note that the function case is not possible here.
5521 if (isRValRef && LValRefType) {
5523 return ICS;
5524 }
5525
5527 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5529 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5533 }
5534
5535 return ICS;
5536}
5537
5538static ImplicitConversionSequence
5539TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5540 bool SuppressUserConversions,
5541 bool InOverloadResolution,
5542 bool AllowObjCWritebackConversion,
5543 bool AllowExplicit = false);
5544
5545/// TryListConversion - Try to copy-initialize a value of type ToType from the
5546/// initializer list From.
5547static ImplicitConversionSequence
5549 bool SuppressUserConversions,
5550 bool InOverloadResolution,
5551 bool AllowObjCWritebackConversion) {
5552 // C++11 [over.ics.list]p1:
5553 // When an argument is an initializer list, it is not an expression and
5554 // special rules apply for converting it to a parameter type.
5555
5557 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5558
5559 // We need a complete type for what follows. With one C++20 exception,
5560 // incomplete types can never be initialized from init lists.
5561 QualType InitTy = ToType;
5562 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5563 if (AT && S.getLangOpts().CPlusPlus20)
5564 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5565 // C++20 allows list initialization of an incomplete array type.
5566 InitTy = IAT->getElementType();
5567 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5568 return Result;
5569
5570 // C++20 [over.ics.list]/2:
5571 // If the initializer list is a designated-initializer-list, a conversion
5572 // is only possible if the parameter has an aggregate type
5573 //
5574 // FIXME: The exception for reference initialization here is not part of the
5575 // language rules, but follow other compilers in adding it as a tentative DR
5576 // resolution.
5577 bool IsDesignatedInit = From->hasDesignatedInit();
5578 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5579 IsDesignatedInit)
5580 return Result;
5581
5582 // Per DR1467 and DR2137:
5583 // If the parameter type is an aggregate class X and the initializer list
5584 // has a single element of type cv U, where U is X or a class derived from
5585 // X, the implicit conversion sequence is the one required to convert the
5586 // element to the parameter type.
5587 //
5588 // Otherwise, if the parameter type is a character array [... ]
5589 // and the initializer list has a single element that is an
5590 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5591 // implicit conversion sequence is the identity conversion.
5592 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5593 if (ToType->isRecordType() && ToType->isAggregateType()) {
5594 QualType InitType = From->getInit(0)->getType();
5595 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5596 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5597 return TryCopyInitialization(S, From->getInit(0), ToType,
5598 SuppressUserConversions,
5599 InOverloadResolution,
5600 AllowObjCWritebackConversion);
5601 }
5602
5603 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5604 InitializedEntity Entity =
5606 /*Consumed=*/false);
5607 if (S.CanPerformCopyInitialization(Entity, From)) {
5608 Result.setStandard();
5609 Result.Standard.setAsIdentityConversion();
5610 Result.Standard.setFromType(ToType);
5611 Result.Standard.setAllToTypes(ToType);
5612 return Result;
5613 }
5614 }
5615 }
5616
5617 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5618 // C++11 [over.ics.list]p2:
5619 // If the parameter type is std::initializer_list<X> or "array of X" and
5620 // all the elements can be implicitly converted to X, the implicit
5621 // conversion sequence is the worst conversion necessary to convert an
5622 // element of the list to X.
5623 //
5624 // C++14 [over.ics.list]p3:
5625 // Otherwise, if the parameter type is "array of N X", if the initializer
5626 // list has exactly N elements or if it has fewer than N elements and X is
5627 // default-constructible, and if all the elements of the initializer list
5628 // can be implicitly converted to X, the implicit conversion sequence is
5629 // the worst conversion necessary to convert an element of the list to X.
5630 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5631 unsigned e = From->getNumInits();
5634 QualType());
5635 QualType ContTy = ToType;
5636 bool IsUnbounded = false;
5637 if (AT) {
5638 InitTy = AT->getElementType();
5639 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5640 if (CT->getSize().ult(e)) {
5641 // Too many inits, fatally bad
5643 ToType);
5644 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5645 return Result;
5646 }
5647 if (CT->getSize().ugt(e)) {
5648 // Need an init from empty {}, is there one?
5649 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5650 From->getEndLoc());
5651 EmptyList.setType(S.Context.VoidTy);
5652 DfltElt = TryListConversion(
5653 S, &EmptyList, InitTy, SuppressUserConversions,
5654 InOverloadResolution, AllowObjCWritebackConversion);
5655 if (DfltElt.isBad()) {
5656 // No {} init, fatally bad
5658 ToType);
5659 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5660 return Result;
5661 }
5662 }
5663 } else {
5664 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5665 IsUnbounded = true;
5666 if (!e) {
5667 // Cannot convert to zero-sized.
5669 ToType);
5670 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5671 return Result;
5672 }
5673 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5674 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5676 }
5677 }
5678
5679 Result.setStandard();
5680 Result.Standard.setAsIdentityConversion();
5681 Result.Standard.setFromType(InitTy);
5682 Result.Standard.setAllToTypes(InitTy);
5683 for (unsigned i = 0; i < e; ++i) {
5684 Expr *Init = From->getInit(i);
5686 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5687 AllowObjCWritebackConversion);
5688
5689 // Keep the worse conversion seen so far.
5690 // FIXME: Sequences are not totally ordered, so 'worse' can be
5691 // ambiguous. CWG has been informed.
5693 Result) ==
5695 Result = ICS;
5696 // Bail as soon as we find something unconvertible.
5697 if (Result.isBad()) {
5698 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5699 return Result;
5700 }
5701 }
5702 }
5703
5704 // If we needed any implicit {} initialization, compare that now.
5705 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5706 // has been informed that this might not be the best thing.
5707 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5708 S, From->getEndLoc(), DfltElt, Result) ==
5710 Result = DfltElt;
5711 // Record the type being initialized so that we may compare sequences
5712 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5713 return Result;
5714 }
5715
5716 // C++14 [over.ics.list]p4:
5717 // C++11 [over.ics.list]p3:
5718 // Otherwise, if the parameter is a non-aggregate class X and overload
5719 // resolution chooses a single best constructor [...] the implicit
5720 // conversion sequence is a user-defined conversion sequence. If multiple
5721 // constructors are viable but none is better than the others, the
5722 // implicit conversion sequence is a user-defined conversion sequence.
5723 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5724 // This function can deal with initializer lists.
5725 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5726 AllowedExplicit::None,
5727 InOverloadResolution, /*CStyle=*/false,
5728 AllowObjCWritebackConversion,
5729 /*AllowObjCConversionOnExplicit=*/false);
5730 }
5731
5732 // C++14 [over.ics.list]p5:
5733 // C++11 [over.ics.list]p4:
5734 // Otherwise, if the parameter has an aggregate type which can be
5735 // initialized from the initializer list [...] the implicit conversion
5736 // sequence is a user-defined conversion sequence.
5737 if (ToType->isAggregateType()) {
5738 // Type is an aggregate, argument is an init list. At this point it comes
5739 // down to checking whether the initialization works.
5740 // FIXME: Find out whether this parameter is consumed or not.
5741 InitializedEntity Entity =
5743 /*Consumed=*/false);
5745 From)) {
5746 Result.setUserDefined();
5747 Result.UserDefined.Before.setAsIdentityConversion();
5748 // Initializer lists don't have a type.
5749 Result.UserDefined.Before.setFromType(QualType());
5750 Result.UserDefined.Before.setAllToTypes(QualType());
5751
5752 Result.UserDefined.After.setAsIdentityConversion();
5753 Result.UserDefined.After.setFromType(ToType);
5754 Result.UserDefined.After.setAllToTypes(ToType);
5755 Result.UserDefined.ConversionFunction = nullptr;
5756 }
5757 return Result;
5758 }
5759
5760 // C++14 [over.ics.list]p6:
5761 // C++11 [over.ics.list]p5:
5762 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5763 if (ToType->isReferenceType()) {
5764 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5765 // mention initializer lists in any way. So we go by what list-
5766 // initialization would do and try to extrapolate from that.
5767
5768 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5769
5770 // If the initializer list has a single element that is reference-related
5771 // to the parameter type, we initialize the reference from that.
5772 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5773 Expr *Init = From->getInit(0);
5774
5775 QualType T2 = Init->getType();
5776
5777 // If the initializer is the address of an overloaded function, try
5778 // to resolve the overloaded function. If all goes well, T2 is the
5779 // type of the resulting function.
5780 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5783 Init, ToType, false, Found))
5784 T2 = Fn->getType();
5785 }
5786
5787 // Compute some basic properties of the types and the initializer.
5788 Sema::ReferenceCompareResult RefRelationship =
5789 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5790
5791 if (RefRelationship >= Sema::Ref_Related) {
5792 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5793 SuppressUserConversions,
5794 /*AllowExplicit=*/false);
5795 }
5796 }
5797
5798 // Otherwise, we bind the reference to a temporary created from the
5799 // initializer list.
5800 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5801 InOverloadResolution,
5802 AllowObjCWritebackConversion);
5803 if (Result.isFailure())
5804 return Result;
5805 assert(!Result.isEllipsis() &&
5806 "Sub-initialization cannot result in ellipsis conversion.");
5807
5808 // Can we even bind to a temporary?
5809 if (ToType->isRValueReferenceType() ||
5810 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5811 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5812 Result.UserDefined.After;
5813 SCS.ReferenceBinding = true;
5815 SCS.BindsToRvalue = true;
5816 SCS.BindsToFunctionLvalue = false;
5819 SCS.FromBracedInitList = false;
5820
5821 } else
5823 From, ToType);
5824 return Result;
5825 }
5826
5827 // C++14 [over.ics.list]p7:
5828 // C++11 [over.ics.list]p6:
5829 // Otherwise, if the parameter type is not a class:
5830 if (!ToType->isRecordType()) {
5831 // - if the initializer list has one element that is not itself an
5832 // initializer list, the implicit conversion sequence is the one
5833 // required to convert the element to the parameter type.
5834 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5835 // single integer.
5836 unsigned NumInits = From->getNumInits();
5837 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5838 !isa<EmbedExpr>(From->getInit(0))) {
5839 Result = TryCopyInitialization(
5840 S, From->getInit(0), ToType, SuppressUserConversions,
5841 InOverloadResolution, AllowObjCWritebackConversion);
5842 if (Result.isStandard())
5843 Result.Standard.FromBracedInitList = true;
5844 }
5845 // - if the initializer list has no elements, the implicit conversion
5846 // sequence is the identity conversion.
5847 else if (NumInits == 0) {
5848 Result.setStandard();
5849 Result.Standard.setAsIdentityConversion();
5850 Result.Standard.setFromType(ToType);
5851 Result.Standard.setAllToTypes(ToType);
5852 }
5853 return Result;
5854 }
5855
5856 // C++14 [over.ics.list]p8:
5857 // C++11 [over.ics.list]p7:
5858 // In all cases other than those enumerated above, no conversion is possible
5859 return Result;
5860}
5861
5862/// TryCopyInitialization - Try to copy-initialize a value of type
5863/// ToType from the expression From. Return the implicit conversion
5864/// sequence required to pass this argument, which may be a bad
5865/// conversion sequence (meaning that the argument cannot be passed to
5866/// a parameter of this type). If @p SuppressUserConversions, then we
5867/// do not permit any user-defined conversion sequences.
5868static ImplicitConversionSequence
5870 bool SuppressUserConversions,
5871 bool InOverloadResolution,
5872 bool AllowObjCWritebackConversion,
5873 bool AllowExplicit) {
5874 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5875 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5876 InOverloadResolution,AllowObjCWritebackConversion);
5877
5878 if (ToType->isReferenceType())
5879 return TryReferenceInit(S, From, ToType,
5880 /*FIXME:*/ From->getBeginLoc(),
5881 SuppressUserConversions, AllowExplicit);
5882
5883 return TryImplicitConversion(S, From, ToType,
5884 SuppressUserConversions,
5885 AllowedExplicit::None,
5886 InOverloadResolution,
5887 /*CStyle=*/false,
5888 AllowObjCWritebackConversion,
5889 /*AllowObjCConversionOnExplicit=*/false);
5890}
5891
5892static bool TryCopyInitialization(const CanQualType FromQTy,
5893 const CanQualType ToQTy,
5894 Sema &S,
5895 SourceLocation Loc,
5896 ExprValueKind FromVK) {
5897 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5899 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5900
5901 return !ICS.isBad();
5902}
5903
5904/// TryObjectArgumentInitialization - Try to initialize the object
5905/// parameter of the given member function (@c Method) from the
5906/// expression @p From.
5908 Sema &S, SourceLocation Loc, QualType FromType,
5909 Expr::Classification FromClassification, CXXMethodDecl *Method,
5910 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5911 QualType ExplicitParameterType = QualType(),
5912 bool SuppressUserConversion = false) {
5913
5914 // We need to have an object of class type.
5915 if (const auto *PT = FromType->getAs<PointerType>()) {
5916 FromType = PT->getPointeeType();
5917
5918 // When we had a pointer, it's implicitly dereferenced, so we
5919 // better have an lvalue.
5920 assert(FromClassification.isLValue());
5921 }
5922
5923 auto ValueKindFromClassification = [](Expr::Classification C) {
5924 if (C.isPRValue())
5925 return clang::VK_PRValue;
5926 if (C.isXValue())
5927 return VK_XValue;
5928 return clang::VK_LValue;
5929 };
5930
5931 if (Method->isExplicitObjectMemberFunction()) {
5932 if (ExplicitParameterType.isNull())
5933 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5934 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5935 ValueKindFromClassification(FromClassification));
5937 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5938 /*InOverloadResolution=*/true, false);
5939 if (ICS.isBad())
5940 ICS.Bad.FromExpr = nullptr;
5941 return ICS;
5942 }
5943
5944 assert(FromType->isRecordType());
5945
5946 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
5947 // C++98 [class.dtor]p2:
5948 // A destructor can be invoked for a const, volatile or const volatile
5949 // object.
5950 // C++98 [over.match.funcs]p4:
5951 // For static member functions, the implicit object parameter is considered
5952 // to match any object (since if the function is selected, the object is
5953 // discarded).
5954 Qualifiers Quals = Method->getMethodQualifiers();
5955 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5956 Quals.addConst();
5957 Quals.addVolatile();
5958 }
5959
5960 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5961
5962 // Set up the conversion sequence as a "bad" conversion, to allow us
5963 // to exit early.
5965
5966 // C++0x [over.match.funcs]p4:
5967 // For non-static member functions, the type of the implicit object
5968 // parameter is
5969 //
5970 // - "lvalue reference to cv X" for functions declared without a
5971 // ref-qualifier or with the & ref-qualifier
5972 // - "rvalue reference to cv X" for functions declared with the &&
5973 // ref-qualifier
5974 //
5975 // where X is the class of which the function is a member and cv is the
5976 // cv-qualification on the member function declaration.
5977 //
5978 // However, when finding an implicit conversion sequence for the argument, we
5979 // are not allowed to perform user-defined conversions
5980 // (C++ [over.match.funcs]p5). We perform a simplified version of
5981 // reference binding here, that allows class rvalues to bind to
5982 // non-constant references.
5983
5984 // First check the qualifiers.
5985 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5986 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5987 if (ImplicitParamType.getCVRQualifiers() !=
5988 FromTypeCanon.getLocalCVRQualifiers() &&
5989 !ImplicitParamType.isAtLeastAsQualifiedAs(
5990 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5992 FromType, ImplicitParamType);
5993 return ICS;
5994 }
5995
5996 if (FromTypeCanon.hasAddressSpace()) {
5997 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5998 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5999 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6000 S.getASTContext())) {
6002 FromType, ImplicitParamType);
6003 return ICS;
6004 }
6005 }
6006
6007 // Check that we have either the same type or a derived type. It
6008 // affects the conversion rank.
6009 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6010 ImplicitConversionKind SecondKind;
6011 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6012 SecondKind = ICK_Identity;
6013 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6014 SecondKind = ICK_Derived_To_Base;
6015 } else if (!Method->isExplicitObjectMemberFunction()) {
6017 FromType, ImplicitParamType);
6018 return ICS;
6019 }
6020
6021 // Check the ref-qualifier.
6022 switch (Method->getRefQualifier()) {
6023 case RQ_None:
6024 // Do nothing; we don't care about lvalueness or rvalueness.
6025 break;
6026
6027 case RQ_LValue:
6028 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6029 // non-const lvalue reference cannot bind to an rvalue
6031 ImplicitParamType);
6032 return ICS;
6033 }
6034 break;
6035
6036 case RQ_RValue:
6037 if (!FromClassification.isRValue()) {
6038 // rvalue reference cannot bind to an lvalue
6040 ImplicitParamType);
6041 return ICS;
6042 }
6043 break;
6044 }
6045
6046 // Success. Mark this as a reference binding.
6047 ICS.setStandard();
6049 ICS.Standard.Second = SecondKind;
6050 ICS.Standard.setFromType(FromType);
6051 ICS.Standard.setAllToTypes(ImplicitParamType);
6052 ICS.Standard.ReferenceBinding = true;
6053 ICS.Standard.DirectBinding = true;
6054 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6055 ICS.Standard.BindsToFunctionLvalue = false;
6056 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6057 ICS.Standard.FromBracedInitList = false;
6059 = (Method->getRefQualifier() == RQ_None);
6060 return ICS;
6061}
6062
6063/// PerformObjectArgumentInitialization - Perform initialization of
6064/// the implicit object parameter for the given Method with the given
6065/// expression.
6067 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6069 QualType FromRecordType, DestType;
6070 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6071
6072 Expr::Classification FromClassification;
6073 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6074 FromRecordType = PT->getPointeeType();
6075 DestType = Method->getThisType();
6076 FromClassification = Expr::Classification::makeSimpleLValue();
6077 } else {
6078 FromRecordType = From->getType();
6079 DestType = ImplicitParamRecordType;
6080 FromClassification = From->Classify(Context);
6081
6082 // CWG2813 [expr.call]p6:
6083 // If the function is an implicit object member function, the object
6084 // expression of the class member access shall be a glvalue [...]
6085 if (From->isPRValue()) {
6086 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6087 Method->getRefQualifier() !=
6089 }
6090 }
6091
6092 // Note that we always use the true parent context when performing
6093 // the actual argument initialization.
6095 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6096 Method->getParent());
6097 if (ICS.isBad()) {
6098 switch (ICS.Bad.Kind) {
6100 Qualifiers FromQs = FromRecordType.getQualifiers();
6101 Qualifiers ToQs = DestType.getQualifiers();
6102 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6103 if (CVR) {
6104 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6105 << Method->getDeclName() << FromRecordType << (CVR - 1)
6106 << From->getSourceRange();
6107 Diag(Method->getLocation(), diag::note_previous_decl)
6108 << Method->getDeclName();
6109 return ExprError();
6110 }
6111 break;
6112 }
6113
6116 bool IsRValueQualified =
6117 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6118 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6119 << Method->getDeclName() << FromClassification.isRValue()
6120 << IsRValueQualified;
6121 Diag(Method->getLocation(), diag::note_previous_decl)
6122 << Method->getDeclName();
6123 return ExprError();
6124 }
6125
6128 break;
6129
6132 llvm_unreachable("Lists are not objects");
6133 }
6134
6135 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6136 << ImplicitParamRecordType << FromRecordType
6137 << From->getSourceRange();
6138 }
6139
6140 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6141 ExprResult FromRes =
6142 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6143 if (FromRes.isInvalid())
6144 return ExprError();
6145 From = FromRes.get();
6146 }
6147
6148 if (!Context.hasSameType(From->getType(), DestType)) {
6149 CastKind CK;
6150 QualType PteeTy = DestType->getPointeeType();
6151 LangAS DestAS =
6152 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6153 if (FromRecordType.getAddressSpace() != DestAS)
6154 CK = CK_AddressSpaceConversion;
6155 else
6156 CK = CK_NoOp;
6157 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6158 }
6159 return From;
6160}
6161
6162/// TryContextuallyConvertToBool - Attempt to contextually convert the
6163/// expression From to bool (C++0x [conv]p3).
6166 // C++ [dcl.init]/17.8:
6167 // - Otherwise, if the initialization is direct-initialization, the source
6168 // type is std::nullptr_t, and the destination type is bool, the initial
6169 // value of the object being initialized is false.
6170 if (From->getType()->isNullPtrType())
6172 S.Context.BoolTy,
6173 From->isGLValue());
6174
6175 // All other direct-initialization of bool is equivalent to an implicit
6176 // conversion to bool in which explicit conversions are permitted.
6177 return TryImplicitConversion(S, From, S.Context.BoolTy,
6178 /*SuppressUserConversions=*/false,
6179 AllowedExplicit::Conversions,
6180 /*InOverloadResolution=*/false,
6181 /*CStyle=*/false,
6182 /*AllowObjCWritebackConversion=*/false,
6183 /*AllowObjCConversionOnExplicit=*/false);
6184}
6185
6187 if (checkPlaceholderForOverload(*this, From))
6188 return ExprError();
6189
6191 if (!ICS.isBad())
6192 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6194
6196 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6197 << From->getType() << From->getSourceRange();
6198 return ExprError();
6199}
6200
6201/// Check that the specified conversion is permitted in a converted constant
6202/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6203/// is acceptable.
6206 // Since we know that the target type is an integral or unscoped enumeration
6207 // type, most conversion kinds are impossible. All possible First and Third
6208 // conversions are fine.
6209 switch (SCS.Second) {
6210 case ICK_Identity:
6212 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6214 return true;
6215
6217 // Conversion from an integral or unscoped enumeration type to bool is
6218 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6219 // conversion, so we allow it in a converted constant expression.
6220 //
6221 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6222 // a lot of popular code. We should at least add a warning for this
6223 // (non-conforming) extension.
6225 SCS.getToType(2)->isBooleanType();
6226
6228 case ICK_Pointer_Member:
6229 // C++1z: null pointer conversions and null member pointer conversions are
6230 // only permitted if the source type is std::nullptr_t.
6231 return SCS.getFromType()->isNullPtrType();
6232
6244 case ICK_Vector_Splat:
6245 case ICK_Complex_Real:
6254 return false;
6255
6260 llvm_unreachable("found a first conversion kind in Second");
6261
6263 case ICK_Qualification:
6264 llvm_unreachable("found a third conversion kind in Second");
6265
6267 break;
6268 }
6269
6270 llvm_unreachable("unknown conversion kind");
6271}
6272
6273/// BuildConvertedConstantExpression - Check that the expression From is a
6274/// converted constant expression of type T, perform the conversion but
6275/// does not evaluate the expression
6277 QualType T, CCEKind CCE,
6278 NamedDecl *Dest,
6279 APValue &PreNarrowingValue) {
6280 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6282 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6283 "converted constant expression outside C++11 or TTP matching");
6284
6285 if (checkPlaceholderForOverload(S, From))
6286 return ExprError();
6287
6288 // C++1z [expr.const]p3:
6289 // A converted constant expression of type T is an expression,
6290 // implicitly converted to type T, where the converted
6291 // expression is a constant expression and the implicit conversion
6292 // sequence contains only [... list of conversions ...].
6294 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6296 : TryCopyInitialization(S, From, T,
6297 /*SuppressUserConversions=*/false,
6298 /*InOverloadResolution=*/false,
6299 /*AllowObjCWritebackConversion=*/false,
6300 /*AllowExplicit=*/false);
6301 StandardConversionSequence *SCS = nullptr;
6302 switch (ICS.getKind()) {
6304 SCS = &ICS.Standard;
6305 break;
6307 if (T->isRecordType())
6308 SCS = &ICS.UserDefined.Before;
6309 else
6310 SCS = &ICS.UserDefined.After;
6311 break;
6315 return S.Diag(From->getBeginLoc(),
6316 diag::err_typecheck_converted_constant_expression)
6317 << From->getType() << From->getSourceRange() << T;
6318 return ExprError();
6319
6322 llvm_unreachable("bad conversion in converted constant expression");
6323 }
6324
6325 // Check that we would only use permitted conversions.
6326 if (!CheckConvertedConstantConversions(S, *SCS)) {
6327 return S.Diag(From->getBeginLoc(),
6328 diag::err_typecheck_converted_constant_expression_disallowed)
6329 << From->getType() << From->getSourceRange() << T;
6330 }
6331 // [...] and where the reference binding (if any) binds directly.
6332 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6333 return S.Diag(From->getBeginLoc(),
6334 diag::err_typecheck_converted_constant_expression_indirect)
6335 << From->getType() << From->getSourceRange() << T;
6336 }
6337 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6338 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6339 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6340 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6341 // case explicitly.
6342 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6343 return S.Diag(From->getBeginLoc(),
6344 diag::err_reference_bind_to_bitfield_in_cce)
6345 << From->getSourceRange();
6346 }
6347
6348 // Usually we can simply apply the ImplicitConversionSequence we formed
6349 // earlier, but that's not guaranteed to work when initializing an object of
6350 // class type.
6351 ExprResult Result;
6352 bool IsTemplateArgument =
6354 if (T->isRecordType()) {
6355 assert(IsTemplateArgument &&
6356 "unexpected class type converted constant expr");
6357 Result = S.PerformCopyInitialization(
6360 SourceLocation(), From);
6361 } else {
6362 Result =
6364 }
6365 if (Result.isInvalid())
6366 return Result;
6367
6368 // C++2a [intro.execution]p5:
6369 // A full-expression is [...] a constant-expression [...]
6370 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6371 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6372 IsTemplateArgument);
6373 if (Result.isInvalid())
6374 return Result;
6375
6376 // Check for a narrowing implicit conversion.
6377 bool ReturnPreNarrowingValue = false;
6378 QualType PreNarrowingType;
6379 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6380 PreNarrowingType)) {
6382 // Implicit conversion to a narrower type, and the value is not a constant
6383 // expression. We'll diagnose this in a moment.
6384 case NK_Not_Narrowing:
6385 break;
6386
6388 if (CCE == CCEKind::ArrayBound &&
6389 PreNarrowingType->isIntegralOrEnumerationType() &&
6390 PreNarrowingValue.isInt()) {
6391 // Don't diagnose array bound narrowing here; we produce more precise
6392 // errors by allowing the un-narrowed value through.
6393 ReturnPreNarrowingValue = true;
6394 break;
6395 }
6396 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6397 << CCE << /*Constant*/ 1
6398 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6399 break;
6400
6402 // Implicit conversion to a narrower type, but the expression is
6403 // value-dependent so we can't tell whether it's actually narrowing.
6404 // For matching the parameters of a TTP, the conversion is ill-formed
6405 // if it may narrow.
6406 if (CCE != CCEKind::TempArgStrict)
6407 break;
6408 [[fallthrough]];
6409 case NK_Type_Narrowing:
6410 // FIXME: It would be better to diagnose that the expression is not a
6411 // constant expression.
6412 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6413 << CCE << /*Constant*/ 0 << From->getType() << T;
6414 break;
6415 }
6416 if (!ReturnPreNarrowingValue)
6417 PreNarrowingValue = {};
6418
6419 return Result;
6420}
6421
6422/// CheckConvertedConstantExpression - Check that the expression From is a
6423/// converted constant expression of type T, perform the conversion and produce
6424/// the converted expression, per C++11 [expr.const]p3.
6427 CCEKind CCE, bool RequireInt,
6428 NamedDecl *Dest) {
6429
6430 APValue PreNarrowingValue;
6431 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6432 PreNarrowingValue);
6433 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6434 Value = APValue();
6435 return Result;
6436 }
6437 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6438 RequireInt, PreNarrowingValue);
6439}
6440
6442 CCEKind CCE,
6443 NamedDecl *Dest) {
6444 APValue PreNarrowingValue;
6445 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6446 PreNarrowingValue);
6447}
6448
6450 APValue &Value, CCEKind CCE,
6451 NamedDecl *Dest) {
6452 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6453 Dest);
6454}
6455
6457 llvm::APSInt &Value,
6458 CCEKind CCE) {
6459 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6460
6461 APValue V;
6462 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6463 /*Dest=*/nullptr);
6464 if (!R.isInvalid() && !R.get()->isValueDependent())
6465 Value = V.getInt();
6466 return R;
6467}
6468
6471 CCEKind CCE, bool RequireInt,
6472 const APValue &PreNarrowingValue) {
6473
6474 ExprResult Result = E;
6475 // Check the expression is a constant expression.
6477 Expr::EvalResult Eval;
6478 Eval.Diag = &Notes;
6479
6480 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6481
6482 ConstantExprKind Kind;
6483 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6484 Kind = ConstantExprKind::ClassTemplateArgument;
6485 else if (CCE == CCEKind::TemplateArg)
6486 Kind = ConstantExprKind::NonClassTemplateArgument;
6487 else
6488 Kind = ConstantExprKind::Normal;
6489
6490 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6491 (RequireInt && !Eval.Val.isInt())) {
6492 // The expression can't be folded, so we can't keep it at this position in
6493 // the AST.
6494 Result = ExprError();
6495 } else {
6496 Value = Eval.Val;
6497
6498 if (Notes.empty()) {
6499 // It's a constant expression.
6500 Expr *E = Result.get();
6501 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6502 // We expect a ConstantExpr to have a value associated with it
6503 // by this point.
6504 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6505 "ConstantExpr has no value associated with it");
6506 (void)CE;
6507 } else {
6509 }
6510 if (!PreNarrowingValue.isAbsent())
6511 Value = std::move(PreNarrowingValue);
6512 return E;
6513 }
6514 }
6515
6516 // It's not a constant expression. Produce an appropriate diagnostic.
6517 if (Notes.size() == 1 &&
6518 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6519 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6520 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6521 diag::note_constexpr_invalid_template_arg) {
6522 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6523 for (unsigned I = 0; I < Notes.size(); ++I)
6524 Diag(Notes[I].first, Notes[I].second);
6525 } else {
6526 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6527 << CCE << E->getSourceRange();
6528 for (unsigned I = 0; I < Notes.size(); ++I)
6529 Diag(Notes[I].first, Notes[I].second);
6530 }
6531 return ExprError();
6532}
6533
6534/// dropPointerConversions - If the given standard conversion sequence
6535/// involves any pointer conversions, remove them. This may change
6536/// the result type of the conversion sequence.
6538 if (SCS.Second == ICK_Pointer_Conversion) {
6539 SCS.Second = ICK_Identity;
6540 SCS.Dimension = ICK_Identity;
6541 SCS.Third = ICK_Identity;
6542 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6543 }
6544}
6545
6546/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6547/// convert the expression From to an Objective-C pointer type.
6548static ImplicitConversionSequence
6550 // Do an implicit conversion to 'id'.
6553 = TryImplicitConversion(S, From, Ty,
6554 // FIXME: Are these flags correct?
6555 /*SuppressUserConversions=*/false,
6556 AllowedExplicit::Conversions,
6557 /*InOverloadResolution=*/false,
6558 /*CStyle=*/false,
6559 /*AllowObjCWritebackConversion=*/false,
6560 /*AllowObjCConversionOnExplicit=*/true);
6561
6562 // Strip off any final conversions to 'id'.
6563 switch (ICS.getKind()) {
6568 break;
6569
6572 break;
6573
6576 break;
6577 }
6578
6579 return ICS;
6580}
6581
6583 if (checkPlaceholderForOverload(*this, From))
6584 return ExprError();
6585
6586 QualType Ty = Context.getObjCIdType();
6589 if (!ICS.isBad())
6590 return PerformImplicitConversion(From, Ty, ICS,
6592 return ExprResult();
6593}
6594
6595static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6596 const Expr *Base = nullptr;
6597 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6598 "expected a member expression");
6599
6600 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6601 M && !M->isImplicitAccess())
6602 Base = M->getBase();
6603 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6604 M && !M->isImplicitAccess())
6605 Base = M->getBase();
6606
6607 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6608
6609 if (T->isPointerType())
6610 T = T->getPointeeType();
6611
6612 return T;
6613}
6614
6616 const FunctionDecl *Fun) {
6617 QualType ObjType = Obj->getType();
6618 if (ObjType->isPointerType()) {
6619 ObjType = ObjType->getPointeeType();
6620 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6622 /*CanOverflow=*/false, FPOptionsOverride());
6623 }
6624 return Obj;
6625}
6626
6634
6636 Expr *Object, MultiExprArg &Args,
6637 SmallVectorImpl<Expr *> &NewArgs) {
6638 assert(Method->isExplicitObjectMemberFunction() &&
6639 "Method is not an explicit member function");
6640 assert(NewArgs.empty() && "NewArgs should be empty");
6641
6642 NewArgs.reserve(Args.size() + 1);
6643 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6644 NewArgs.push_back(This);
6645 NewArgs.append(Args.begin(), Args.end());
6646 Args = NewArgs;
6648 Method, Object->getBeginLoc());
6649}
6650
6651/// Determine whether the provided type is an integral type, or an enumeration
6652/// type of a permitted flavor.
6654 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6655 : T->isIntegralOrUnscopedEnumerationType();
6656}
6657
6658static ExprResult
6661 QualType T, UnresolvedSetImpl &ViableConversions) {
6662
6663 if (Converter.Suppress)
6664 return ExprError();
6665
6666 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6667 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6668 CXXConversionDecl *Conv =
6669 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6671 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6672 }
6673 return From;
6674}
6675
6676static bool
6679 QualType T, bool HadMultipleCandidates,
6680 UnresolvedSetImpl &ExplicitConversions) {
6681 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6682 DeclAccessPair Found = ExplicitConversions[0];
6683 CXXConversionDecl *Conversion =
6684 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6685
6686 // The user probably meant to invoke the given explicit
6687 // conversion; use it.
6688 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6689 std::string TypeStr;
6690 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6691
6692 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6694 "static_cast<" + TypeStr + ">(")
6696 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6697 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6698
6699 // If we aren't in a SFINAE context, build a call to the
6700 // explicit conversion function.
6701 if (SemaRef.isSFINAEContext())
6702 return true;
6703
6704 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6705 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6706 HadMultipleCandidates);
6707 if (Result.isInvalid())
6708 return true;
6709
6710 // Replace the conversion with a RecoveryExpr, so we don't try to
6711 // instantiate it later, but can further diagnose here.
6712 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6713 From, Result.get()->getType());
6714 if (Result.isInvalid())
6715 return true;
6716 From = Result.get();
6717 }
6718 return false;
6719}
6720
6721static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6723 QualType T, bool HadMultipleCandidates,
6725 CXXConversionDecl *Conversion =
6726 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6727 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6728
6729 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6730 if (!Converter.SuppressConversion) {
6731 if (SemaRef.isSFINAEContext())
6732 return true;
6733
6734 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6735 << From->getSourceRange();
6736 }
6737
6738 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6739 HadMultipleCandidates);
6740 if (Result.isInvalid())
6741 return true;
6742 // Record usage of conversion in an implicit cast.
6743 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6744 CK_UserDefinedConversion, Result.get(),
6745 nullptr, Result.get()->getValueKind(),
6746 SemaRef.CurFPFeatureOverrides());
6747 return false;
6748}
6749
6751 Sema &SemaRef, SourceLocation Loc, Expr *From,
6753 if (!Converter.match(From->getType()) && !Converter.Suppress)
6754 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6755 << From->getSourceRange();
6756
6757 return SemaRef.DefaultLvalueConversion(From);
6758}
6759
6760static void
6762 UnresolvedSetImpl &ViableConversions,
6763 OverloadCandidateSet &CandidateSet) {
6764 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6765 NamedDecl *D = FoundDecl.getDecl();
6766 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6767 if (isa<UsingShadowDecl>(D))
6768 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6769
6770 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6772 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6773 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6774 continue;
6775 }
6777 SemaRef.AddConversionCandidate(
6778 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6779 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6780 }
6781}
6782
6783/// Attempt to convert the given expression to a type which is accepted
6784/// by the given converter.
6785///
6786/// This routine will attempt to convert an expression of class type to a
6787/// type accepted by the specified converter. In C++11 and before, the class
6788/// must have a single non-explicit conversion function converting to a matching
6789/// type. In C++1y, there can be multiple such conversion functions, but only
6790/// one target type.
6791///
6792/// \param Loc The source location of the construct that requires the
6793/// conversion.
6794///
6795/// \param From The expression we're converting from.
6796///
6797/// \param Converter Used to control and diagnose the conversion process.
6798///
6799/// \returns The expression, converted to an integral or enumeration type if
6800/// successful.
6802 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6803 // We can't perform any more checking for type-dependent expressions.
6804 if (From->isTypeDependent())
6805 return From;
6806
6807 // Process placeholders immediately.
6808 if (From->hasPlaceholderType()) {
6809 ExprResult result = CheckPlaceholderExpr(From);
6810 if (result.isInvalid())
6811 return result;
6812 From = result.get();
6813 }
6814
6815 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6816 ExprResult Converted = DefaultLvalueConversion(From);
6817 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6818 // If the expression already has a matching type, we're golden.
6819 if (Converter.match(T))
6820 return Converted;
6821
6822 // FIXME: Check for missing '()' if T is a function type?
6823
6824 // We can only perform contextual implicit conversions on objects of class
6825 // type.
6826 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6827 if (!RecordTy || !getLangOpts().CPlusPlus) {
6828 if (!Converter.Suppress)
6829 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6830 return From;
6831 }
6832
6833 // We must have a complete class type.
6834 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6835 ContextualImplicitConverter &Converter;
6836 Expr *From;
6837
6838 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6839 : Converter(Converter), From(From) {}
6840
6841 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6842 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6843 }
6844 } IncompleteDiagnoser(Converter, From);
6845
6846 if (Converter.Suppress ? !isCompleteType(Loc, T)
6847 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6848 return From;
6849
6850 // Look for a conversion to an integral or enumeration type.
6852 ViableConversions; // These are *potentially* viable in C++1y.
6853 UnresolvedSet<4> ExplicitConversions;
6854 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
6855 ->getDefinitionOrSelf()
6856 ->getVisibleConversionFunctions();
6857
6858 bool HadMultipleCandidates =
6859 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6860
6861 // To check that there is only one target type, in C++1y:
6862 QualType ToType;
6863 bool HasUniqueTargetType = true;
6864
6865 // Collect explicit or viable (potentially in C++1y) conversions.
6866 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6867 NamedDecl *D = (*I)->getUnderlyingDecl();
6868 CXXConversionDecl *Conversion;
6869 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6870 if (ConvTemplate) {
6872 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6873 else
6874 continue; // C++11 does not consider conversion operator templates(?).
6875 } else
6876 Conversion = cast<CXXConversionDecl>(D);
6877
6878 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6879 "Conversion operator templates are considered potentially "
6880 "viable in C++1y");
6881
6882 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6883 if (Converter.match(CurToType) || ConvTemplate) {
6884
6885 if (Conversion->isExplicit()) {
6886 // FIXME: For C++1y, do we need this restriction?
6887 // cf. diagnoseNoViableConversion()
6888 if (!ConvTemplate)
6889 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6890 } else {
6891 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6892 if (ToType.isNull())
6893 ToType = CurToType.getUnqualifiedType();
6894 else if (HasUniqueTargetType &&
6895 (CurToType.getUnqualifiedType() != ToType))
6896 HasUniqueTargetType = false;
6897 }
6898 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6899 }
6900 }
6901 }
6902
6903 if (getLangOpts().CPlusPlus14) {
6904 // C++1y [conv]p6:
6905 // ... An expression e of class type E appearing in such a context
6906 // is said to be contextually implicitly converted to a specified
6907 // type T and is well-formed if and only if e can be implicitly
6908 // converted to a type T that is determined as follows: E is searched
6909 // for conversion functions whose return type is cv T or reference to
6910 // cv T such that T is allowed by the context. There shall be
6911 // exactly one such T.
6912
6913 // If no unique T is found:
6914 if (ToType.isNull()) {
6915 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6916 HadMultipleCandidates,
6917 ExplicitConversions))
6918 return ExprError();
6919 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6920 }
6921
6922 // If more than one unique Ts are found:
6923 if (!HasUniqueTargetType)
6924 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6925 ViableConversions);
6926
6927 // If one unique T is found:
6928 // First, build a candidate set from the previously recorded
6929 // potentially viable conversions.
6931 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6932 CandidateSet);
6933
6934 // Then, perform overload resolution over the candidate set.
6936 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6937 case OR_Success: {
6938 // Apply this conversion.
6940 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6941 if (recordConversion(*this, Loc, From, Converter, T,
6942 HadMultipleCandidates, Found))
6943 return ExprError();
6944 break;
6945 }
6946 case OR_Ambiguous:
6947 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6948 ViableConversions);
6950 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6951 HadMultipleCandidates,
6952 ExplicitConversions))
6953 return ExprError();
6954 [[fallthrough]];
6955 case OR_Deleted:
6956 // We'll complain below about a non-integral condition type.
6957 break;
6958 }
6959 } else {
6960 switch (ViableConversions.size()) {
6961 case 0: {
6962 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6963 HadMultipleCandidates,
6964 ExplicitConversions))
6965 return ExprError();
6966
6967 // We'll complain below about a non-integral condition type.
6968 break;
6969 }
6970 case 1: {
6971 // Apply this conversion.
6972 DeclAccessPair Found = ViableConversions[0];
6973 if (recordConversion(*this, Loc, From, Converter, T,
6974 HadMultipleCandidates, Found))
6975 return ExprError();
6976 break;
6977 }
6978 default:
6979 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6980 ViableConversions);
6981 }
6982 }
6983
6984 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6985}
6986
6987/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6988/// an acceptable non-member overloaded operator for a call whose
6989/// arguments have types T1 (and, if non-empty, T2). This routine
6990/// implements the check in C++ [over.match.oper]p3b2 concerning
6991/// enumeration types.
6993 FunctionDecl *Fn,
6994 ArrayRef<Expr *> Args) {
6995 QualType T1 = Args[0]->getType();
6996 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6997
6998 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6999 return true;
7000
7001 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7002 return true;
7003
7004 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7005 if (Proto->getNumParams() < 1)
7006 return false;
7007
7008 if (T1->isEnumeralType()) {
7009 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7010 if (Context.hasSameUnqualifiedType(T1, ArgType))
7011 return true;
7012 }
7013
7014 if (Proto->getNumParams() < 2)
7015 return false;
7016
7017 if (!T2.isNull() && T2->isEnumeralType()) {
7018 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7019 if (Context.hasSameUnqualifiedType(T2, ArgType))
7020 return true;
7021 }
7022
7023 return false;
7024}
7025
7028 return false;
7029
7030 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7031 return FD->isTargetMultiVersion();
7032
7033 if (!FD->isMultiVersion())
7034 return false;
7035
7036 // Among multiple target versions consider either the default,
7037 // or the first non-default in the absence of default version.
7038 unsigned SeenAt = 0;
7039 unsigned I = 0;
7040 bool HasDefault = false;
7042 FD, [&](const FunctionDecl *CurFD) {
7043 if (FD == CurFD)
7044 SeenAt = I;
7045 else if (CurFD->isTargetMultiVersionDefault())
7046 HasDefault = true;
7047 ++I;
7048 });
7049 return HasDefault || SeenAt != 0;
7050}
7051
7054 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7055 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7056 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7057 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7058 bool StrictPackMatch) {
7059 const FunctionProtoType *Proto
7060 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7061 assert(Proto && "Functions without a prototype cannot be overloaded");
7062 assert(!Function->getDescribedFunctionTemplate() &&
7063 "Use AddTemplateOverloadCandidate for function templates");
7064
7065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7067 // If we get here, it's because we're calling a member function
7068 // that is named without a member access expression (e.g.,
7069 // "this->f") that was either written explicitly or created
7070 // implicitly. This can happen with a qualified call to a member
7071 // function, e.g., X::f(). We use an empty type for the implied
7072 // object argument (C++ [over.call.func]p3), and the acting context
7073 // is irrelevant.
7074 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7076 CandidateSet, SuppressUserConversions,
7077 PartialOverloading, EarlyConversions, PO,
7078 StrictPackMatch);
7079 return;
7080 }
7081 // We treat a constructor like a non-member function, since its object
7082 // argument doesn't participate in overload resolution.
7083 }
7084
7085 if (!CandidateSet.isNewCandidate(Function, PO))
7086 return;
7087
7088 // C++11 [class.copy]p11: [DR1402]
7089 // A defaulted move constructor that is defined as deleted is ignored by
7090 // overload resolution.
7091 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7092 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7093 Constructor->isMoveConstructor())
7094 return;
7095
7096 // Overload resolution is always an unevaluated context.
7099
7100 // C++ [over.match.oper]p3:
7101 // if no operand has a class type, only those non-member functions in the
7102 // lookup set that have a first parameter of type T1 or "reference to
7103 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7104 // is a right operand) a second parameter of type T2 or "reference to
7105 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7106 // candidate functions.
7107 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7109 return;
7110
7111 // Add this candidate
7112 OverloadCandidate &Candidate =
7113 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7114 Candidate.FoundDecl = FoundDecl;
7115 Candidate.Function = Function;
7116 Candidate.Viable = true;
7117 Candidate.RewriteKind =
7118 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7119 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7120 Candidate.ExplicitCallArguments = Args.size();
7121 Candidate.StrictPackMatch = StrictPackMatch;
7122
7123 // Explicit functions are not actually candidates at all if we're not
7124 // allowing them in this context, but keep them around so we can point
7125 // to them in diagnostics.
7126 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7127 Candidate.Viable = false;
7128 Candidate.FailureKind = ovl_fail_explicit;
7129 return;
7130 }
7131
7132 // Functions with internal linkage are only viable in the same module unit.
7133 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7134 /// FIXME: Currently, the semantics of linkage in clang is slightly
7135 /// different from the semantics in C++ spec. In C++ spec, only names
7136 /// have linkage. So that all entities of the same should share one
7137 /// linkage. But in clang, different entities of the same could have
7138 /// different linkage.
7139 const NamedDecl *ND = Function;
7140 bool IsImplicitlyInstantiated = false;
7141 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7142 ND = SpecInfo->getTemplate();
7143 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7145 }
7146
7147 /// Don't remove inline functions with internal linkage from the overload
7148 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7149 /// However:
7150 /// - Inline functions with internal linkage are a common pattern in
7151 /// headers to avoid ODR issues.
7152 /// - The global module is meant to be a transition mechanism for C and C++
7153 /// headers, and the current rules as written work against that goal.
7154 const bool IsInlineFunctionInGMF =
7155 Function->isFromGlobalModule() &&
7156 (IsImplicitlyInstantiated || Function->isInlined());
7157
7158 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7159 Candidate.Viable = false;
7161 return;
7162 }
7163 }
7164
7166 Candidate.Viable = false;
7168 return;
7169 }
7170
7171 if (Constructor) {
7172 // C++ [class.copy]p3:
7173 // A member function template is never instantiated to perform the copy
7174 // of a class object to an object of its class type.
7175 CanQualType ClassType =
7176 Context.getCanonicalTagType(Constructor->getParent());
7177 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7178 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7179 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7180 ClassType))) {
7181 Candidate.Viable = false;
7183 return;
7184 }
7185
7186 // C++ [over.match.funcs]p8: (proposed DR resolution)
7187 // A constructor inherited from class type C that has a first parameter
7188 // of type "reference to P" (including such a constructor instantiated
7189 // from a template) is excluded from the set of candidate functions when
7190 // constructing an object of type cv D if the argument list has exactly
7191 // one argument and D is reference-related to P and P is reference-related
7192 // to C.
7193 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7194 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7195 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7196 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7197 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7198 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7199 SourceLocation Loc = Args.front()->getExprLoc();
7200 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7201 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7202 Candidate.Viable = false;
7204 return;
7205 }
7206 }
7207
7208 // Check that the constructor is capable of constructing an object in the
7209 // destination address space.
7211 Constructor->getMethodQualifiers().getAddressSpace(),
7212 CandidateSet.getDestAS(), getASTContext())) {
7213 Candidate.Viable = false;
7215 }
7216 }
7217
7218 unsigned NumParams = Proto->getNumParams();
7219
7220 // (C++ 13.3.2p2): A candidate function having fewer than m
7221 // parameters is viable only if it has an ellipsis in its parameter
7222 // list (8.3.5).
7223 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7224 !Proto->isVariadic() &&
7225 shouldEnforceArgLimit(PartialOverloading, Function)) {
7226 Candidate.Viable = false;
7228 return;
7229 }
7230
7231 // (C++ 13.3.2p2): A candidate function having more than m parameters
7232 // is viable only if the (m+1)st parameter has a default argument
7233 // (8.3.6). For the purposes of overload resolution, the
7234 // parameter list is truncated on the right, so that there are
7235 // exactly m parameters.
7236 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7237 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7238 !PartialOverloading) {
7239 // Not enough arguments.
7240 Candidate.Viable = false;
7242 return;
7243 }
7244
7245 // (CUDA B.1): Check for invalid calls between targets.
7246 if (getLangOpts().CUDA) {
7247 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7248 // Skip the check for callers that are implicit members, because in this
7249 // case we may not yet know what the member's target is; the target is
7250 // inferred for the member automatically, based on the bases and fields of
7251 // the class.
7252 if (!(Caller && Caller->isImplicit()) &&
7253 !CUDA().IsAllowedCall(Caller, Function)) {
7254 Candidate.Viable = false;
7255 Candidate.FailureKind = ovl_fail_bad_target;
7256 return;
7257 }
7258 }
7259
7260 if (Function->getTrailingRequiresClause()) {
7261 ConstraintSatisfaction Satisfaction;
7262 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7263 /*ForOverloadResolution*/ true) ||
7264 !Satisfaction.IsSatisfied) {
7265 Candidate.Viable = false;
7267 return;
7268 }
7269 }
7270
7271 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7272 // Determine the implicit conversion sequences for each of the
7273 // arguments.
7274 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7275 unsigned ConvIdx =
7276 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7277 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7278 // We already formed a conversion sequence for this parameter during
7279 // template argument deduction.
7280 } else if (ArgIdx < NumParams) {
7281 // (C++ 13.3.2p3): for F to be a viable function, there shall
7282 // exist for each argument an implicit conversion sequence
7283 // (13.3.3.1) that converts that argument to the corresponding
7284 // parameter of F.
7285 QualType ParamType = Proto->getParamType(ArgIdx);
7286 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7287 if (ParamABI == ParameterABI::HLSLOut ||
7288 ParamABI == ParameterABI::HLSLInOut)
7289 ParamType = ParamType.getNonReferenceType();
7290 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7291 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7292 /*InOverloadResolution=*/true,
7293 /*AllowObjCWritebackConversion=*/
7294 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7295 if (Candidate.Conversions[ConvIdx].isBad()) {
7296 Candidate.Viable = false;
7298 return;
7299 }
7300 } else {
7301 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7302 // argument for which there is no corresponding parameter is
7303 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7304 Candidate.Conversions[ConvIdx].setEllipsis();
7305 }
7306 }
7307
7308 if (EnableIfAttr *FailedAttr =
7309 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7310 Candidate.Viable = false;
7311 Candidate.FailureKind = ovl_fail_enable_if;
7312 Candidate.DeductionFailure.Data = FailedAttr;
7313 return;
7314 }
7315}
7316
7320 if (Methods.size() <= 1)
7321 return nullptr;
7322
7323 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7324 bool Match = true;
7325 ObjCMethodDecl *Method = Methods[b];
7326 unsigned NumNamedArgs = Sel.getNumArgs();
7327 // Method might have more arguments than selector indicates. This is due
7328 // to addition of c-style arguments in method.
7329 if (Method->param_size() > NumNamedArgs)
7330 NumNamedArgs = Method->param_size();
7331 if (Args.size() < NumNamedArgs)
7332 continue;
7333
7334 for (unsigned i = 0; i < NumNamedArgs; i++) {
7335 // We can't do any type-checking on a type-dependent argument.
7336 if (Args[i]->isTypeDependent()) {
7337 Match = false;
7338 break;
7339 }
7340
7341 ParmVarDecl *param = Method->parameters()[i];
7342 Expr *argExpr = Args[i];
7343 assert(argExpr && "SelectBestMethod(): missing expression");
7344
7345 // Strip the unbridged-cast placeholder expression off unless it's
7346 // a consumed argument.
7347 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7348 !param->hasAttr<CFConsumedAttr>())
7349 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7350
7351 // If the parameter is __unknown_anytype, move on to the next method.
7352 if (param->getType() == Context.UnknownAnyTy) {
7353 Match = false;
7354 break;
7355 }
7356
7357 ImplicitConversionSequence ConversionState
7358 = TryCopyInitialization(*this, argExpr, param->getType(),
7359 /*SuppressUserConversions*/false,
7360 /*InOverloadResolution=*/true,
7361 /*AllowObjCWritebackConversion=*/
7362 getLangOpts().ObjCAutoRefCount,
7363 /*AllowExplicit*/false);
7364 // This function looks for a reasonably-exact match, so we consider
7365 // incompatible pointer conversions to be a failure here.
7366 if (ConversionState.isBad() ||
7367 (ConversionState.isStandard() &&
7368 ConversionState.Standard.Second ==
7370 Match = false;
7371 break;
7372 }
7373 }
7374 // Promote additional arguments to variadic methods.
7375 if (Match && Method->isVariadic()) {
7376 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7377 if (Args[i]->isTypeDependent()) {
7378 Match = false;
7379 break;
7380 }
7382 Args[i], VariadicCallType::Method, nullptr);
7383 if (Arg.isInvalid()) {
7384 Match = false;
7385 break;
7386 }
7387 }
7388 } else {
7389 // Check for extra arguments to non-variadic methods.
7390 if (Args.size() != NumNamedArgs)
7391 Match = false;
7392 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7393 // Special case when selectors have no argument. In this case, select
7394 // one with the most general result type of 'id'.
7395 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7396 QualType ReturnT = Methods[b]->getReturnType();
7397 if (ReturnT->isObjCIdType())
7398 return Methods[b];
7399 }
7400 }
7401 }
7402
7403 if (Match)
7404 return Method;
7405 }
7406 return nullptr;
7407}
7408
7410 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7411 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7412 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7413 if (ThisArg) {
7414 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7415 assert(!isa<CXXConstructorDecl>(Method) &&
7416 "Shouldn't have `this` for ctors!");
7417 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7419 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7420 if (R.isInvalid())
7421 return false;
7422 ConvertedThis = R.get();
7423 } else {
7424 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7425 (void)MD;
7426 assert((MissingImplicitThis || MD->isStatic() ||
7428 "Expected `this` for non-ctor instance methods");
7429 }
7430 ConvertedThis = nullptr;
7431 }
7432
7433 // Ignore any variadic arguments. Converting them is pointless, since the
7434 // user can't refer to them in the function condition.
7435 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7436
7437 // Convert the arguments.
7438 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7439 ExprResult R;
7441 S.Context, Function->getParamDecl(I)),
7442 SourceLocation(), Args[I]);
7443
7444 if (R.isInvalid())
7445 return false;
7446
7447 ConvertedArgs.push_back(R.get());
7448 }
7449
7450 if (Trap.hasErrorOccurred())
7451 return false;
7452
7453 // Push default arguments if needed.
7454 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7455 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7456 ParmVarDecl *P = Function->getParamDecl(i);
7457 if (!P->hasDefaultArg())
7458 return false;
7459 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7460 if (R.isInvalid())
7461 return false;
7462 ConvertedArgs.push_back(R.get());
7463 }
7464
7465 if (Trap.hasErrorOccurred())
7466 return false;
7467 }
7468 return true;
7469}
7470
7472 SourceLocation CallLoc,
7473 ArrayRef<Expr *> Args,
7474 bool MissingImplicitThis) {
7475 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7476 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7477 return nullptr;
7478
7479 SFINAETrap Trap(*this);
7480 SmallVector<Expr *, 16> ConvertedArgs;
7481 // FIXME: We should look into making enable_if late-parsed.
7482 Expr *DiscardedThis;
7484 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7485 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7486 return *EnableIfAttrs.begin();
7487
7488 for (auto *EIA : EnableIfAttrs) {
7490 // FIXME: This doesn't consider value-dependent cases, because doing so is
7491 // very difficult. Ideally, we should handle them more gracefully.
7492 if (EIA->getCond()->isValueDependent() ||
7493 !EIA->getCond()->EvaluateWithSubstitution(
7494 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7495 return EIA;
7496
7497 if (!Result.isInt() || !Result.getInt().getBoolValue())
7498 return EIA;
7499 }
7500 return nullptr;
7501}
7502
7503template <typename CheckFn>
7505 bool ArgDependent, SourceLocation Loc,
7506 CheckFn &&IsSuccessful) {
7508 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7509 if (ArgDependent == DIA->getArgDependent())
7510 Attrs.push_back(DIA);
7511 }
7512
7513 // Common case: No diagnose_if attributes, so we can quit early.
7514 if (Attrs.empty())
7515 return false;
7516
7517 auto WarningBegin = std::stable_partition(
7518 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7519 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7520 DIA->getWarningGroup().empty();
7521 });
7522
7523 // Note that diagnose_if attributes are late-parsed, so they appear in the
7524 // correct order (unlike enable_if attributes).
7525 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7526 IsSuccessful);
7527 if (ErrAttr != WarningBegin) {
7528 const DiagnoseIfAttr *DIA = *ErrAttr;
7529 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7530 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7531 << DIA->getParent() << DIA->getCond()->getSourceRange();
7532 return true;
7533 }
7534
7535 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7536 switch (Sev) {
7537 case DiagnoseIfAttr::DS_warning:
7539 case DiagnoseIfAttr::DS_error:
7540 return diag::Severity::Error;
7541 }
7542 llvm_unreachable("Fully covered switch above!");
7543 };
7544
7545 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7546 if (IsSuccessful(DIA)) {
7547 if (DIA->getWarningGroup().empty() &&
7548 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7549 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7550 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7551 << DIA->getParent() << DIA->getCond()->getSourceRange();
7552 } else {
7553 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7554 DIA->getWarningGroup());
7555 assert(DiagGroup);
7556 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7557 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7558 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7559 S.Diag(Loc, DiagID) << DIA->getMessage();
7560 }
7561 }
7562
7563 return false;
7564}
7565
7567 const Expr *ThisArg,
7569 SourceLocation Loc) {
7571 *this, Function, /*ArgDependent=*/true, Loc,
7572 [&](const DiagnoseIfAttr *DIA) {
7574 // It's sane to use the same Args for any redecl of this function, since
7575 // EvaluateWithSubstitution only cares about the position of each
7576 // argument in the arg list, not the ParmVarDecl* it maps to.
7577 if (!DIA->getCond()->EvaluateWithSubstitution(
7578 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7579 return false;
7580 return Result.isInt() && Result.getInt().getBoolValue();
7581 });
7582}
7583
7585 SourceLocation Loc) {
7587 *this, ND, /*ArgDependent=*/false, Loc,
7588 [&](const DiagnoseIfAttr *DIA) {
7589 bool Result;
7590 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7591 Result;
7592 });
7593}
7594
7596 ArrayRef<Expr *> Args,
7597 OverloadCandidateSet &CandidateSet,
7598 TemplateArgumentListInfo *ExplicitTemplateArgs,
7599 bool SuppressUserConversions,
7600 bool PartialOverloading,
7601 bool FirstArgumentIsBase) {
7602 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7603 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7604 ArrayRef<Expr *> FunctionArgs = Args;
7605
7606 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7607 FunctionDecl *FD =
7608 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7609
7610 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7611 QualType ObjectType;
7612 Expr::Classification ObjectClassification;
7613 if (Args.size() > 0) {
7614 if (Expr *E = Args[0]) {
7615 // Use the explicit base to restrict the lookup:
7616 ObjectType = E->getType();
7617 // Pointers in the object arguments are implicitly dereferenced, so we
7618 // always classify them as l-values.
7619 if (!ObjectType.isNull() && ObjectType->isPointerType())
7620 ObjectClassification = Expr::Classification::makeSimpleLValue();
7621 else
7622 ObjectClassification = E->Classify(Context);
7623 } // .. else there is an implicit base.
7624 FunctionArgs = Args.slice(1);
7625 }
7626 if (FunTmpl) {
7628 FunTmpl, F.getPair(),
7630 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7631 FunctionArgs, CandidateSet, SuppressUserConversions,
7632 PartialOverloading);
7633 } else {
7634 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7635 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7636 ObjectClassification, FunctionArgs, CandidateSet,
7637 SuppressUserConversions, PartialOverloading);
7638 }
7639 } else {
7640 // This branch handles both standalone functions and static methods.
7641
7642 // Slice the first argument (which is the base) when we access
7643 // static method as non-static.
7644 if (Args.size() > 0 &&
7645 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7646 !isa<CXXConstructorDecl>(FD)))) {
7647 assert(cast<CXXMethodDecl>(FD)->isStatic());
7648 FunctionArgs = Args.slice(1);
7649 }
7650 if (FunTmpl) {
7651 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7652 ExplicitTemplateArgs, FunctionArgs,
7653 CandidateSet, SuppressUserConversions,
7654 PartialOverloading);
7655 } else {
7656 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7657 SuppressUserConversions, PartialOverloading);
7658 }
7659 }
7660 }
7661}
7662
7664 Expr::Classification ObjectClassification,
7665 ArrayRef<Expr *> Args,
7666 OverloadCandidateSet &CandidateSet,
7667 bool SuppressUserConversions,
7669 NamedDecl *Decl = FoundDecl.getDecl();
7671
7673 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7674
7675 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7676 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7677 "Expected a member function template");
7678 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7679 /*ExplicitArgs*/ nullptr, ObjectType,
7680 ObjectClassification, Args, CandidateSet,
7681 SuppressUserConversions, false, PO);
7682 } else {
7683 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7684 ObjectType, ObjectClassification, Args, CandidateSet,
7685 SuppressUserConversions, false, {}, PO);
7686 }
7687}
7688
7691 CXXRecordDecl *ActingContext, QualType ObjectType,
7692 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7693 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7694 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7695 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7696 const FunctionProtoType *Proto
7697 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7698 assert(Proto && "Methods without a prototype cannot be overloaded");
7700 "Use AddOverloadCandidate for constructors");
7701
7702 if (!CandidateSet.isNewCandidate(Method, PO))
7703 return;
7704
7705 // C++11 [class.copy]p23: [DR1402]
7706 // A defaulted move assignment operator that is defined as deleted is
7707 // ignored by overload resolution.
7708 if (Method->isDefaulted() && Method->isDeleted() &&
7709 Method->isMoveAssignmentOperator())
7710 return;
7711
7712 // Overload resolution is always an unevaluated context.
7715
7716 bool IgnoreExplicitObject =
7717 (Method->isExplicitObjectMemberFunction() &&
7718 CandidateSet.getKind() ==
7720 bool ImplicitObjectMethodTreatedAsStatic =
7721 CandidateSet.getKind() ==
7723 Method->isImplicitObjectMemberFunction();
7724
7725 unsigned ExplicitOffset =
7726 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7727
7728 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7729 int(ImplicitObjectMethodTreatedAsStatic);
7730
7731 unsigned ExtraArgs =
7733 ? 0
7734 : 1;
7735
7736 // Add this candidate
7737 OverloadCandidate &Candidate =
7738 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7739 Candidate.FoundDecl = FoundDecl;
7740 Candidate.Function = Method;
7741 Candidate.RewriteKind =
7742 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7743 Candidate.TookAddressOfOverload =
7745 Candidate.ExplicitCallArguments = Args.size();
7746 Candidate.StrictPackMatch = StrictPackMatch;
7747
7748 // (C++ 13.3.2p2): A candidate function having fewer than m
7749 // parameters is viable only if it has an ellipsis in its parameter
7750 // list (8.3.5).
7751 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7752 !Proto->isVariadic() &&
7753 shouldEnforceArgLimit(PartialOverloading, Method)) {
7754 Candidate.Viable = false;
7756 return;
7757 }
7758
7759 // (C++ 13.3.2p2): A candidate function having more than m parameters
7760 // is viable only if the (m+1)st parameter has a default argument
7761 // (8.3.6). For the purposes of overload resolution, the
7762 // parameter list is truncated on the right, so that there are
7763 // exactly m parameters.
7764 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7765 ExplicitOffset +
7766 int(ImplicitObjectMethodTreatedAsStatic);
7767
7768 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7769 // Not enough arguments.
7770 Candidate.Viable = false;
7772 return;
7773 }
7774
7775 Candidate.Viable = true;
7776
7777 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7778 if (!IgnoreExplicitObject) {
7779 if (ObjectType.isNull())
7780 Candidate.IgnoreObjectArgument = true;
7781 else if (Method->isStatic()) {
7782 // [over.best.ics.general]p8
7783 // When the parameter is the implicit object parameter of a static member
7784 // function, the implicit conversion sequence is a standard conversion
7785 // sequence that is neither better nor worse than any other standard
7786 // conversion sequence.
7787 //
7788 // This is a rule that was introduced in C++23 to support static lambdas.
7789 // We apply it retroactively because we want to support static lambdas as
7790 // an extension and it doesn't hurt previous code.
7791 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7792 } else {
7793 // Determine the implicit conversion sequence for the object
7794 // parameter.
7795 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7796 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7797 Method, ActingContext, /*InOverloadResolution=*/true);
7798 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7799 Candidate.Viable = false;
7801 return;
7802 }
7803 }
7804 }
7805
7806 // (CUDA B.1): Check for invalid calls between targets.
7807 if (getLangOpts().CUDA)
7808 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7809 Method)) {
7810 Candidate.Viable = false;
7811 Candidate.FailureKind = ovl_fail_bad_target;
7812 return;
7813 }
7814
7815 if (Method->getTrailingRequiresClause()) {
7816 ConstraintSatisfaction Satisfaction;
7817 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7818 /*ForOverloadResolution*/ true) ||
7819 !Satisfaction.IsSatisfied) {
7820 Candidate.Viable = false;
7822 return;
7823 }
7824 }
7825
7826 // Determine the implicit conversion sequences for each of the
7827 // arguments.
7828 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7829 unsigned ConvIdx =
7830 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7831 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7832 // We already formed a conversion sequence for this parameter during
7833 // template argument deduction.
7834 } else if (ArgIdx < NumParams) {
7835 // (C++ 13.3.2p3): for F to be a viable function, there shall
7836 // exist for each argument an implicit conversion sequence
7837 // (13.3.3.1) that converts that argument to the corresponding
7838 // parameter of F.
7839 QualType ParamType;
7840 if (ImplicitObjectMethodTreatedAsStatic) {
7841 ParamType = ArgIdx == 0
7842 ? Method->getFunctionObjectParameterReferenceType()
7843 : Proto->getParamType(ArgIdx - 1);
7844 } else {
7845 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7846 }
7847 Candidate.Conversions[ConvIdx]
7848 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7849 SuppressUserConversions,
7850 /*InOverloadResolution=*/true,
7851 /*AllowObjCWritebackConversion=*/
7852 getLangOpts().ObjCAutoRefCount);
7853 if (Candidate.Conversions[ConvIdx].isBad()) {
7854 Candidate.Viable = false;
7856 return;
7857 }
7858 } else {
7859 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7860 // argument for which there is no corresponding parameter is
7861 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7862 Candidate.Conversions[ConvIdx].setEllipsis();
7863 }
7864 }
7865
7866 if (EnableIfAttr *FailedAttr =
7867 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7868 Candidate.Viable = false;
7869 Candidate.FailureKind = ovl_fail_enable_if;
7870 Candidate.DeductionFailure.Data = FailedAttr;
7871 return;
7872 }
7873
7875 Candidate.Viable = false;
7877 }
7878}
7879
7881 Sema &S, OverloadCandidateSet &CandidateSet,
7882 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7883 CXXRecordDecl *ActingContext,
7884 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7885 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7886 bool SuppressUserConversions, bool PartialOverloading,
7888
7889 // C++ [over.match.funcs]p7:
7890 // In each case where a candidate is a function template, candidate
7891 // function template specializations are generated using template argument
7892 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7893 // candidate functions in the usual way.113) A given name can refer to one
7894 // or more function templates and also to a set of overloaded non-template
7895 // functions. In such a case, the candidate functions generated from each
7896 // function template are combined with the set of non-template candidate
7897 // functions.
7898 TemplateDeductionInfo Info(CandidateSet.getLocation());
7899 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7900 FunctionDecl *Specialization = nullptr;
7901 ConversionSequenceList Conversions;
7903 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7904 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7905 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7906 CandidateSet.getKind() ==
7908 [&](ArrayRef<QualType> ParamTypes,
7909 bool OnlyInitializeNonUserDefinedConversions) {
7910 return S.CheckNonDependentConversions(
7911 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7912 Sema::CheckNonDependentConversionsFlag(
7913 SuppressUserConversions,
7914 OnlyInitializeNonUserDefinedConversions),
7915 ActingContext, ObjectType, ObjectClassification, PO);
7916 });
7918 OverloadCandidate &Candidate =
7919 CandidateSet.addCandidate(Conversions.size(), Conversions);
7920 Candidate.FoundDecl = FoundDecl;
7921 Candidate.Function = Method;
7922 Candidate.Viable = false;
7923 Candidate.RewriteKind =
7924 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7925 Candidate.IsSurrogate = false;
7926 Candidate.TookAddressOfOverload =
7927 CandidateSet.getKind() ==
7929
7930 Candidate.IgnoreObjectArgument =
7931 Method->isStatic() ||
7932 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7933 Candidate.ExplicitCallArguments = Args.size();
7936 else {
7938 Candidate.DeductionFailure =
7939 MakeDeductionFailureInfo(S.Context, Result, Info);
7940 }
7941 return;
7942 }
7943
7944 // Add the function template specialization produced by template argument
7945 // deduction as a candidate.
7946 assert(Specialization && "Missing member function template specialization?");
7948 "Specialization is not a member function?");
7950 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7951 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7952 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7953}
7954
7956 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7957 CXXRecordDecl *ActingContext,
7958 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7959 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7960 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7961 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7962 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7963 return;
7964
7965 if (ExplicitTemplateArgs ||
7968 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7969 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7970 SuppressUserConversions, PartialOverloading, PO);
7971 return;
7972 }
7973
7975 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7976 Args, SuppressUserConversions, PartialOverloading, PO);
7977}
7978
7979/// Determine whether a given function template has a simple explicit specifier
7980/// or a non-value-dependent explicit-specification that evaluates to true.
7984
7989
7991 Sema &S, OverloadCandidateSet &CandidateSet,
7993 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7994 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7996 bool AggregateCandidateDeduction) {
7997
7998 // If the function template has a non-dependent explicit specification,
7999 // exclude it now if appropriate; we are not permitted to perform deduction
8000 // and substitution in this case.
8001 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8002 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8003 Candidate.FoundDecl = FoundDecl;
8004 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8005 Candidate.Viable = false;
8006 Candidate.FailureKind = ovl_fail_explicit;
8007 return;
8008 }
8009
8010 // C++ [over.match.funcs]p7:
8011 // In each case where a candidate is a function template, candidate
8012 // function template specializations are generated using template argument
8013 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8014 // candidate functions in the usual way.113) A given name can refer to one
8015 // or more function templates and also to a set of overloaded non-template
8016 // functions. In such a case, the candidate functions generated from each
8017 // function template are combined with the set of non-template candidate
8018 // functions.
8019 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8020 FunctionTemplate->getTemplateDepth());
8021 FunctionDecl *Specialization = nullptr;
8022 ConversionSequenceList Conversions;
8024 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8025 PartialOverloading, AggregateCandidateDeduction,
8026 /*PartialOrdering=*/false,
8027 /*ObjectType=*/QualType(),
8028 /*ObjectClassification=*/Expr::Classification(),
8029 CandidateSet.getKind() ==
8031 [&](ArrayRef<QualType> ParamTypes,
8032 bool OnlyInitializeNonUserDefinedConversions) {
8033 return S.CheckNonDependentConversions(
8034 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8035 Sema::CheckNonDependentConversionsFlag(
8036 SuppressUserConversions,
8037 OnlyInitializeNonUserDefinedConversions),
8038 nullptr, QualType(), {}, PO);
8039 });
8041 OverloadCandidate &Candidate =
8042 CandidateSet.addCandidate(Conversions.size(), Conversions);
8043 Candidate.FoundDecl = FoundDecl;
8044 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8045 Candidate.Viable = false;
8046 Candidate.RewriteKind =
8047 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8048 Candidate.IsSurrogate = false;
8049 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8050 // Ignore the object argument if there is one, since we don't have an object
8051 // type.
8052 Candidate.TookAddressOfOverload =
8053 CandidateSet.getKind() ==
8055
8056 Candidate.IgnoreObjectArgument =
8057 isa<CXXMethodDecl>(Candidate.Function) &&
8058 !cast<CXXMethodDecl>(Candidate.Function)
8059 ->isExplicitObjectMemberFunction() &&
8061
8062 Candidate.ExplicitCallArguments = Args.size();
8065 else {
8067 Candidate.DeductionFailure =
8069 }
8070 return;
8071 }
8072
8073 // Add the function template specialization produced by template argument
8074 // deduction as a candidate.
8075 assert(Specialization && "Missing function template specialization?");
8077 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8078 PartialOverloading, AllowExplicit,
8079 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8080 Info.AggregateDeductionCandidateHasMismatchedArity,
8081 Info.hasStrictPackMatch());
8082}
8083
8086 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8087 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8088 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8089 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8090 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8091 return;
8092
8093 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8094
8095 if (ExplicitTemplateArgs ||
8097 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8098 DependentExplicitSpecifier)) {
8099
8101 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8102 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8103 IsADLCandidate, PO, AggregateCandidateDeduction);
8104
8105 if (DependentExplicitSpecifier)
8107 return;
8108 }
8109
8110 CandidateSet.AddDeferredTemplateCandidate(
8111 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8112 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8113 AggregateCandidateDeduction);
8114}
8115
8118 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8120 CheckNonDependentConversionsFlag UserConversionFlag,
8121 CXXRecordDecl *ActingContext, QualType ObjectType,
8122 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8123 // FIXME: The cases in which we allow explicit conversions for constructor
8124 // arguments never consider calling a constructor template. It's not clear
8125 // that is correct.
8126 const bool AllowExplicit = false;
8127
8128 bool ForOverloadSetAddressResolution =
8130 auto *FD = FunctionTemplate->getTemplatedDecl();
8131 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8132 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8134 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8135
8136 if (Conversions.empty())
8137 Conversions =
8138 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8139
8140 // Overload resolution is always an unevaluated context.
8143
8144 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8145 // require that, but this check should never result in a hard error, and
8146 // overload resolution is permitted to sidestep instantiations.
8147 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8148 !ObjectType.isNull()) {
8149 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8150 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8151 !ParamTypes[0]->isDependentType()) {
8153 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8154 Method, ActingContext, /*InOverloadResolution=*/true,
8155 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8156 : QualType());
8157 if (Conversions[ConvIdx].isBad())
8158 return true;
8159 }
8160 }
8161
8162 // A speculative workaround for self-dependent constraint bugs that manifest
8163 // after CWG2369.
8164 // FIXME: Add references to the standard once P3606 is adopted.
8165 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8166 QualType ArgType) {
8167 ParamType = ParamType.getNonReferenceType();
8168 ArgType = ArgType.getNonReferenceType();
8169 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8170 if (PointerConv) {
8171 ParamType = ParamType->getPointeeType();
8172 ArgType = ArgType->getPointeeType();
8173 }
8174
8175 if (auto *RD = ParamType->getAsCXXRecordDecl();
8176 RD && RD->hasDefinition() &&
8177 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8178 auto Info = getConstructorInfo(ND);
8179 if (!Info)
8180 return false;
8181 CXXConstructorDecl *Ctor = Info.Constructor;
8182 /// isConvertingConstructor takes copy/move constructors into
8183 /// account!
8184 return !Ctor->isCopyOrMoveConstructor() &&
8186 /*AllowExplicit=*/true);
8187 }))
8188 return true;
8189 if (auto *RD = ArgType->getAsCXXRecordDecl();
8190 RD && RD->hasDefinition() &&
8191 !RD->getVisibleConversionFunctions().empty())
8192 return true;
8193
8194 return false;
8195 };
8196
8197 unsigned Offset =
8198 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8199 : 0;
8200
8201 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8202 I != N; ++I) {
8203 QualType ParamType = ParamTypes[I + Offset];
8204 if (!ParamType->isDependentType()) {
8205 unsigned ConvIdx;
8207 ConvIdx = Args.size() - 1 - I;
8208 assert(Args.size() + ThisConversions == 2 &&
8209 "number of args (including 'this') must be exactly 2 for "
8210 "reversed order");
8211 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8212 // would also be 0. 'this' got ConvIdx = 1 previously.
8213 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8214 } else {
8215 // For members, 'this' got ConvIdx = 0 previously.
8216 ConvIdx = ThisConversions + I;
8217 }
8218 if (Conversions[ConvIdx].isInitialized())
8219 continue;
8220 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8221 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8222 continue;
8224 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8225 /*InOverloadResolution=*/true,
8226 /*AllowObjCWritebackConversion=*/
8227 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8228 if (Conversions[ConvIdx].isBad())
8229 return true;
8230 }
8231 }
8232
8233 return false;
8234}
8235
8236/// Determine whether this is an allowable conversion from the result
8237/// of an explicit conversion operator to the expected type, per C++
8238/// [over.match.conv]p1 and [over.match.ref]p1.
8239///
8240/// \param ConvType The return type of the conversion function.
8241///
8242/// \param ToType The type we are converting to.
8243///
8244/// \param AllowObjCPointerConversion Allow a conversion from one
8245/// Objective-C pointer to another.
8246///
8247/// \returns true if the conversion is allowable, false otherwise.
8249 QualType ConvType, QualType ToType,
8250 bool AllowObjCPointerConversion) {
8251 QualType ToNonRefType = ToType.getNonReferenceType();
8252
8253 // Easy case: the types are the same.
8254 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8255 return true;
8256
8257 // Allow qualification conversions.
8258 bool ObjCLifetimeConversion;
8259 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8260 ObjCLifetimeConversion))
8261 return true;
8262
8263 // If we're not allowed to consider Objective-C pointer conversions,
8264 // we're done.
8265 if (!AllowObjCPointerConversion)
8266 return false;
8267
8268 // Is this an Objective-C pointer conversion?
8269 bool IncompatibleObjC = false;
8270 QualType ConvertedType;
8271 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8272 IncompatibleObjC);
8273}
8274
8276 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8277 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8278 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8279 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8280 assert(!Conversion->getDescribedFunctionTemplate() &&
8281 "Conversion function templates use AddTemplateConversionCandidate");
8282 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8283 if (!CandidateSet.isNewCandidate(Conversion))
8284 return;
8285
8286 // If the conversion function has an undeduced return type, trigger its
8287 // deduction now.
8288 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8289 if (DeduceReturnType(Conversion, From->getExprLoc()))
8290 return;
8291 ConvType = Conversion->getConversionType().getNonReferenceType();
8292 }
8293
8294 // If we don't allow any conversion of the result type, ignore conversion
8295 // functions that don't convert to exactly (possibly cv-qualified) T.
8296 if (!AllowResultConversion &&
8297 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8298 return;
8299
8300 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8301 // operator is only a candidate if its return type is the target type or
8302 // can be converted to the target type with a qualification conversion.
8303 //
8304 // FIXME: Include such functions in the candidate list and explain why we
8305 // can't select them.
8306 if (Conversion->isExplicit() &&
8307 !isAllowableExplicitConversion(*this, ConvType, ToType,
8308 AllowObjCConversionOnExplicit))
8309 return;
8310
8311 // Overload resolution is always an unevaluated context.
8314
8315 // Add this candidate
8316 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8317 Candidate.FoundDecl = FoundDecl;
8318 Candidate.Function = Conversion;
8320 Candidate.FinalConversion.setFromType(ConvType);
8321 Candidate.FinalConversion.setAllToTypes(ToType);
8322 Candidate.HasFinalConversion = true;
8323 Candidate.Viable = true;
8324 Candidate.ExplicitCallArguments = 1;
8325 Candidate.StrictPackMatch = StrictPackMatch;
8326
8327 // Explicit functions are not actually candidates at all if we're not
8328 // allowing them in this context, but keep them around so we can point
8329 // to them in diagnostics.
8330 if (!AllowExplicit && Conversion->isExplicit()) {
8331 Candidate.Viable = false;
8332 Candidate.FailureKind = ovl_fail_explicit;
8333 return;
8334 }
8335
8336 // C++ [over.match.funcs]p4:
8337 // For conversion functions, the function is considered to be a member of
8338 // the class of the implicit implied object argument for the purpose of
8339 // defining the type of the implicit object parameter.
8340 //
8341 // Determine the implicit conversion sequence for the implicit
8342 // object parameter.
8343 QualType ObjectType = From->getType();
8344 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8345 ObjectType = FromPtrType->getPointeeType();
8346 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8347 // C++23 [over.best.ics.general]
8348 // However, if the target is [...]
8349 // - the object parameter of a user-defined conversion function
8350 // [...] user-defined conversion sequences are not considered.
8352 *this, CandidateSet.getLocation(), From->getType(),
8353 From->Classify(Context), Conversion, ConversionContext,
8354 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8355 /*SuppressUserConversion*/ true);
8356
8357 if (Candidate.Conversions[0].isBad()) {
8358 Candidate.Viable = false;
8360 return;
8361 }
8362
8363 if (Conversion->getTrailingRequiresClause()) {
8364 ConstraintSatisfaction Satisfaction;
8365 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8366 !Satisfaction.IsSatisfied) {
8367 Candidate.Viable = false;
8369 return;
8370 }
8371 }
8372
8373 // We won't go through a user-defined type conversion function to convert a
8374 // derived to base as such conversions are given Conversion Rank. They only
8375 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8376 QualType FromCanon
8377 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8378 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8379 if (FromCanon == ToCanon ||
8380 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8381 Candidate.Viable = false;
8383 return;
8384 }
8385
8386 // To determine what the conversion from the result of calling the
8387 // conversion function to the type we're eventually trying to
8388 // convert to (ToType), we need to synthesize a call to the
8389 // conversion function and attempt copy initialization from it. This
8390 // makes sure that we get the right semantics with respect to
8391 // lvalues/rvalues and the type. Fortunately, we can allocate this
8392 // call on the stack and we don't need its arguments to be
8393 // well-formed.
8394 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8395 VK_LValue, From->getBeginLoc());
8397 Context.getPointerType(Conversion->getType()),
8398 CK_FunctionToPointerDecay, &ConversionRef,
8400
8401 QualType ConversionType = Conversion->getConversionType();
8402 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8403 Candidate.Viable = false;
8405 return;
8406 }
8407
8408 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8409
8410 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8411
8412 // Introduce a temporary expression with the right type and value category
8413 // that we can use for deduction purposes.
8414 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8415
8417 TryCopyInitialization(*this, &FakeCall, ToType,
8418 /*SuppressUserConversions=*/true,
8419 /*InOverloadResolution=*/false,
8420 /*AllowObjCWritebackConversion=*/false);
8421
8422 switch (ICS.getKind()) {
8424 Candidate.FinalConversion = ICS.Standard;
8425 Candidate.HasFinalConversion = true;
8426
8427 // C++ [over.ics.user]p3:
8428 // If the user-defined conversion is specified by a specialization of a
8429 // conversion function template, the second standard conversion sequence
8430 // shall have exact match rank.
8431 if (Conversion->getPrimaryTemplate() &&
8433 Candidate.Viable = false;
8435 return;
8436 }
8437
8438 // C++0x [dcl.init.ref]p5:
8439 // In the second case, if the reference is an rvalue reference and
8440 // the second standard conversion sequence of the user-defined
8441 // conversion sequence includes an lvalue-to-rvalue conversion, the
8442 // program is ill-formed.
8443 if (ToType->isRValueReferenceType() &&
8445 Candidate.Viable = false;
8447 return;
8448 }
8449 break;
8450
8452 Candidate.Viable = false;
8454 return;
8455
8456 default:
8457 llvm_unreachable(
8458 "Can only end up with a standard conversion sequence or failure");
8459 }
8460
8461 if (EnableIfAttr *FailedAttr =
8462 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8463 Candidate.Viable = false;
8464 Candidate.FailureKind = ovl_fail_enable_if;
8465 Candidate.DeductionFailure.Data = FailedAttr;
8466 return;
8467 }
8468
8469 if (isNonViableMultiVersionOverload(Conversion)) {
8470 Candidate.Viable = false;
8472 }
8473}
8474
8476 Sema &S, OverloadCandidateSet &CandidateSet,
8478 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8479 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8480 bool AllowResultConversion) {
8481
8482 // If the function template has a non-dependent explicit specification,
8483 // exclude it now if appropriate; we are not permitted to perform deduction
8484 // and substitution in this case.
8485 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8486 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8487 Candidate.FoundDecl = FoundDecl;
8488 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8489 Candidate.Viable = false;
8490 Candidate.FailureKind = ovl_fail_explicit;
8491 return;
8492 }
8493
8494 QualType ObjectType = From->getType();
8495 Expr::Classification ObjectClassification = From->Classify(S.Context);
8496
8497 TemplateDeductionInfo Info(CandidateSet.getLocation());
8500 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8501 Specialization, Info);
8503 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8504 Candidate.FoundDecl = FoundDecl;
8505 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8506 Candidate.Viable = false;
8508 Candidate.ExplicitCallArguments = 1;
8509 Candidate.DeductionFailure =
8510 MakeDeductionFailureInfo(S.Context, Result, Info);
8511 return;
8512 }
8513
8514 // Add the conversion function template specialization produced by
8515 // template argument deduction as a candidate.
8516 assert(Specialization && "Missing function template specialization?");
8517 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8518 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8519 AllowExplicit, AllowResultConversion,
8520 Info.hasStrictPackMatch());
8521}
8522
8525 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8526 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8527 bool AllowExplicit, bool AllowResultConversion) {
8528 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8529 "Only conversion function templates permitted here");
8530
8531 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8532 return;
8533
8535 CandidateSet.getKind() ==
8539 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8540 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8541 AllowResultConversion);
8542
8544 return;
8545 }
8546
8548 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8549 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8550}
8551
8553 DeclAccessPair FoundDecl,
8554 CXXRecordDecl *ActingContext,
8555 const FunctionProtoType *Proto,
8556 Expr *Object,
8557 ArrayRef<Expr *> Args,
8558 OverloadCandidateSet& CandidateSet) {
8559 if (!CandidateSet.isNewCandidate(Conversion))
8560 return;
8561
8562 // Overload resolution is always an unevaluated context.
8565
8566 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8567 Candidate.FoundDecl = FoundDecl;
8568 Candidate.Function = nullptr;
8569 Candidate.Surrogate = Conversion;
8570 Candidate.IsSurrogate = true;
8571 Candidate.Viable = true;
8572 Candidate.ExplicitCallArguments = Args.size();
8573
8574 // Determine the implicit conversion sequence for the implicit
8575 // object parameter.
8576 ImplicitConversionSequence ObjectInit;
8577 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8578 ObjectInit = TryCopyInitialization(*this, Object,
8579 Conversion->getParamDecl(0)->getType(),
8580 /*SuppressUserConversions=*/false,
8581 /*InOverloadResolution=*/true, false);
8582 } else {
8584 *this, CandidateSet.getLocation(), Object->getType(),
8585 Object->Classify(Context), Conversion, ActingContext);
8586 }
8587
8588 if (ObjectInit.isBad()) {
8589 Candidate.Viable = false;
8591 Candidate.Conversions[0] = ObjectInit;
8592 return;
8593 }
8594
8595 // The first conversion is actually a user-defined conversion whose
8596 // first conversion is ObjectInit's standard conversion (which is
8597 // effectively a reference binding). Record it as such.
8598 Candidate.Conversions[0].setUserDefined();
8599 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8600 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8601 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8602 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8603 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8604 Candidate.Conversions[0].UserDefined.After
8605 = Candidate.Conversions[0].UserDefined.Before;
8606 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8607
8608 // Find the
8609 unsigned NumParams = Proto->getNumParams();
8610
8611 // (C++ 13.3.2p2): A candidate function having fewer than m
8612 // parameters is viable only if it has an ellipsis in its parameter
8613 // list (8.3.5).
8614 if (Args.size() > NumParams && !Proto->isVariadic()) {
8615 Candidate.Viable = false;
8617 return;
8618 }
8619
8620 // Function types don't have any default arguments, so just check if
8621 // we have enough arguments.
8622 if (Args.size() < NumParams) {
8623 // Not enough arguments.
8624 Candidate.Viable = false;
8626 return;
8627 }
8628
8629 // Determine the implicit conversion sequences for each of the
8630 // arguments.
8631 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8632 if (ArgIdx < NumParams) {
8633 // (C++ 13.3.2p3): for F to be a viable function, there shall
8634 // exist for each argument an implicit conversion sequence
8635 // (13.3.3.1) that converts that argument to the corresponding
8636 // parameter of F.
8637 QualType ParamType = Proto->getParamType(ArgIdx);
8638 Candidate.Conversions[ArgIdx + 1]
8639 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8640 /*SuppressUserConversions=*/false,
8641 /*InOverloadResolution=*/false,
8642 /*AllowObjCWritebackConversion=*/
8643 getLangOpts().ObjCAutoRefCount);
8644 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8645 Candidate.Viable = false;
8647 return;
8648 }
8649 } else {
8650 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8651 // argument for which there is no corresponding parameter is
8652 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8653 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8654 }
8655 }
8656
8657 if (Conversion->getTrailingRequiresClause()) {
8658 ConstraintSatisfaction Satisfaction;
8659 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8660 /*ForOverloadResolution*/ true) ||
8661 !Satisfaction.IsSatisfied) {
8662 Candidate.Viable = false;
8664 return;
8665 }
8666 }
8667
8668 if (EnableIfAttr *FailedAttr =
8669 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8670 Candidate.Viable = false;
8671 Candidate.FailureKind = ovl_fail_enable_if;
8672 Candidate.DeductionFailure.Data = FailedAttr;
8673 return;
8674 }
8675}
8676
8678 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8679 OverloadCandidateSet &CandidateSet,
8680 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8681 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8682 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8683 ArrayRef<Expr *> FunctionArgs = Args;
8684
8685 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8686 FunctionDecl *FD =
8687 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8688
8689 // Don't consider rewritten functions if we're not rewriting.
8690 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8691 continue;
8692
8693 assert(!isa<CXXMethodDecl>(FD) &&
8694 "unqualified operator lookup found a member function");
8695
8696 if (FunTmpl) {
8697 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8698 FunctionArgs, CandidateSet);
8699 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8700
8701 // As template candidates are not deduced immediately,
8702 // persist the array in the overload set.
8704 FunctionArgs[1], FunctionArgs[0]);
8705 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8706 Reversed, CandidateSet, false, false, true,
8707 ADLCallKind::NotADL,
8709 }
8710 } else {
8711 if (ExplicitTemplateArgs)
8712 continue;
8713 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8714 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8715 AddOverloadCandidate(FD, F.getPair(),
8716 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8717 false, false, true, false, ADLCallKind::NotADL, {},
8719 }
8720 }
8721}
8722
8724 SourceLocation OpLoc,
8725 ArrayRef<Expr *> Args,
8726 OverloadCandidateSet &CandidateSet,
8728 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8729
8730 // C++ [over.match.oper]p3:
8731 // For a unary operator @ with an operand of a type whose
8732 // cv-unqualified version is T1, and for a binary operator @ with
8733 // a left operand of a type whose cv-unqualified version is T1 and
8734 // a right operand of a type whose cv-unqualified version is T2,
8735 // three sets of candidate functions, designated member
8736 // candidates, non-member candidates and built-in candidates, are
8737 // constructed as follows:
8738 QualType T1 = Args[0]->getType();
8739
8740 // -- If T1 is a complete class type or a class currently being
8741 // defined, the set of member candidates is the result of the
8742 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8743 // the set of member candidates is empty.
8744 if (T1->isRecordType()) {
8745 bool IsComplete = isCompleteType(OpLoc, T1);
8746 auto *T1RD = T1->getAsCXXRecordDecl();
8747 // Complete the type if it can be completed.
8748 // If the type is neither complete nor being defined, bail out now.
8749 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8750 return;
8751
8752 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8753 LookupQualifiedName(Operators, T1RD);
8754 Operators.suppressAccessDiagnostics();
8755
8756 for (LookupResult::iterator Oper = Operators.begin(),
8757 OperEnd = Operators.end();
8758 Oper != OperEnd; ++Oper) {
8759 if (Oper->getAsFunction() &&
8761 !CandidateSet.getRewriteInfo().shouldAddReversed(
8762 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8763 continue;
8764 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8765 Args[0]->Classify(Context), Args.slice(1),
8766 CandidateSet, /*SuppressUserConversion=*/false, PO);
8767 }
8768 }
8769}
8770
8772 OverloadCandidateSet& CandidateSet,
8773 bool IsAssignmentOperator,
8774 unsigned NumContextualBoolArguments) {
8775 // Overload resolution is always an unevaluated context.
8778
8779 // Add this candidate
8780 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8781 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8782 Candidate.Function = nullptr;
8783 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8784
8785 // Determine the implicit conversion sequences for each of the
8786 // arguments.
8787 Candidate.Viable = true;
8788 Candidate.ExplicitCallArguments = Args.size();
8789 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8790 // C++ [over.match.oper]p4:
8791 // For the built-in assignment operators, conversions of the
8792 // left operand are restricted as follows:
8793 // -- no temporaries are introduced to hold the left operand, and
8794 // -- no user-defined conversions are applied to the left
8795 // operand to achieve a type match with the left-most
8796 // parameter of a built-in candidate.
8797 //
8798 // We block these conversions by turning off user-defined
8799 // conversions, since that is the only way that initialization of
8800 // a reference to a non-class type can occur from something that
8801 // is not of the same type.
8802 if (ArgIdx < NumContextualBoolArguments) {
8803 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8804 "Contextual conversion to bool requires bool type");
8805 Candidate.Conversions[ArgIdx]
8806 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8807 } else {
8808 Candidate.Conversions[ArgIdx]
8809 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8810 ArgIdx == 0 && IsAssignmentOperator,
8811 /*InOverloadResolution=*/false,
8812 /*AllowObjCWritebackConversion=*/
8813 getLangOpts().ObjCAutoRefCount);
8814 }
8815 if (Candidate.Conversions[ArgIdx].isBad()) {
8816 Candidate.Viable = false;
8818 break;
8819 }
8820 }
8821}
8822
8823namespace {
8824
8825/// BuiltinCandidateTypeSet - A set of types that will be used for the
8826/// candidate operator functions for built-in operators (C++
8827/// [over.built]). The types are separated into pointer types and
8828/// enumeration types.
8829class BuiltinCandidateTypeSet {
8830 /// TypeSet - A set of types.
8831 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8832
8833 /// PointerTypes - The set of pointer types that will be used in the
8834 /// built-in candidates.
8835 TypeSet PointerTypes;
8836
8837 /// MemberPointerTypes - The set of member pointer types that will be
8838 /// used in the built-in candidates.
8839 TypeSet MemberPointerTypes;
8840
8841 /// EnumerationTypes - The set of enumeration types that will be
8842 /// used in the built-in candidates.
8843 TypeSet EnumerationTypes;
8844
8845 /// The set of vector types that will be used in the built-in
8846 /// candidates.
8847 TypeSet VectorTypes;
8848
8849 /// The set of matrix types that will be used in the built-in
8850 /// candidates.
8851 TypeSet MatrixTypes;
8852
8853 /// The set of _BitInt types that will be used in the built-in candidates.
8854 TypeSet BitIntTypes;
8855
8856 /// A flag indicating non-record types are viable candidates
8857 bool HasNonRecordTypes;
8858
8859 /// A flag indicating whether either arithmetic or enumeration types
8860 /// were present in the candidate set.
8861 bool HasArithmeticOrEnumeralTypes;
8862
8863 /// A flag indicating whether the nullptr type was present in the
8864 /// candidate set.
8865 bool HasNullPtrType;
8866
8867 /// Sema - The semantic analysis instance where we are building the
8868 /// candidate type set.
8869 Sema &SemaRef;
8870
8871 /// Context - The AST context in which we will build the type sets.
8872 ASTContext &Context;
8873
8874 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8875 const Qualifiers &VisibleQuals);
8876 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8877
8878public:
8879 /// iterator - Iterates through the types that are part of the set.
8880 typedef TypeSet::iterator iterator;
8881
8882 BuiltinCandidateTypeSet(Sema &SemaRef)
8883 : HasNonRecordTypes(false),
8884 HasArithmeticOrEnumeralTypes(false),
8885 HasNullPtrType(false),
8886 SemaRef(SemaRef),
8887 Context(SemaRef.Context) { }
8888
8889 void AddTypesConvertedFrom(QualType Ty,
8890 SourceLocation Loc,
8891 bool AllowUserConversions,
8892 bool AllowExplicitConversions,
8893 const Qualifiers &VisibleTypeConversionsQuals);
8894
8895 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8896 llvm::iterator_range<iterator> member_pointer_types() {
8897 return MemberPointerTypes;
8898 }
8899 llvm::iterator_range<iterator> enumeration_types() {
8900 return EnumerationTypes;
8901 }
8902 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8903 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8904 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8905
8906 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8907 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8908 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8909 bool hasNullPtrType() const { return HasNullPtrType; }
8910};
8911
8912} // end anonymous namespace
8913
8914/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8915/// the set of pointer types along with any more-qualified variants of
8916/// that type. For example, if @p Ty is "int const *", this routine
8917/// will add "int const *", "int const volatile *", "int const
8918/// restrict *", and "int const volatile restrict *" to the set of
8919/// pointer types. Returns true if the add of @p Ty itself succeeded,
8920/// false otherwise.
8921///
8922/// FIXME: what to do about extended qualifiers?
8923bool
8924BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8925 const Qualifiers &VisibleQuals) {
8926
8927 // Insert this type.
8928 if (!PointerTypes.insert(Ty))
8929 return false;
8930
8931 QualType PointeeTy;
8932 const PointerType *PointerTy = Ty->getAs<PointerType>();
8933 bool buildObjCPtr = false;
8934 if (!PointerTy) {
8935 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8936 PointeeTy = PTy->getPointeeType();
8937 buildObjCPtr = true;
8938 } else {
8939 PointeeTy = PointerTy->getPointeeType();
8940 }
8941
8942 // Don't add qualified variants of arrays. For one, they're not allowed
8943 // (the qualifier would sink to the element type), and for another, the
8944 // only overload situation where it matters is subscript or pointer +- int,
8945 // and those shouldn't have qualifier variants anyway.
8946 if (PointeeTy->isArrayType())
8947 return true;
8948
8949 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8950 bool hasVolatile = VisibleQuals.hasVolatile();
8951 bool hasRestrict = VisibleQuals.hasRestrict();
8952
8953 // Iterate through all strict supersets of BaseCVR.
8954 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8955 if ((CVR | BaseCVR) != CVR) continue;
8956 // Skip over volatile if no volatile found anywhere in the types.
8957 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8958
8959 // Skip over restrict if no restrict found anywhere in the types, or if
8960 // the type cannot be restrict-qualified.
8961 if ((CVR & Qualifiers::Restrict) &&
8962 (!hasRestrict ||
8963 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8964 continue;
8965
8966 // Build qualified pointee type.
8967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8968
8969 // Build qualified pointer type.
8970 QualType QPointerTy;
8971 if (!buildObjCPtr)
8972 QPointerTy = Context.getPointerType(QPointeeTy);
8973 else
8974 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8975
8976 // Insert qualified pointer type.
8977 PointerTypes.insert(QPointerTy);
8978 }
8979
8980 return true;
8981}
8982
8983/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8984/// to the set of pointer types along with any more-qualified variants of
8985/// that type. For example, if @p Ty is "int const *", this routine
8986/// will add "int const *", "int const volatile *", "int const
8987/// restrict *", and "int const volatile restrict *" to the set of
8988/// pointer types. Returns true if the add of @p Ty itself succeeded,
8989/// false otherwise.
8990///
8991/// FIXME: what to do about extended qualifiers?
8992bool
8993BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8994 QualType Ty) {
8995 // Insert this type.
8996 if (!MemberPointerTypes.insert(Ty))
8997 return false;
8998
8999 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9000 assert(PointerTy && "type was not a member pointer type!");
9001
9002 QualType PointeeTy = PointerTy->getPointeeType();
9003 // Don't add qualified variants of arrays. For one, they're not allowed
9004 // (the qualifier would sink to the element type), and for another, the
9005 // only overload situation where it matters is subscript or pointer +- int,
9006 // and those shouldn't have qualifier variants anyway.
9007 if (PointeeTy->isArrayType())
9008 return true;
9009 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9010
9011 // Iterate through all strict supersets of the pointee type's CVR
9012 // qualifiers.
9013 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9014 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9015 if ((CVR | BaseCVR) != CVR) continue;
9016
9017 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9018 MemberPointerTypes.insert(Context.getMemberPointerType(
9019 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9020 }
9021
9022 return true;
9023}
9024
9025/// AddTypesConvertedFrom - Add each of the types to which the type @p
9026/// Ty can be implicit converted to the given set of @p Types. We're
9027/// primarily interested in pointer types and enumeration types. We also
9028/// take member pointer types, for the conditional operator.
9029/// AllowUserConversions is true if we should look at the conversion
9030/// functions of a class type, and AllowExplicitConversions if we
9031/// should also include the explicit conversion functions of a class
9032/// type.
9033void
9034BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9035 SourceLocation Loc,
9036 bool AllowUserConversions,
9037 bool AllowExplicitConversions,
9038 const Qualifiers &VisibleQuals) {
9039 // Only deal with canonical types.
9040 Ty = Context.getCanonicalType(Ty);
9041
9042 // Look through reference types; they aren't part of the type of an
9043 // expression for the purposes of conversions.
9044 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9045 Ty = RefTy->getPointeeType();
9046
9047 // If we're dealing with an array type, decay to the pointer.
9048 if (Ty->isArrayType())
9049 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9050
9051 // Otherwise, we don't care about qualifiers on the type.
9052 Ty = Ty.getLocalUnqualifiedType();
9053
9054 // Flag if we ever add a non-record type.
9055 bool TyIsRec = Ty->isRecordType();
9056 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9057
9058 // Flag if we encounter an arithmetic type.
9059 HasArithmeticOrEnumeralTypes =
9060 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9061
9062 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9063 PointerTypes.insert(Ty);
9064 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9065 // Insert our type, and its more-qualified variants, into the set
9066 // of types.
9067 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9068 return;
9069 } else if (Ty->isMemberPointerType()) {
9070 // Member pointers are far easier, since the pointee can't be converted.
9071 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9072 return;
9073 } else if (Ty->isEnumeralType()) {
9074 HasArithmeticOrEnumeralTypes = true;
9075 EnumerationTypes.insert(Ty);
9076 } else if (Ty->isBitIntType()) {
9077 HasArithmeticOrEnumeralTypes = true;
9078 BitIntTypes.insert(Ty);
9079 } else if (Ty->isVectorType()) {
9080 // We treat vector types as arithmetic types in many contexts as an
9081 // extension.
9082 HasArithmeticOrEnumeralTypes = true;
9083 VectorTypes.insert(Ty);
9084 } else if (Ty->isMatrixType()) {
9085 // Similar to vector types, we treat vector types as arithmetic types in
9086 // many contexts as an extension.
9087 HasArithmeticOrEnumeralTypes = true;
9088 MatrixTypes.insert(Ty);
9089 } else if (Ty->isNullPtrType()) {
9090 HasNullPtrType = true;
9091 } else if (AllowUserConversions && TyIsRec) {
9092 // No conversion functions in incomplete types.
9093 if (!SemaRef.isCompleteType(Loc, Ty))
9094 return;
9095
9096 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9097 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9098 if (isa<UsingShadowDecl>(D))
9099 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9100
9101 // Skip conversion function templates; they don't tell us anything
9102 // about which builtin types we can convert to.
9104 continue;
9105
9106 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9107 if (AllowExplicitConversions || !Conv->isExplicit()) {
9108 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9109 VisibleQuals);
9110 }
9111 }
9112 }
9113}
9114/// Helper function for adjusting address spaces for the pointer or reference
9115/// operands of builtin operators depending on the argument.
9120
9121/// Helper function for AddBuiltinOperatorCandidates() that adds
9122/// the volatile- and non-volatile-qualified assignment operators for the
9123/// given type to the candidate set.
9125 QualType T,
9126 ArrayRef<Expr *> Args,
9127 OverloadCandidateSet &CandidateSet) {
9128 QualType ParamTypes[2];
9129
9130 // T& operator=(T&, T)
9131 ParamTypes[0] = S.Context.getLValueReferenceType(
9133 ParamTypes[1] = T;
9134 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9135 /*IsAssignmentOperator=*/true);
9136
9138 // volatile T& operator=(volatile T&, T)
9139 ParamTypes[0] = S.Context.getLValueReferenceType(
9141 Args[0]));
9142 ParamTypes[1] = T;
9143 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9144 /*IsAssignmentOperator=*/true);
9145 }
9146}
9147
9148/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9149/// if any, found in visible type conversion functions found in ArgExpr's type.
9150static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9151 Qualifiers VRQuals;
9152 CXXRecordDecl *ClassDecl;
9153 if (const MemberPointerType *RHSMPType =
9154 ArgExpr->getType()->getAs<MemberPointerType>())
9155 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9156 else
9157 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9158 if (!ClassDecl) {
9159 // Just to be safe, assume the worst case.
9160 VRQuals.addVolatile();
9161 VRQuals.addRestrict();
9162 return VRQuals;
9163 }
9164 if (!ClassDecl->hasDefinition())
9165 return VRQuals;
9166
9167 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9168 if (isa<UsingShadowDecl>(D))
9169 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9170 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9171 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9172 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9173 CanTy = ResTypeRef->getPointeeType();
9174 // Need to go down the pointer/mempointer chain and add qualifiers
9175 // as see them.
9176 bool done = false;
9177 while (!done) {
9178 if (CanTy.isRestrictQualified())
9179 VRQuals.addRestrict();
9180 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9181 CanTy = ResTypePtr->getPointeeType();
9182 else if (const MemberPointerType *ResTypeMPtr =
9183 CanTy->getAs<MemberPointerType>())
9184 CanTy = ResTypeMPtr->getPointeeType();
9185 else
9186 done = true;
9187 if (CanTy.isVolatileQualified())
9188 VRQuals.addVolatile();
9189 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9190 return VRQuals;
9191 }
9192 }
9193 }
9194 return VRQuals;
9195}
9196
9197// Note: We're currently only handling qualifiers that are meaningful for the
9198// LHS of compound assignment overloading.
9200 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9201 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9202 // _Atomic
9203 if (Available.hasAtomic()) {
9204 Available.removeAtomic();
9205 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9206 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9207 return;
9208 }
9209
9210 // volatile
9211 if (Available.hasVolatile()) {
9212 Available.removeVolatile();
9213 assert(!Applied.hasVolatile());
9214 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9215 Callback);
9216 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9217 return;
9218 }
9219
9220 Callback(Applied);
9221}
9222
9224 QualifiersAndAtomic Quals,
9225 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9227 Callback);
9228}
9229
9231 QualifiersAndAtomic Quals,
9232 Sema &S) {
9233 if (Quals.hasAtomic())
9235 if (Quals.hasVolatile())
9238}
9239
9240namespace {
9241
9242/// Helper class to manage the addition of builtin operator overload
9243/// candidates. It provides shared state and utility methods used throughout
9244/// the process, as well as a helper method to add each group of builtin
9245/// operator overloads from the standard to a candidate set.
9246class BuiltinOperatorOverloadBuilder {
9247 // Common instance state available to all overload candidate addition methods.
9248 Sema &S;
9249 ArrayRef<Expr *> Args;
9250 QualifiersAndAtomic VisibleTypeConversionsQuals;
9251 bool HasArithmeticOrEnumeralCandidateType;
9252 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9253 OverloadCandidateSet &CandidateSet;
9254
9255 static constexpr int ArithmeticTypesCap = 26;
9256 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9257
9258 // Define some indices used to iterate over the arithmetic types in
9259 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9260 // types are that preserved by promotion (C++ [over.built]p2).
9261 unsigned FirstIntegralType,
9262 LastIntegralType;
9263 unsigned FirstPromotedIntegralType,
9264 LastPromotedIntegralType;
9265 unsigned FirstPromotedArithmeticType,
9266 LastPromotedArithmeticType;
9267 unsigned NumArithmeticTypes;
9268
9269 void InitArithmeticTypes() {
9270 // Start of promoted types.
9271 FirstPromotedArithmeticType = 0;
9272 ArithmeticTypes.push_back(S.Context.FloatTy);
9273 ArithmeticTypes.push_back(S.Context.DoubleTy);
9274 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9276 ArithmeticTypes.push_back(S.Context.Float128Ty);
9278 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9279
9280 // Start of integral types.
9281 FirstIntegralType = ArithmeticTypes.size();
9282 FirstPromotedIntegralType = ArithmeticTypes.size();
9283 ArithmeticTypes.push_back(S.Context.IntTy);
9284 ArithmeticTypes.push_back(S.Context.LongTy);
9285 ArithmeticTypes.push_back(S.Context.LongLongTy);
9289 ArithmeticTypes.push_back(S.Context.Int128Ty);
9290 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9291 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9292 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9296 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9297
9298 /// We add candidates for the unique, unqualified _BitInt types present in
9299 /// the candidate type set. The candidate set already handled ensuring the
9300 /// type is unqualified and canonical, but because we're adding from N
9301 /// different sets, we need to do some extra work to unique things. Insert
9302 /// the candidates into a unique set, then move from that set into the list
9303 /// of arithmetic types.
9304 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9305 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9306 for (QualType BitTy : Candidate.bitint_types())
9307 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9308 }
9309 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9310 LastPromotedIntegralType = ArithmeticTypes.size();
9311 LastPromotedArithmeticType = ArithmeticTypes.size();
9312 // End of promoted types.
9313
9314 ArithmeticTypes.push_back(S.Context.BoolTy);
9315 ArithmeticTypes.push_back(S.Context.CharTy);
9316 ArithmeticTypes.push_back(S.Context.WCharTy);
9317 if (S.Context.getLangOpts().Char8)
9318 ArithmeticTypes.push_back(S.Context.Char8Ty);
9319 ArithmeticTypes.push_back(S.Context.Char16Ty);
9320 ArithmeticTypes.push_back(S.Context.Char32Ty);
9321 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9322 ArithmeticTypes.push_back(S.Context.ShortTy);
9323 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9324 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9325 LastIntegralType = ArithmeticTypes.size();
9326 NumArithmeticTypes = ArithmeticTypes.size();
9327 // End of integral types.
9328 // FIXME: What about complex? What about half?
9329
9330 // We don't know for sure how many bit-precise candidates were involved, so
9331 // we subtract those from the total when testing whether we're under the
9332 // cap or not.
9333 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9334 ArithmeticTypesCap &&
9335 "Enough inline storage for all arithmetic types.");
9336 }
9337
9338 /// Helper method to factor out the common pattern of adding overloads
9339 /// for '++' and '--' builtin operators.
9340 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9341 bool HasVolatile,
9342 bool HasRestrict) {
9343 QualType ParamTypes[2] = {
9344 S.Context.getLValueReferenceType(CandidateTy),
9345 S.Context.IntTy
9346 };
9347
9348 // Non-volatile version.
9349 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9350
9351 // Use a heuristic to reduce number of builtin candidates in the set:
9352 // add volatile version only if there are conversions to a volatile type.
9353 if (HasVolatile) {
9354 ParamTypes[0] =
9356 S.Context.getVolatileType(CandidateTy));
9357 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9358 }
9359
9360 // Add restrict version only if there are conversions to a restrict type
9361 // and our candidate type is a non-restrict-qualified pointer.
9362 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9363 !CandidateTy.isRestrictQualified()) {
9364 ParamTypes[0]
9367 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9368
9369 if (HasVolatile) {
9370 ParamTypes[0]
9372 S.Context.getCVRQualifiedType(CandidateTy,
9375 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9376 }
9377 }
9378
9379 }
9380
9381 /// Helper to add an overload candidate for a binary builtin with types \p L
9382 /// and \p R.
9383 void AddCandidate(QualType L, QualType R) {
9384 QualType LandR[2] = {L, R};
9385 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9386 }
9387
9388public:
9389 BuiltinOperatorOverloadBuilder(
9390 Sema &S, ArrayRef<Expr *> Args,
9391 QualifiersAndAtomic VisibleTypeConversionsQuals,
9392 bool HasArithmeticOrEnumeralCandidateType,
9393 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9394 OverloadCandidateSet &CandidateSet)
9395 : S(S), Args(Args),
9396 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9397 HasArithmeticOrEnumeralCandidateType(
9398 HasArithmeticOrEnumeralCandidateType),
9399 CandidateTypes(CandidateTypes),
9400 CandidateSet(CandidateSet) {
9401
9402 InitArithmeticTypes();
9403 }
9404
9405 // Increment is deprecated for bool since C++17.
9406 //
9407 // C++ [over.built]p3:
9408 //
9409 // For every pair (T, VQ), where T is an arithmetic type other
9410 // than bool, and VQ is either volatile or empty, there exist
9411 // candidate operator functions of the form
9412 //
9413 // VQ T& operator++(VQ T&);
9414 // T operator++(VQ T&, int);
9415 //
9416 // C++ [over.built]p4:
9417 //
9418 // For every pair (T, VQ), where T is an arithmetic type other
9419 // than bool, and VQ is either volatile or empty, there exist
9420 // candidate operator functions of the form
9421 //
9422 // VQ T& operator--(VQ T&);
9423 // T operator--(VQ T&, int);
9424 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9425 if (!HasArithmeticOrEnumeralCandidateType)
9426 return;
9427
9428 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9429 const auto TypeOfT = ArithmeticTypes[Arith];
9430 if (TypeOfT == S.Context.BoolTy) {
9431 if (Op == OO_MinusMinus)
9432 continue;
9433 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9434 continue;
9435 }
9436 addPlusPlusMinusMinusStyleOverloads(
9437 TypeOfT,
9438 VisibleTypeConversionsQuals.hasVolatile(),
9439 VisibleTypeConversionsQuals.hasRestrict());
9440 }
9441 }
9442
9443 // C++ [over.built]p5:
9444 //
9445 // For every pair (T, VQ), where T is a cv-qualified or
9446 // cv-unqualified object type, and VQ is either volatile or
9447 // empty, there exist candidate operator functions of the form
9448 //
9449 // T*VQ& operator++(T*VQ&);
9450 // T*VQ& operator--(T*VQ&);
9451 // T* operator++(T*VQ&, int);
9452 // T* operator--(T*VQ&, int);
9453 void addPlusPlusMinusMinusPointerOverloads() {
9454 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9455 // Skip pointer types that aren't pointers to object types.
9456 if (!PtrTy->getPointeeType()->isObjectType())
9457 continue;
9458
9459 addPlusPlusMinusMinusStyleOverloads(
9460 PtrTy,
9461 (!PtrTy.isVolatileQualified() &&
9462 VisibleTypeConversionsQuals.hasVolatile()),
9463 (!PtrTy.isRestrictQualified() &&
9464 VisibleTypeConversionsQuals.hasRestrict()));
9465 }
9466 }
9467
9468 // C++ [over.built]p6:
9469 // For every cv-qualified or cv-unqualified object type T, there
9470 // exist candidate operator functions of the form
9471 //
9472 // T& operator*(T*);
9473 //
9474 // C++ [over.built]p7:
9475 // For every function type T that does not have cv-qualifiers or a
9476 // ref-qualifier, there exist candidate operator functions of the form
9477 // T& operator*(T*);
9478 void addUnaryStarPointerOverloads() {
9479 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9480 QualType PointeeTy = ParamTy->getPointeeType();
9481 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9482 continue;
9483
9484 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9485 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9486 continue;
9487
9488 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9489 }
9490 }
9491
9492 // C++ [over.built]p9:
9493 // For every promoted arithmetic type T, there exist candidate
9494 // operator functions of the form
9495 //
9496 // T operator+(T);
9497 // T operator-(T);
9498 void addUnaryPlusOrMinusArithmeticOverloads() {
9499 if (!HasArithmeticOrEnumeralCandidateType)
9500 return;
9501
9502 for (unsigned Arith = FirstPromotedArithmeticType;
9503 Arith < LastPromotedArithmeticType; ++Arith) {
9504 QualType ArithTy = ArithmeticTypes[Arith];
9505 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9506 }
9507
9508 // Extension: We also add these operators for vector types.
9509 for (QualType VecTy : CandidateTypes[0].vector_types())
9510 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9511 }
9512
9513 // C++ [over.built]p8:
9514 // For every type T, there exist candidate operator functions of
9515 // the form
9516 //
9517 // T* operator+(T*);
9518 void addUnaryPlusPointerOverloads() {
9519 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9520 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9521 }
9522
9523 // C++ [over.built]p10:
9524 // For every promoted integral type T, there exist candidate
9525 // operator functions of the form
9526 //
9527 // T operator~(T);
9528 void addUnaryTildePromotedIntegralOverloads() {
9529 if (!HasArithmeticOrEnumeralCandidateType)
9530 return;
9531
9532 for (unsigned Int = FirstPromotedIntegralType;
9533 Int < LastPromotedIntegralType; ++Int) {
9534 QualType IntTy = ArithmeticTypes[Int];
9535 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9536 }
9537
9538 // Extension: We also add this operator for vector types.
9539 for (QualType VecTy : CandidateTypes[0].vector_types())
9540 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9541 }
9542
9543 // C++ [over.match.oper]p16:
9544 // For every pointer to member type T or type std::nullptr_t, there
9545 // exist candidate operator functions of the form
9546 //
9547 // bool operator==(T,T);
9548 // bool operator!=(T,T);
9549 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9550 /// Set of (canonical) types that we've already handled.
9551 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9552
9553 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9554 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9555 // Don't add the same builtin candidate twice.
9556 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9557 continue;
9558
9559 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9560 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9561 }
9562
9563 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9565 if (AddedTypes.insert(NullPtrTy).second) {
9566 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9568 }
9569 }
9570 }
9571 }
9572
9573 // C++ [over.built]p15:
9574 //
9575 // For every T, where T is an enumeration type or a pointer type,
9576 // there exist candidate operator functions of the form
9577 //
9578 // bool operator<(T, T);
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 // R operator<=>(T, T)
9585 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9586 // C++ [over.match.oper]p3:
9587 // [...]the built-in candidates include all of the candidate operator
9588 // functions defined in 13.6 that, compared to the given operator, [...]
9589 // do not have the same parameter-type-list as any non-template non-member
9590 // candidate.
9591 //
9592 // Note that in practice, this only affects enumeration types because there
9593 // aren't any built-in candidates of record type, and a user-defined operator
9594 // must have an operand of record or enumeration type. Also, the only other
9595 // overloaded operator with enumeration arguments, operator=,
9596 // cannot be overloaded for enumeration types, so this is the only place
9597 // where we must suppress candidates like this.
9598 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9599 UserDefinedBinaryOperators;
9600
9601 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9602 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9603 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9604 CEnd = CandidateSet.end();
9605 C != CEnd; ++C) {
9606 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9607 continue;
9608
9609 if (C->Function->isFunctionTemplateSpecialization())
9610 continue;
9611
9612 // We interpret "same parameter-type-list" as applying to the
9613 // "synthesized candidate, with the order of the two parameters
9614 // reversed", not to the original function.
9615 bool Reversed = C->isReversed();
9616 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9617 ->getType()
9618 .getUnqualifiedType();
9619 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9620 ->getType()
9621 .getUnqualifiedType();
9622
9623 // Skip if either parameter isn't of enumeral type.
9624 if (!FirstParamType->isEnumeralType() ||
9625 !SecondParamType->isEnumeralType())
9626 continue;
9627
9628 // Add this operator to the set of known user-defined operators.
9629 UserDefinedBinaryOperators.insert(
9630 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9631 S.Context.getCanonicalType(SecondParamType)));
9632 }
9633 }
9634 }
9635
9636 /// Set of (canonical) types that we've already handled.
9637 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9638
9639 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9640 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9641 // Don't add the same builtin candidate twice.
9642 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9643 continue;
9644 if (IsSpaceship && PtrTy->isFunctionPointerType())
9645 continue;
9646
9647 QualType ParamTypes[2] = {PtrTy, PtrTy};
9648 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9649 }
9650 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9651 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9652
9653 // Don't add the same builtin candidate twice, or if a user defined
9654 // candidate exists.
9655 if (!AddedTypes.insert(CanonType).second ||
9656 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9657 CanonType)))
9658 continue;
9659 QualType ParamTypes[2] = {EnumTy, EnumTy};
9660 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9661 }
9662 }
9663 }
9664
9665 // C++ [over.built]p13:
9666 //
9667 // For every cv-qualified or cv-unqualified object type T
9668 // there exist candidate operator functions of the form
9669 //
9670 // T* operator+(T*, ptrdiff_t);
9671 // T& operator[](T*, ptrdiff_t); [BELOW]
9672 // T* operator-(T*, ptrdiff_t);
9673 // T* operator+(ptrdiff_t, T*);
9674 // T& operator[](ptrdiff_t, T*); [BELOW]
9675 //
9676 // C++ [over.built]p14:
9677 //
9678 // For every T, where T is a pointer to object type, there
9679 // exist candidate operator functions of the form
9680 //
9681 // ptrdiff_t operator-(T, T);
9682 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9683 /// Set of (canonical) types that we've already handled.
9684 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9685
9686 for (int Arg = 0; Arg < 2; ++Arg) {
9687 QualType AsymmetricParamTypes[2] = {
9690 };
9691 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9692 QualType PointeeTy = PtrTy->getPointeeType();
9693 if (!PointeeTy->isObjectType())
9694 continue;
9695
9696 AsymmetricParamTypes[Arg] = PtrTy;
9697 if (Arg == 0 || Op == OO_Plus) {
9698 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9699 // T* operator+(ptrdiff_t, T*);
9700 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9701 }
9702 if (Op == OO_Minus) {
9703 // ptrdiff_t operator-(T, T);
9704 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9705 continue;
9706
9707 QualType ParamTypes[2] = {PtrTy, PtrTy};
9708 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9709 }
9710 }
9711 }
9712 }
9713
9714 // C++ [over.built]p12:
9715 //
9716 // For every pair of promoted arithmetic types L and R, there
9717 // exist candidate operator functions of the form
9718 //
9719 // LR operator*(L, R);
9720 // LR operator/(L, R);
9721 // LR operator+(L, R);
9722 // LR operator-(L, R);
9723 // bool 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 //
9730 // where LR is the result of the usual arithmetic conversions
9731 // between types L and R.
9732 //
9733 // C++ [over.built]p24:
9734 //
9735 // For every pair of promoted arithmetic types L and R, there exist
9736 // candidate operator functions of the form
9737 //
9738 // LR operator?(bool, L, R);
9739 //
9740 // where LR is the result of the usual arithmetic conversions
9741 // between types L and R.
9742 // Our candidates ignore the first parameter.
9743 void addGenericBinaryArithmeticOverloads() {
9744 if (!HasArithmeticOrEnumeralCandidateType)
9745 return;
9746
9747 for (unsigned Left = FirstPromotedArithmeticType;
9748 Left < LastPromotedArithmeticType; ++Left) {
9749 for (unsigned Right = FirstPromotedArithmeticType;
9750 Right < LastPromotedArithmeticType; ++Right) {
9751 QualType LandR[2] = { ArithmeticTypes[Left],
9752 ArithmeticTypes[Right] };
9753 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9754 }
9755 }
9756
9757 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9758 // conditional operator for vector types.
9759 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9760 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9761 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9762 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9763 }
9764 }
9765
9766 /// Add binary operator overloads for each candidate matrix type M1, M2:
9767 /// * (M1, M1) -> M1
9768 /// * (M1, M1.getElementType()) -> M1
9769 /// * (M2.getElementType(), M2) -> M2
9770 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9771 void addMatrixBinaryArithmeticOverloads() {
9772 if (!HasArithmeticOrEnumeralCandidateType)
9773 return;
9774
9775 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9776 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9777 AddCandidate(M1, M1);
9778 }
9779
9780 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9781 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9782 if (!CandidateTypes[0].containsMatrixType(M2))
9783 AddCandidate(M2, M2);
9784 }
9785 }
9786
9787 // C++2a [over.built]p14:
9788 //
9789 // For every integral type T there exists a candidate operator function
9790 // of the form
9791 //
9792 // std::strong_ordering operator<=>(T, T)
9793 //
9794 // C++2a [over.built]p15:
9795 //
9796 // For every pair of floating-point types L and R, there exists a candidate
9797 // operator function of the form
9798 //
9799 // std::partial_ordering operator<=>(L, R);
9800 //
9801 // FIXME: The current specification for integral types doesn't play nice with
9802 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9803 // comparisons. Under the current spec this can lead to ambiguity during
9804 // overload resolution. For example:
9805 //
9806 // enum A : int {a};
9807 // auto x = (a <=> (long)42);
9808 //
9809 // error: call is ambiguous for arguments 'A' and 'long'.
9810 // note: candidate operator<=>(int, int)
9811 // note: candidate operator<=>(long, long)
9812 //
9813 // To avoid this error, this function deviates from the specification and adds
9814 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9815 // arithmetic types (the same as the generic relational overloads).
9816 //
9817 // For now this function acts as a placeholder.
9818 void addThreeWayArithmeticOverloads() {
9819 addGenericBinaryArithmeticOverloads();
9820 }
9821
9822 // C++ [over.built]p17:
9823 //
9824 // For every pair of promoted integral types L and R, there
9825 // exist candidate operator functions of the form
9826 //
9827 // LR operator%(L, R);
9828 // LR operator&(L, R);
9829 // LR operator^(L, R);
9830 // LR operator|(L, R);
9831 // L operator<<(L, R);
9832 // L operator>>(L, R);
9833 //
9834 // where LR is the result of the usual arithmetic conversions
9835 // between types L and R.
9836 void addBinaryBitwiseArithmeticOverloads() {
9837 if (!HasArithmeticOrEnumeralCandidateType)
9838 return;
9839
9840 for (unsigned Left = FirstPromotedIntegralType;
9841 Left < LastPromotedIntegralType; ++Left) {
9842 for (unsigned Right = FirstPromotedIntegralType;
9843 Right < LastPromotedIntegralType; ++Right) {
9844 QualType LandR[2] = { ArithmeticTypes[Left],
9845 ArithmeticTypes[Right] };
9846 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9847 }
9848 }
9849 }
9850
9851 // C++ [over.built]p20:
9852 //
9853 // For every pair (T, VQ), where T is an enumeration or
9854 // pointer to member type and VQ is either volatile or
9855 // empty, there exist candidate operator functions of the form
9856 //
9857 // VQ T& operator=(VQ T&, T);
9858 void addAssignmentMemberPointerOrEnumeralOverloads() {
9859 /// Set of (canonical) types that we've already handled.
9860 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9861
9862 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9863 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9864 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9865 continue;
9866
9867 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9868 }
9869
9870 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9871 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9872 continue;
9873
9874 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9875 }
9876 }
9877 }
9878
9879 // C++ [over.built]p19:
9880 //
9881 // For every pair (T, VQ), where T is any type and VQ is either
9882 // volatile or empty, there exist candidate operator functions
9883 // of the form
9884 //
9885 // T*VQ& operator=(T*VQ&, T*);
9886 //
9887 // C++ [over.built]p21:
9888 //
9889 // For every pair (T, VQ), where T is a cv-qualified or
9890 // cv-unqualified object type and VQ is either volatile or
9891 // empty, there exist candidate operator functions of the form
9892 //
9893 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9894 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9895 void addAssignmentPointerOverloads(bool isEqualOp) {
9896 /// Set of (canonical) types that we've already handled.
9897 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9898
9899 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9900 // If this is operator=, keep track of the builtin candidates we added.
9901 if (isEqualOp)
9902 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9903 else if (!PtrTy->getPointeeType()->isObjectType())
9904 continue;
9905
9906 // non-volatile version
9907 QualType ParamTypes[2] = {
9909 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9910 };
9911 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9912 /*IsAssignmentOperator=*/ isEqualOp);
9913
9914 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9915 VisibleTypeConversionsQuals.hasVolatile();
9916 if (NeedVolatile) {
9917 // volatile version
9918 ParamTypes[0] =
9920 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9921 /*IsAssignmentOperator=*/isEqualOp);
9922 }
9923
9924 if (!PtrTy.isRestrictQualified() &&
9925 VisibleTypeConversionsQuals.hasRestrict()) {
9926 // restrict version
9927 ParamTypes[0] =
9929 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9930 /*IsAssignmentOperator=*/isEqualOp);
9931
9932 if (NeedVolatile) {
9933 // volatile restrict version
9934 ParamTypes[0] =
9937 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9938 /*IsAssignmentOperator=*/isEqualOp);
9939 }
9940 }
9941 }
9942
9943 if (isEqualOp) {
9944 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9945 // Make sure we don't add the same candidate twice.
9946 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9947 continue;
9948
9949 QualType ParamTypes[2] = {
9951 PtrTy,
9952 };
9953
9954 // non-volatile version
9955 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9956 /*IsAssignmentOperator=*/true);
9957
9958 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9959 VisibleTypeConversionsQuals.hasVolatile();
9960 if (NeedVolatile) {
9961 // volatile version
9962 ParamTypes[0] = S.Context.getLValueReferenceType(
9963 S.Context.getVolatileType(PtrTy));
9964 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9965 /*IsAssignmentOperator=*/true);
9966 }
9967
9968 if (!PtrTy.isRestrictQualified() &&
9969 VisibleTypeConversionsQuals.hasRestrict()) {
9970 // restrict version
9971 ParamTypes[0] = S.Context.getLValueReferenceType(
9972 S.Context.getRestrictType(PtrTy));
9973 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9974 /*IsAssignmentOperator=*/true);
9975
9976 if (NeedVolatile) {
9977 // volatile restrict version
9978 ParamTypes[0] =
9981 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9982 /*IsAssignmentOperator=*/true);
9983 }
9984 }
9985 }
9986 }
9987 }
9988
9989 // C++ [over.built]p18:
9990 //
9991 // For every triple (L, VQ, R), where L is an arithmetic type,
9992 // VQ is either volatile or empty, and R is a promoted
9993 // arithmetic type, there exist candidate operator functions of
9994 // the form
9995 //
9996 // VQ L& operator=(VQ L&, R);
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 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10002 if (!HasArithmeticOrEnumeralCandidateType)
10003 return;
10004
10005 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10006 for (unsigned Right = FirstPromotedArithmeticType;
10007 Right < LastPromotedArithmeticType; ++Right) {
10008 QualType ParamTypes[2];
10009 ParamTypes[1] = ArithmeticTypes[Right];
10011 S, ArithmeticTypes[Left], Args[0]);
10012
10014 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10015 ParamTypes[0] =
10016 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10018 /*IsAssignmentOperator=*/isEqualOp);
10019 });
10020 }
10021 }
10022
10023 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10024 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10025 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10026 QualType ParamTypes[2];
10027 ParamTypes[1] = Vec2Ty;
10028 // Add this built-in operator as a candidate (VQ is empty).
10029 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10030 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10031 /*IsAssignmentOperator=*/isEqualOp);
10032
10033 // Add this built-in operator as a candidate (VQ is 'volatile').
10034 if (VisibleTypeConversionsQuals.hasVolatile()) {
10035 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10036 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10037 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10038 /*IsAssignmentOperator=*/isEqualOp);
10039 }
10040 }
10041 }
10042
10043 // C++ [over.built]p22:
10044 //
10045 // For every triple (L, VQ, R), where L is an integral type, VQ
10046 // is either volatile or empty, and R is a promoted integral
10047 // type, there exist candidate operator functions of the form
10048 //
10049 // VQ L& operator%=(VQ L&, R);
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 void addAssignmentIntegralOverloads() {
10056 if (!HasArithmeticOrEnumeralCandidateType)
10057 return;
10058
10059 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10060 for (unsigned Right = FirstPromotedIntegralType;
10061 Right < LastPromotedIntegralType; ++Right) {
10062 QualType ParamTypes[2];
10063 ParamTypes[1] = ArithmeticTypes[Right];
10065 S, ArithmeticTypes[Left], Args[0]);
10066
10068 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10069 ParamTypes[0] =
10070 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10071 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10072 });
10073 }
10074 }
10075 }
10076
10077 // C++ [over.operator]p23:
10078 //
10079 // There also exist candidate operator functions of the form
10080 //
10081 // bool operator!(bool);
10082 // bool operator&&(bool, bool);
10083 // bool operator||(bool, bool);
10084 void addExclaimOverload() {
10085 QualType ParamTy = S.Context.BoolTy;
10086 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10087 /*IsAssignmentOperator=*/false,
10088 /*NumContextualBoolArguments=*/1);
10089 }
10090 void addAmpAmpOrPipePipeOverload() {
10091 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10092 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10093 /*IsAssignmentOperator=*/false,
10094 /*NumContextualBoolArguments=*/2);
10095 }
10096
10097 // C++ [over.built]p13:
10098 //
10099 // For every cv-qualified or cv-unqualified object type T there
10100 // exist candidate operator functions of the form
10101 //
10102 // T* operator+(T*, ptrdiff_t); [ABOVE]
10103 // T& operator[](T*, ptrdiff_t);
10104 // T* operator-(T*, ptrdiff_t); [ABOVE]
10105 // T* operator+(ptrdiff_t, T*); [ABOVE]
10106 // T& operator[](ptrdiff_t, T*);
10107 void addSubscriptOverloads() {
10108 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10109 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10110 QualType PointeeType = PtrTy->getPointeeType();
10111 if (!PointeeType->isObjectType())
10112 continue;
10113
10114 // T& operator[](T*, ptrdiff_t)
10115 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10116 }
10117
10118 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10119 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10120 QualType PointeeType = PtrTy->getPointeeType();
10121 if (!PointeeType->isObjectType())
10122 continue;
10123
10124 // T& operator[](ptrdiff_t, T*)
10125 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10126 }
10127 }
10128
10129 // C++ [over.built]p11:
10130 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10131 // C1 is the same type as C2 or is a derived class of C2, T is an object
10132 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10133 // there exist candidate operator functions of the form
10134 //
10135 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10136 //
10137 // where CV12 is the union of CV1 and CV2.
10138 void addArrowStarOverloads() {
10139 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10140 QualType C1Ty = PtrTy;
10141 QualType C1;
10142 QualifierCollector Q1;
10143 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10144 if (!isa<RecordType>(C1))
10145 continue;
10146 // heuristic to reduce number of builtin candidates in the set.
10147 // Add volatile/restrict version only if there are conversions to a
10148 // volatile/restrict type.
10149 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10150 continue;
10151 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10152 continue;
10153 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10154 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10155 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10156 *D2 = mptr->getMostRecentCXXRecordDecl();
10157 if (!declaresSameEntity(D1, D2) &&
10158 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10159 break;
10160 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10161 // build CV12 T&
10162 QualType T = mptr->getPointeeType();
10163 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10164 T.isVolatileQualified())
10165 continue;
10166 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10167 T.isRestrictQualified())
10168 continue;
10169 T = Q1.apply(S.Context, T);
10170 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10171 }
10172 }
10173 }
10174
10175 // Note that we don't consider the first argument, since it has been
10176 // contextually converted to bool long ago. The candidates below are
10177 // therefore added as binary.
10178 //
10179 // C++ [over.built]p25:
10180 // For every type T, where T is a pointer, pointer-to-member, or scoped
10181 // enumeration type, there exist candidate operator functions of the form
10182 //
10183 // T operator?(bool, T, T);
10184 //
10185 void addConditionalOperatorOverloads() {
10186 /// Set of (canonical) types that we've already handled.
10187 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10188
10189 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10190 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10191 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10192 continue;
10193
10194 QualType ParamTypes[2] = {PtrTy, PtrTy};
10195 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10196 }
10197
10198 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10199 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10200 continue;
10201
10202 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10203 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10204 }
10205
10206 if (S.getLangOpts().CPlusPlus11) {
10207 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10208 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10209 continue;
10210
10211 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10212 continue;
10213
10214 QualType ParamTypes[2] = {EnumTy, EnumTy};
10215 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10216 }
10217 }
10218 }
10219 }
10220};
10221
10222} // end anonymous namespace
10223
10225 SourceLocation OpLoc,
10226 ArrayRef<Expr *> Args,
10227 OverloadCandidateSet &CandidateSet) {
10228 // Find all of the types that the arguments can convert to, but only
10229 // if the operator we're looking at has built-in operator candidates
10230 // that make use of these types. Also record whether we encounter non-record
10231 // candidate types or either arithmetic or enumeral candidate types.
10232 QualifiersAndAtomic VisibleTypeConversionsQuals;
10233 VisibleTypeConversionsQuals.addConst();
10234 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10235 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10236 if (Args[ArgIdx]->getType()->isAtomicType())
10237 VisibleTypeConversionsQuals.addAtomic();
10238 }
10239
10240 bool HasNonRecordCandidateType = false;
10241 bool HasArithmeticOrEnumeralCandidateType = false;
10243 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10244 CandidateTypes.emplace_back(*this);
10245 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10246 OpLoc,
10247 true,
10248 (Op == OO_Exclaim ||
10249 Op == OO_AmpAmp ||
10250 Op == OO_PipePipe),
10251 VisibleTypeConversionsQuals);
10252 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10253 CandidateTypes[ArgIdx].hasNonRecordTypes();
10254 HasArithmeticOrEnumeralCandidateType =
10255 HasArithmeticOrEnumeralCandidateType ||
10256 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10257 }
10258
10259 // Exit early when no non-record types have been added to the candidate set
10260 // for any of the arguments to the operator.
10261 //
10262 // We can't exit early for !, ||, or &&, since there we have always have
10263 // 'bool' overloads.
10264 if (!HasNonRecordCandidateType &&
10265 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10266 return;
10267
10268 // Setup an object to manage the common state for building overloads.
10269 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10270 VisibleTypeConversionsQuals,
10271 HasArithmeticOrEnumeralCandidateType,
10272 CandidateTypes, CandidateSet);
10273
10274 // Dispatch over the operation to add in only those overloads which apply.
10275 switch (Op) {
10276 case OO_None:
10278 llvm_unreachable("Expected an overloaded operator");
10279
10280 case OO_New:
10281 case OO_Delete:
10282 case OO_Array_New:
10283 case OO_Array_Delete:
10284 case OO_Call:
10285 llvm_unreachable(
10286 "Special operators don't use AddBuiltinOperatorCandidates");
10287
10288 case OO_Comma:
10289 case OO_Arrow:
10290 case OO_Coawait:
10291 // C++ [over.match.oper]p3:
10292 // -- For the operator ',', the unary operator '&', the
10293 // operator '->', or the operator 'co_await', the
10294 // built-in candidates set is empty.
10295 break;
10296
10297 case OO_Plus: // '+' is either unary or binary
10298 if (Args.size() == 1)
10299 OpBuilder.addUnaryPlusPointerOverloads();
10300 [[fallthrough]];
10301
10302 case OO_Minus: // '-' is either unary or binary
10303 if (Args.size() == 1) {
10304 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10305 } else {
10306 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10307 OpBuilder.addGenericBinaryArithmeticOverloads();
10308 OpBuilder.addMatrixBinaryArithmeticOverloads();
10309 }
10310 break;
10311
10312 case OO_Star: // '*' is either unary or binary
10313 if (Args.size() == 1)
10314 OpBuilder.addUnaryStarPointerOverloads();
10315 else {
10316 OpBuilder.addGenericBinaryArithmeticOverloads();
10317 OpBuilder.addMatrixBinaryArithmeticOverloads();
10318 }
10319 break;
10320
10321 case OO_Slash:
10322 OpBuilder.addGenericBinaryArithmeticOverloads();
10323 break;
10324
10325 case OO_PlusPlus:
10326 case OO_MinusMinus:
10327 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10328 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10329 break;
10330
10331 case OO_EqualEqual:
10332 case OO_ExclaimEqual:
10333 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10334 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10335 OpBuilder.addGenericBinaryArithmeticOverloads();
10336 break;
10337
10338 case OO_Less:
10339 case OO_Greater:
10340 case OO_LessEqual:
10341 case OO_GreaterEqual:
10342 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10343 OpBuilder.addGenericBinaryArithmeticOverloads();
10344 break;
10345
10346 case OO_Spaceship:
10347 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10348 OpBuilder.addThreeWayArithmeticOverloads();
10349 break;
10350
10351 case OO_Percent:
10352 case OO_Caret:
10353 case OO_Pipe:
10354 case OO_LessLess:
10355 case OO_GreaterGreater:
10356 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10357 break;
10358
10359 case OO_Amp: // '&' is either unary or binary
10360 if (Args.size() == 1)
10361 // C++ [over.match.oper]p3:
10362 // -- For the operator ',', the unary operator '&', or the
10363 // operator '->', the built-in candidates set is empty.
10364 break;
10365
10366 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10367 break;
10368
10369 case OO_Tilde:
10370 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10371 break;
10372
10373 case OO_Equal:
10374 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10375 [[fallthrough]];
10376
10377 case OO_PlusEqual:
10378 case OO_MinusEqual:
10379 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10380 [[fallthrough]];
10381
10382 case OO_StarEqual:
10383 case OO_SlashEqual:
10384 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10385 break;
10386
10387 case OO_PercentEqual:
10388 case OO_LessLessEqual:
10389 case OO_GreaterGreaterEqual:
10390 case OO_AmpEqual:
10391 case OO_CaretEqual:
10392 case OO_PipeEqual:
10393 OpBuilder.addAssignmentIntegralOverloads();
10394 break;
10395
10396 case OO_Exclaim:
10397 OpBuilder.addExclaimOverload();
10398 break;
10399
10400 case OO_AmpAmp:
10401 case OO_PipePipe:
10402 OpBuilder.addAmpAmpOrPipePipeOverload();
10403 break;
10404
10405 case OO_Subscript:
10406 if (Args.size() == 2)
10407 OpBuilder.addSubscriptOverloads();
10408 break;
10409
10410 case OO_ArrowStar:
10411 OpBuilder.addArrowStarOverloads();
10412 break;
10413
10414 case OO_Conditional:
10415 OpBuilder.addConditionalOperatorOverloads();
10416 OpBuilder.addGenericBinaryArithmeticOverloads();
10417 break;
10418 }
10419}
10420
10421void
10423 SourceLocation Loc,
10424 ArrayRef<Expr *> Args,
10425 TemplateArgumentListInfo *ExplicitTemplateArgs,
10426 OverloadCandidateSet& CandidateSet,
10427 bool PartialOverloading) {
10428 ADLResult Fns;
10429
10430 // FIXME: This approach for uniquing ADL results (and removing
10431 // redundant candidates from the set) relies on pointer-equality,
10432 // which means we need to key off the canonical decl. However,
10433 // always going back to the canonical decl might not get us the
10434 // right set of default arguments. What default arguments are
10435 // we supposed to consider on ADL candidates, anyway?
10436
10437 // FIXME: Pass in the explicit template arguments?
10438 ArgumentDependentLookup(Name, Loc, Args, Fns);
10439
10440 ArrayRef<Expr *> ReversedArgs;
10441
10442 // Erase all of the candidates we already knew about.
10443 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10444 CandEnd = CandidateSet.end();
10445 Cand != CandEnd; ++Cand)
10446 if (Cand->Function) {
10447 FunctionDecl *Fn = Cand->Function;
10448 Fns.erase(Fn);
10449 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10450 Fns.erase(FunTmpl);
10451 }
10452
10453 // For each of the ADL candidates we found, add it to the overload
10454 // set.
10455 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10457
10458 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10459 if (ExplicitTemplateArgs)
10460 continue;
10461
10463 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10464 PartialOverloading, /*AllowExplicit=*/true,
10465 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10466 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10468 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10469 /*SuppressUserConversions=*/false, PartialOverloading,
10470 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10471 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10472 }
10473 } else {
10474 auto *FTD = cast<FunctionTemplateDecl>(*I);
10476 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10477 /*SuppressUserConversions=*/false, PartialOverloading,
10478 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10479 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10480 *this, Args, FTD->getTemplatedDecl())) {
10481
10482 // As template candidates are not deduced immediately,
10483 // persist the array in the overload set.
10484 if (ReversedArgs.empty())
10485 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10486
10488 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10489 /*SuppressUserConversions=*/false, PartialOverloading,
10490 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10492 }
10493 }
10494 }
10495}
10496
10497namespace {
10498enum class Comparison { Equal, Better, Worse };
10499}
10500
10501/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10502/// overload resolution.
10503///
10504/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10505/// Cand1's first N enable_if attributes have precisely the same conditions as
10506/// Cand2's first N enable_if attributes (where N = the number of enable_if
10507/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10508///
10509/// Note that you can have a pair of candidates such that Cand1's enable_if
10510/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10511/// worse than Cand1's.
10512static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10513 const FunctionDecl *Cand2) {
10514 // Common case: One (or both) decls don't have enable_if attrs.
10515 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10516 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10517 if (!Cand1Attr || !Cand2Attr) {
10518 if (Cand1Attr == Cand2Attr)
10519 return Comparison::Equal;
10520 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10521 }
10522
10523 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10524 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10525
10526 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10527 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10528 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10529 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10530
10531 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10532 // has fewer enable_if attributes than Cand2, and vice versa.
10533 if (!Cand1A)
10534 return Comparison::Worse;
10535 if (!Cand2A)
10536 return Comparison::Better;
10537
10538 Cand1ID.clear();
10539 Cand2ID.clear();
10540
10541 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10542 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10543 if (Cand1ID != Cand2ID)
10544 return Comparison::Worse;
10545 }
10546
10547 return Comparison::Equal;
10548}
10549
10550static Comparison
10552 const OverloadCandidate &Cand2) {
10553 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10554 !Cand2.Function->isMultiVersion())
10555 return Comparison::Equal;
10556
10557 // If both are invalid, they are equal. If one of them is invalid, the other
10558 // is better.
10559 if (Cand1.Function->isInvalidDecl()) {
10560 if (Cand2.Function->isInvalidDecl())
10561 return Comparison::Equal;
10562 return Comparison::Worse;
10563 }
10564 if (Cand2.Function->isInvalidDecl())
10565 return Comparison::Better;
10566
10567 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10568 // cpu_dispatch, else arbitrarily based on the identifiers.
10569 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10570 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10571 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10572 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10573
10574 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10575 return Comparison::Equal;
10576
10577 if (Cand1CPUDisp && !Cand2CPUDisp)
10578 return Comparison::Better;
10579 if (Cand2CPUDisp && !Cand1CPUDisp)
10580 return Comparison::Worse;
10581
10582 if (Cand1CPUSpec && Cand2CPUSpec) {
10583 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10584 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10585 ? Comparison::Better
10586 : Comparison::Worse;
10587
10588 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10589 FirstDiff = std::mismatch(
10590 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10591 Cand2CPUSpec->cpus_begin(),
10592 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10593 return LHS->getName() == RHS->getName();
10594 });
10595
10596 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10597 "Two different cpu-specific versions should not have the same "
10598 "identifier list, otherwise they'd be the same decl!");
10599 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10600 ? Comparison::Better
10601 : Comparison::Worse;
10602 }
10603 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10604}
10605
10606/// Compute the type of the implicit object parameter for the given function,
10607/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10608/// null QualType if there is a 'matches anything' implicit object parameter.
10609static std::optional<QualType>
10612 return std::nullopt;
10613
10614 auto *M = cast<CXXMethodDecl>(F);
10615 // Static member functions' object parameters match all types.
10616 if (M->isStatic())
10617 return QualType();
10618 return M->getFunctionObjectParameterReferenceType();
10619}
10620
10621// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10622// represent the same entity.
10623static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10624 const FunctionDecl *F2) {
10625 if (declaresSameEntity(F1, F2))
10626 return true;
10627 auto PT1 = F1->getPrimaryTemplate();
10628 auto PT2 = F2->getPrimaryTemplate();
10629 if (PT1 && PT2) {
10630 if (declaresSameEntity(PT1, PT2) ||
10631 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10632 PT2->getInstantiatedFromMemberTemplate()))
10633 return true;
10634 }
10635 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10636 // different functions with same params). Consider removing this (as no test
10637 // fail w/o it).
10638 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10639 if (First) {
10640 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10641 return *T;
10642 }
10643 assert(I < F->getNumParams());
10644 return F->getParamDecl(I++)->getType();
10645 };
10646
10647 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10648 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10649
10650 if (F1NumParams != F2NumParams)
10651 return false;
10652
10653 unsigned I1 = 0, I2 = 0;
10654 for (unsigned I = 0; I != F1NumParams; ++I) {
10655 QualType T1 = NextParam(F1, I1, I == 0);
10656 QualType T2 = NextParam(F2, I2, I == 0);
10657 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10658 if (!Context.hasSameUnqualifiedType(T1, T2))
10659 return false;
10660 }
10661 return true;
10662}
10663
10664/// We're allowed to use constraints partial ordering only if the candidates
10665/// have the same parameter types:
10666/// [over.match.best.general]p2.6
10667/// F1 and F2 are non-template functions with the same
10668/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10670 FunctionDecl *Fn2,
10671 bool IsFn1Reversed,
10672 bool IsFn2Reversed) {
10673 assert(Fn1 && Fn2);
10674 if (Fn1->isVariadic() != Fn2->isVariadic())
10675 return false;
10676
10677 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10678 IsFn1Reversed ^ IsFn2Reversed))
10679 return false;
10680
10681 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10682 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10683 if (Mem1 && Mem2) {
10684 // if they are member functions, both are direct members of the same class,
10685 // and
10686 if (Mem1->getParent() != Mem2->getParent())
10687 return false;
10688 // if both are non-static member functions, they have the same types for
10689 // their object parameters
10690 if (Mem1->isInstance() && Mem2->isInstance() &&
10692 Mem1->getFunctionObjectParameterReferenceType(),
10693 Mem1->getFunctionObjectParameterReferenceType()))
10694 return false;
10695 }
10696 return true;
10697}
10698
10699static FunctionDecl *
10701 bool IsFn1Reversed, bool IsFn2Reversed) {
10702 if (!Fn1 || !Fn2)
10703 return nullptr;
10704
10705 // C++ [temp.constr.order]:
10706 // A non-template function F1 is more partial-ordering-constrained than a
10707 // non-template function F2 if:
10708 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10709 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10710
10711 if (Cand1IsSpecialization || Cand2IsSpecialization)
10712 return nullptr;
10713
10714 // - they have the same non-object-parameter-type-lists, and [...]
10715 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10716 IsFn2Reversed))
10717 return nullptr;
10718
10719 // - the declaration of F1 is more constrained than the declaration of F2.
10720 return S.getMoreConstrainedFunction(Fn1, Fn2);
10721}
10722
10723/// isBetterOverloadCandidate - Determines whether the first overload
10724/// candidate is a better candidate than the second (C++ 13.3.3p1).
10726 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10728 bool PartialOverloading) {
10729 // Define viable functions to be better candidates than non-viable
10730 // functions.
10731 if (!Cand2.Viable)
10732 return Cand1.Viable;
10733 else if (!Cand1.Viable)
10734 return false;
10735
10736 // [CUDA] A function with 'never' preference is marked not viable, therefore
10737 // is never shown up here. The worst preference shown up here is 'wrong side',
10738 // e.g. an H function called by a HD function in device compilation. This is
10739 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10740 // function which is called only by an H function. A deferred diagnostic will
10741 // be triggered if it is emitted. However a wrong-sided function is still
10742 // a viable candidate here.
10743 //
10744 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10745 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10746 // can be emitted, Cand1 is not better than Cand2. This rule should have
10747 // precedence over other rules.
10748 //
10749 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10750 // other rules should be used to determine which is better. This is because
10751 // host/device based overloading resolution is mostly for determining
10752 // viability of a function. If two functions are both viable, other factors
10753 // should take precedence in preference, e.g. the standard-defined preferences
10754 // like argument conversion ranks or enable_if partial-ordering. The
10755 // preference for pass-object-size parameters is probably most similar to a
10756 // type-based-overloading decision and so should take priority.
10757 //
10758 // If other rules cannot determine which is better, CUDA preference will be
10759 // used again to determine which is better.
10760 //
10761 // TODO: Currently IdentifyPreference does not return correct values
10762 // for functions called in global variable initializers due to missing
10763 // correct context about device/host. Therefore we can only enforce this
10764 // rule when there is a caller. We should enforce this rule for functions
10765 // in global variable initializers once proper context is added.
10766 //
10767 // TODO: We can only enable the hostness based overloading resolution when
10768 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10769 // overloading resolution diagnostics.
10770 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10771 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10772 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10773 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10774 bool IsCand1ImplicitHD =
10776 bool IsCand2ImplicitHD =
10778 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10779 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10780 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10781 // The implicit HD function may be a function in a system header which
10782 // is forced by pragma. In device compilation, if we prefer HD candidates
10783 // over wrong-sided candidates, overloading resolution may change, which
10784 // may result in non-deferrable diagnostics. As a workaround, we let
10785 // implicit HD candidates take equal preference as wrong-sided candidates.
10786 // This will preserve the overloading resolution.
10787 // TODO: We still need special handling of implicit HD functions since
10788 // they may incur other diagnostics to be deferred. We should make all
10789 // host/device related diagnostics deferrable and remove special handling
10790 // of implicit HD functions.
10791 auto EmitThreshold =
10792 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10793 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10796 auto Cand1Emittable = P1 > EmitThreshold;
10797 auto Cand2Emittable = P2 > EmitThreshold;
10798 if (Cand1Emittable && !Cand2Emittable)
10799 return true;
10800 if (!Cand1Emittable && Cand2Emittable)
10801 return false;
10802 }
10803 }
10804
10805 // C++ [over.match.best]p1: (Changed in C++23)
10806 //
10807 // -- if F is a static member function, ICS1(F) is defined such
10808 // that ICS1(F) is neither better nor worse than ICS1(G) for
10809 // any function G, and, symmetrically, ICS1(G) is neither
10810 // better nor worse than ICS1(F).
10811 unsigned StartArg = 0;
10812 if (!Cand1.TookAddressOfOverload &&
10814 StartArg = 1;
10815
10816 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10817 // We don't allow incompatible pointer conversions in C++.
10818 if (!S.getLangOpts().CPlusPlus)
10819 return ICS.isStandard() &&
10820 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10821
10822 // The only ill-formed conversion we allow in C++ is the string literal to
10823 // char* conversion, which is only considered ill-formed after C++11.
10824 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10826 };
10827
10828 // Define functions that don't require ill-formed conversions for a given
10829 // argument to be better candidates than functions that do.
10830 unsigned NumArgs = Cand1.Conversions.size();
10831 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10832 bool HasBetterConversion = false;
10833 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10834 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10835 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10836 if (Cand1Bad != Cand2Bad) {
10837 if (Cand1Bad)
10838 return false;
10839 HasBetterConversion = true;
10840 }
10841 }
10842
10843 if (HasBetterConversion)
10844 return true;
10845
10846 // C++ [over.match.best]p1:
10847 // A viable function F1 is defined to be a better function than another
10848 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10849 // conversion sequence than ICSi(F2), and then...
10850 bool HasWorseConversion = false;
10851 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10853 Cand1.Conversions[ArgIdx],
10854 Cand2.Conversions[ArgIdx])) {
10856 // Cand1 has a better conversion sequence.
10857 HasBetterConversion = true;
10858 break;
10859
10861 if (Cand1.Function && Cand2.Function &&
10862 Cand1.isReversed() != Cand2.isReversed() &&
10863 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10864 // Work around large-scale breakage caused by considering reversed
10865 // forms of operator== in C++20:
10866 //
10867 // When comparing a function against a reversed function, if we have a
10868 // better conversion for one argument and a worse conversion for the
10869 // other, the implicit conversion sequences are treated as being equally
10870 // good.
10871 //
10872 // This prevents a comparison function from being considered ambiguous
10873 // with a reversed form that is written in the same way.
10874 //
10875 // We diagnose this as an extension from CreateOverloadedBinOp.
10876 HasWorseConversion = true;
10877 break;
10878 }
10879
10880 // Cand1 can't be better than Cand2.
10881 return false;
10882
10884 // Do nothing.
10885 break;
10886 }
10887 }
10888
10889 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10890 // ICSj(F2), or, if not that,
10891 if (HasBetterConversion && !HasWorseConversion)
10892 return true;
10893
10894 // -- the context is an initialization by user-defined conversion
10895 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10896 // from the return type of F1 to the destination type (i.e.,
10897 // the type of the entity being initialized) is a better
10898 // conversion sequence than the standard conversion sequence
10899 // from the return type of F2 to the destination type.
10901 Cand1.Function && Cand2.Function &&
10904
10905 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10906 // First check whether we prefer one of the conversion functions over the
10907 // other. This only distinguishes the results in non-standard, extension
10908 // cases such as the conversion from a lambda closure type to a function
10909 // pointer or block.
10914 Cand1.FinalConversion,
10915 Cand2.FinalConversion);
10916
10919
10920 // FIXME: Compare kind of reference binding if conversion functions
10921 // convert to a reference type used in direct reference binding, per
10922 // C++14 [over.match.best]p1 section 2 bullet 3.
10923 }
10924
10925 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10926 // as combined with the resolution to CWG issue 243.
10927 //
10928 // When the context is initialization by constructor ([over.match.ctor] or
10929 // either phase of [over.match.list]), a constructor is preferred over
10930 // a conversion function.
10931 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10932 Cand1.Function && Cand2.Function &&
10935 return isa<CXXConstructorDecl>(Cand1.Function);
10936
10937 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10938 return Cand2.StrictPackMatch;
10939
10940 // -- F1 is a non-template function and F2 is a function template
10941 // specialization, or, if not that,
10942 bool Cand1IsSpecialization = Cand1.Function &&
10944 bool Cand2IsSpecialization = Cand2.Function &&
10946 if (Cand1IsSpecialization != Cand2IsSpecialization)
10947 return Cand2IsSpecialization;
10948
10949 // -- F1 and F2 are function template specializations, and the function
10950 // template for F1 is more specialized than the template for F2
10951 // according to the partial ordering rules described in 14.5.5.2, or,
10952 // if not that,
10953 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10954 const auto *Obj1Context =
10955 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10956 const auto *Obj2Context =
10957 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10958 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10960 Cand2.Function->getPrimaryTemplate(), Loc,
10962 : TPOC_Call,
10964 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
10965 : QualType{},
10966 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
10967 : QualType{},
10968 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10969 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10970 }
10971 }
10972
10973 // -— F1 and F2 are non-template functions and F1 is more
10974 // partial-ordering-constrained than F2 [...],
10976 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10977 Cand2.isReversed());
10978 F && F == Cand1.Function)
10979 return true;
10980
10981 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10982 // class B of D, and for all arguments the corresponding parameters of
10983 // F1 and F2 have the same type.
10984 // FIXME: Implement the "all parameters have the same type" check.
10985 bool Cand1IsInherited =
10986 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10987 bool Cand2IsInherited =
10988 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10989 if (Cand1IsInherited != Cand2IsInherited)
10990 return Cand2IsInherited;
10991 else if (Cand1IsInherited) {
10992 assert(Cand2IsInherited);
10993 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10994 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10995 if (Cand1Class->isDerivedFrom(Cand2Class))
10996 return true;
10997 if (Cand2Class->isDerivedFrom(Cand1Class))
10998 return false;
10999 // Inherited from sibling base classes: still ambiguous.
11000 }
11001
11002 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11003 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11004 // with reversed order of parameters and F1 is not
11005 //
11006 // We rank reversed + different operator as worse than just reversed, but
11007 // that comparison can never happen, because we only consider reversing for
11008 // the maximally-rewritten operator (== or <=>).
11009 if (Cand1.RewriteKind != Cand2.RewriteKind)
11010 return Cand1.RewriteKind < Cand2.RewriteKind;
11011
11012 // Check C++17 tie-breakers for deduction guides.
11013 {
11014 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11015 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11016 if (Guide1 && Guide2) {
11017 // -- F1 is generated from a deduction-guide and F2 is not
11018 if (Guide1->isImplicit() != Guide2->isImplicit())
11019 return Guide2->isImplicit();
11020
11021 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11022 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11023 return true;
11024 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11025 return false;
11026
11027 // --F1 is generated from a non-template constructor and F2 is generated
11028 // from a constructor template
11029 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11030 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11031 if (Constructor1 && Constructor2) {
11032 bool isC1Templated = Constructor1->getTemplatedKind() !=
11034 bool isC2Templated = Constructor2->getTemplatedKind() !=
11036 if (isC1Templated != isC2Templated)
11037 return isC2Templated;
11038 }
11039 }
11040 }
11041
11042 // Check for enable_if value-based overload resolution.
11043 if (Cand1.Function && Cand2.Function) {
11044 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11045 if (Cmp != Comparison::Equal)
11046 return Cmp == Comparison::Better;
11047 }
11048
11049 bool HasPS1 = Cand1.Function != nullptr &&
11051 bool HasPS2 = Cand2.Function != nullptr &&
11053 if (HasPS1 != HasPS2 && HasPS1)
11054 return true;
11055
11056 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11057 if (MV == Comparison::Better)
11058 return true;
11059 if (MV == Comparison::Worse)
11060 return false;
11061
11062 // If other rules cannot determine which is better, CUDA preference is used
11063 // to determine which is better.
11064 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11065 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11066 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11067 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11068 }
11069
11070 // General member function overloading is handled above, so this only handles
11071 // constructors with address spaces.
11072 // This only handles address spaces since C++ has no other
11073 // qualifier that can be used with constructors.
11074 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11075 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11076 if (CD1 && CD2) {
11077 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11078 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11079 if (AS1 != AS2) {
11081 return true;
11083 return false;
11084 }
11085 }
11086
11087 return false;
11088}
11089
11090/// Determine whether two declarations are "equivalent" for the purposes of
11091/// name lookup and overload resolution. This applies when the same internal/no
11092/// linkage entity is defined by two modules (probably by textually including
11093/// the same header). In such a case, we don't consider the declarations to
11094/// declare the same entity, but we also don't want lookups with both
11095/// declarations visible to be ambiguous in some cases (this happens when using
11096/// a modularized libstdc++).
11098 const NamedDecl *B) {
11099 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11100 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11101 if (!VA || !VB)
11102 return false;
11103
11104 // The declarations must be declaring the same name as an internal linkage
11105 // entity in different modules.
11106 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11107 VB->getDeclContext()->getRedeclContext()) ||
11108 getOwningModule(VA) == getOwningModule(VB) ||
11109 VA->isExternallyVisible() || VB->isExternallyVisible())
11110 return false;
11111
11112 // Check that the declarations appear to be equivalent.
11113 //
11114 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11115 // For constants and functions, we should check the initializer or body is
11116 // the same. For non-constant variables, we shouldn't allow it at all.
11117 if (Context.hasSameType(VA->getType(), VB->getType()))
11118 return true;
11119
11120 // Enum constants within unnamed enumerations will have different types, but
11121 // may still be similar enough to be interchangeable for our purposes.
11122 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11123 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11124 // Only handle anonymous enums. If the enumerations were named and
11125 // equivalent, they would have been merged to the same type.
11126 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11127 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11128 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11129 !Context.hasSameType(EnumA->getIntegerType(),
11130 EnumB->getIntegerType()))
11131 return false;
11132 // Allow this only if the value is the same for both enumerators.
11133 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11134 }
11135 }
11136
11137 // Nothing else is sufficiently similar.
11138 return false;
11139}
11140
11143 assert(D && "Unknown declaration");
11144 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11145
11146 Module *M = getOwningModule(D);
11147 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11148 << !M << (M ? M->getFullModuleName() : "");
11149
11150 for (auto *E : Equiv) {
11151 Module *M = getOwningModule(E);
11152 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11153 << !M << (M ? M->getFullModuleName() : "");
11154 }
11155}
11156
11159 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11161 static_cast<CNSInfo *>(DeductionFailure.Data)
11162 ->Satisfaction.ContainsErrors;
11163}
11164
11167 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11168 bool PartialOverloading, bool AllowExplicit,
11170 bool AggregateCandidateDeduction) {
11171
11172 auto *C =
11173 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11174
11177 /*AllowObjCConversionOnExplicit=*/false,
11178 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11179 PartialOverloading, AggregateCandidateDeduction},
11181 FoundDecl,
11182 Args,
11183 IsADLCandidate,
11184 PO};
11185
11186 HasDeferredTemplateConstructors |=
11187 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11188}
11189
11191 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11192 CXXRecordDecl *ActingContext, QualType ObjectType,
11193 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11194 bool SuppressUserConversions, bool PartialOverloading,
11196
11197 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11198
11199 auto *C =
11200 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11201
11204 /*AllowObjCConversionOnExplicit=*/false,
11205 /*AllowResultConversion=*/false,
11206 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11207 /*AggregateCandidateDeduction=*/false},
11208 MethodTmpl,
11209 FoundDecl,
11210 Args,
11211 ActingContext,
11212 ObjectClassification,
11213 ObjectType,
11214 PO};
11215}
11216
11219 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11220 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11221 bool AllowResultConversion) {
11222
11223 auto *C =
11224 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11225
11228 AllowObjCConversionOnExplicit, AllowResultConversion,
11229 /*AllowExplicit=*/false,
11230 /*SuppressUserConversions=*/false,
11231 /*PartialOverloading*/ false,
11232 /*AggregateCandidateDeduction=*/false},
11234 FoundDecl,
11235 ActingContext,
11236 From,
11237 ToType};
11238}
11239
11240static void
11243
11245 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11246 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11247 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11248}
11249
11250static void
11254 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11255 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11256 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11257 C.AggregateCandidateDeduction);
11258}
11259
11260static void
11264 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11265 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11266 C.AllowResultConversion);
11267}
11268
11270 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11271 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11272 while (Cand) {
11273 switch (Cand->Kind) {
11276 S, *this,
11277 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11278 break;
11281 S, *this,
11282 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11283 break;
11286 S, *this,
11287 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11288 break;
11289 }
11290 Cand = Cand->Next;
11291 }
11292 FirstDeferredCandidate = nullptr;
11293 DeferredCandidatesCount = 0;
11294}
11295
11297OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11298 Best->Best = true;
11299 if (Best->Function && Best->Function->isDeleted())
11300 return OR_Deleted;
11301 return OR_Success;
11302}
11303
11304void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11306 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11307 // are accepted by both clang and NVCC. However, during a particular
11308 // compilation mode only one call variant is viable. We need to
11309 // exclude non-viable overload candidates from consideration based
11310 // only on their host/device attributes. Specifically, if one
11311 // candidate call is WrongSide and the other is SameSide, we ignore
11312 // the WrongSide candidate.
11313 // We only need to remove wrong-sided candidates here if
11314 // -fgpu-exclude-wrong-side-overloads is off. When
11315 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11316 // uniformly in isBetterOverloadCandidate.
11317 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11318 return;
11319 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11320
11321 bool ContainsSameSideCandidate =
11322 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11323 // Check viable function only.
11324 return Cand->Viable && Cand->Function &&
11325 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11327 });
11328
11329 if (!ContainsSameSideCandidate)
11330 return;
11331
11332 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11333 // Check viable function only to avoid unnecessary data copying/moving.
11334 return Cand->Viable && Cand->Function &&
11335 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11337 };
11338 llvm::erase_if(Candidates, IsWrongSideCandidate);
11339}
11340
11341/// Computes the best viable function (C++ 13.3.3)
11342/// within an overload candidate set.
11343///
11344/// \param Loc The location of the function name (or operator symbol) for
11345/// which overload resolution occurs.
11346///
11347/// \param Best If overload resolution was successful or found a deleted
11348/// function, \p Best points to the candidate function found.
11349///
11350/// \returns The result of overload resolution.
11352 SourceLocation Loc,
11353 iterator &Best) {
11354
11356 DeferredCandidatesCount == 0) &&
11357 "Unexpected deferred template candidates");
11358
11359 bool TwoPhaseResolution =
11360 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11361
11362 if (TwoPhaseResolution) {
11363 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11364 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11365 if (!(HasDeferredTemplateConstructors &&
11366 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11367 return Res;
11368 }
11369 }
11370
11372 return BestViableFunctionImpl(S, Loc, Best);
11373}
11374
11375OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11377
11379 Candidates.reserve(this->Candidates.size());
11380 std::transform(this->Candidates.begin(), this->Candidates.end(),
11381 std::back_inserter(Candidates),
11382 [](OverloadCandidate &Cand) { return &Cand; });
11383
11384 if (S.getLangOpts().CUDA)
11385 CudaExcludeWrongSideCandidates(S, Candidates);
11386
11387 Best = end();
11388 for (auto *Cand : Candidates) {
11389 Cand->Best = false;
11390 if (Cand->Viable) {
11391 if (Best == end() ||
11392 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11393 Best = Cand;
11394 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11395 // This candidate has constraint that we were unable to evaluate because
11396 // it referenced an expression that contained an error. Rather than fall
11397 // back onto a potentially unintended candidate (made worse by
11398 // subsuming constraints), treat this as 'no viable candidate'.
11399 Best = end();
11400 return OR_No_Viable_Function;
11401 }
11402 }
11403
11404 // If we didn't find any viable functions, abort.
11405 if (Best == end())
11406 return OR_No_Viable_Function;
11407
11408 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11409 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11410 PendingBest.push_back(&*Best);
11411 Best->Best = true;
11412
11413 // Make sure that this function is better than every other viable
11414 // function. If not, we have an ambiguity.
11415 while (!PendingBest.empty()) {
11416 auto *Curr = PendingBest.pop_back_val();
11417 for (auto *Cand : Candidates) {
11418 if (Cand->Viable && !Cand->Best &&
11419 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11420 PendingBest.push_back(Cand);
11421 Cand->Best = true;
11422
11424 Curr->Function))
11425 EquivalentCands.push_back(Cand->Function);
11426 else
11427 Best = end();
11428 }
11429 }
11430 }
11431
11432 if (Best == end())
11433 return OR_Ambiguous;
11434
11435 OverloadingResult R = ResultForBestCandidate(Best);
11436
11437 if (!EquivalentCands.empty())
11439 EquivalentCands);
11440 return R;
11441}
11442
11443namespace {
11444
11445enum OverloadCandidateKind {
11446 oc_function,
11447 oc_method,
11448 oc_reversed_binary_operator,
11449 oc_constructor,
11450 oc_implicit_default_constructor,
11451 oc_implicit_copy_constructor,
11452 oc_implicit_move_constructor,
11453 oc_implicit_copy_assignment,
11454 oc_implicit_move_assignment,
11455 oc_implicit_equality_comparison,
11456 oc_inherited_constructor
11457};
11458
11459enum OverloadCandidateSelect {
11460 ocs_non_template,
11461 ocs_template,
11462 ocs_described_template,
11463};
11464
11465static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11466ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11467 const FunctionDecl *Fn,
11469 std::string &Description) {
11470
11471 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11472 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11473 isTemplate = true;
11474 Description = S.getTemplateArgumentBindingsText(
11475 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11476 }
11477
11478 OverloadCandidateSelect Select = [&]() {
11479 if (!Description.empty())
11480 return ocs_described_template;
11481 return isTemplate ? ocs_template : ocs_non_template;
11482 }();
11483
11484 OverloadCandidateKind Kind = [&]() {
11485 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11486 return oc_implicit_equality_comparison;
11487
11488 if (CRK & CRK_Reversed)
11489 return oc_reversed_binary_operator;
11490
11491 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11492 if (!Ctor->isImplicit()) {
11494 return oc_inherited_constructor;
11495 else
11496 return oc_constructor;
11497 }
11498
11499 if (Ctor->isDefaultConstructor())
11500 return oc_implicit_default_constructor;
11501
11502 if (Ctor->isMoveConstructor())
11503 return oc_implicit_move_constructor;
11504
11505 assert(Ctor->isCopyConstructor() &&
11506 "unexpected sort of implicit constructor");
11507 return oc_implicit_copy_constructor;
11508 }
11509
11510 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11511 // This actually gets spelled 'candidate function' for now, but
11512 // it doesn't hurt to split it out.
11513 if (!Meth->isImplicit())
11514 return oc_method;
11515
11516 if (Meth->isMoveAssignmentOperator())
11517 return oc_implicit_move_assignment;
11518
11519 if (Meth->isCopyAssignmentOperator())
11520 return oc_implicit_copy_assignment;
11521
11522 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11523 return oc_method;
11524 }
11525
11526 return oc_function;
11527 }();
11528
11529 return std::make_pair(Kind, Select);
11530}
11531
11532void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11533 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11534 // set.
11535 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11536 S.Diag(FoundDecl->getLocation(),
11537 diag::note_ovl_candidate_inherited_constructor)
11538 << Shadow->getNominatedBaseClass();
11539}
11540
11541} // end anonymous namespace
11542
11544 const FunctionDecl *FD) {
11545 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11546 bool AlwaysTrue;
11547 if (EnableIf->getCond()->isValueDependent() ||
11548 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11549 return false;
11550 if (!AlwaysTrue)
11551 return false;
11552 }
11553 return true;
11554}
11555
11556/// Returns true if we can take the address of the function.
11557///
11558/// \param Complain - If true, we'll emit a diagnostic
11559/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11560/// we in overload resolution?
11561/// \param Loc - The location of the statement we're complaining about. Ignored
11562/// if we're not complaining, or if we're in overload resolution.
11564 bool Complain,
11565 bool InOverloadResolution,
11566 SourceLocation Loc) {
11567 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11568 if (Complain) {
11569 if (InOverloadResolution)
11570 S.Diag(FD->getBeginLoc(),
11571 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11572 else
11573 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11574 }
11575 return false;
11576 }
11577
11578 if (FD->getTrailingRequiresClause()) {
11579 ConstraintSatisfaction Satisfaction;
11580 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11581 return false;
11582 if (!Satisfaction.IsSatisfied) {
11583 if (Complain) {
11584 if (InOverloadResolution) {
11585 SmallString<128> TemplateArgString;
11586 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11587 TemplateArgString += " ";
11588 TemplateArgString += S.getTemplateArgumentBindingsText(
11589 FunTmpl->getTemplateParameters(),
11591 }
11592
11593 S.Diag(FD->getBeginLoc(),
11594 diag::note_ovl_candidate_unsatisfied_constraints)
11595 << TemplateArgString;
11596 } else
11597 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11598 << FD;
11599 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11600 }
11601 return false;
11602 }
11603 }
11604
11605 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11606 return P->hasAttr<PassObjectSizeAttr>();
11607 });
11608 if (I == FD->param_end())
11609 return true;
11610
11611 if (Complain) {
11612 // Add one to ParamNo because it's user-facing
11613 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11614 if (InOverloadResolution)
11615 S.Diag(FD->getLocation(),
11616 diag::note_ovl_candidate_has_pass_object_size_params)
11617 << ParamNo;
11618 else
11619 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11620 << FD << ParamNo;
11621 }
11622 return false;
11623}
11624
11626 const FunctionDecl *FD) {
11627 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11628 /*InOverloadResolution=*/true,
11629 /*Loc=*/SourceLocation());
11630}
11631
11633 bool Complain,
11634 SourceLocation Loc) {
11635 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11636 /*InOverloadResolution=*/false,
11637 Loc);
11638}
11639
11640// Don't print candidates other than the one that matches the calling
11641// convention of the call operator, since that is guaranteed to exist.
11643 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11644
11645 if (!ConvD)
11646 return false;
11647 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11648 if (!RD->isLambda())
11649 return false;
11650
11651 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11652 CallingConv CallOpCC =
11653 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11654 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11655 CallingConv ConvToCC =
11656 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11657
11658 return ConvToCC != CallOpCC;
11659}
11660
11661// Notes the location of an overload candidate.
11663 OverloadCandidateRewriteKind RewriteKind,
11664 QualType DestType, bool TakingAddress) {
11665 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11666 return;
11667 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11668 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11669 return;
11670 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11671 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11672 return;
11674 return;
11675
11676 std::string FnDesc;
11677 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11678 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11679 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11680 << (unsigned)KSPair.first << (unsigned)KSPair.second
11681 << Fn << FnDesc;
11682
11683 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11684 Diag(Fn->getLocation(), PD);
11685 MaybeEmitInheritedConstructorNote(*this, Found);
11686}
11687
11688static void
11690 // Perhaps the ambiguity was caused by two atomic constraints that are
11691 // 'identical' but not equivalent:
11692 //
11693 // void foo() requires (sizeof(T) > 4) { } // #1
11694 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11695 //
11696 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11697 // #2 to subsume #1, but these constraint are not considered equivalent
11698 // according to the subsumption rules because they are not the same
11699 // source-level construct. This behavior is quite confusing and we should try
11700 // to help the user figure out what happened.
11701
11702 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11703 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11704 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11705 if (!I->Function)
11706 continue;
11708 if (auto *Template = I->Function->getPrimaryTemplate())
11709 Template->getAssociatedConstraints(AC);
11710 else
11711 I->Function->getAssociatedConstraints(AC);
11712 if (AC.empty())
11713 continue;
11714 if (FirstCand == nullptr) {
11715 FirstCand = I->Function;
11716 FirstAC = AC;
11717 } else if (SecondCand == nullptr) {
11718 SecondCand = I->Function;
11719 SecondAC = AC;
11720 } else {
11721 // We have more than one pair of constrained functions - this check is
11722 // expensive and we'd rather not try to diagnose it.
11723 return;
11724 }
11725 }
11726 if (!SecondCand)
11727 return;
11728 // The diagnostic can only happen if there are associated constraints on
11729 // both sides (there needs to be some identical atomic constraint).
11730 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11731 SecondCand, SecondAC))
11732 // Just show the user one diagnostic, they'll probably figure it out
11733 // from here.
11734 return;
11735}
11736
11737// Notes the location of all overload candidates designated through
11738// OverloadedExpr
11739void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11740 bool TakingAddress) {
11741 assert(OverloadedExpr->getType() == Context.OverloadTy);
11742
11743 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11744 OverloadExpr *OvlExpr = Ovl.Expression;
11745
11746 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11747 IEnd = OvlExpr->decls_end();
11748 I != IEnd; ++I) {
11749 if (FunctionTemplateDecl *FunTmpl =
11750 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11751 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11752 TakingAddress);
11753 } else if (FunctionDecl *Fun
11754 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11755 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11756 }
11757 }
11758}
11759
11760/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11761/// "lead" diagnostic; it will be given two arguments, the source and
11762/// target types of the conversion.
11764 Sema &S,
11765 SourceLocation CaretLoc,
11766 const PartialDiagnostic &PDiag) const {
11767 S.Diag(CaretLoc, PDiag)
11768 << Ambiguous.getFromType() << Ambiguous.getToType();
11769 unsigned CandsShown = 0;
11771 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11772 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11773 break;
11774 ++CandsShown;
11775 S.NoteOverloadCandidate(I->first, I->second);
11776 }
11777 S.Diags.overloadCandidatesShown(CandsShown);
11778 if (I != E)
11779 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11780}
11781
11783 unsigned I, bool TakingCandidateAddress) {
11784 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11785 assert(Conv.isBad());
11786 assert(Cand->Function && "for now, candidate must be a function");
11787 FunctionDecl *Fn = Cand->Function;
11788
11789 // There's a conversion slot for the object argument if this is a
11790 // non-constructor method. Note that 'I' corresponds the
11791 // conversion-slot index.
11792 bool isObjectArgument = false;
11793 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11795 if (I == 0)
11796 isObjectArgument = true;
11797 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11798 I--;
11799 }
11800
11801 std::string FnDesc;
11802 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11803 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11804 FnDesc);
11805
11806 Expr *FromExpr = Conv.Bad.FromExpr;
11807 QualType FromTy = Conv.Bad.getFromType();
11808 QualType ToTy = Conv.Bad.getToType();
11809 SourceRange ToParamRange;
11810
11811 // FIXME: In presence of parameter packs we can't determine parameter range
11812 // reliably, as we don't have access to instantiation.
11813 bool HasParamPack =
11814 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11815 return Parm->isParameterPack();
11816 });
11817 if (!isObjectArgument && !HasParamPack)
11818 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11819
11820 if (FromTy == S.Context.OverloadTy) {
11821 assert(FromExpr && "overload set argument came from implicit argument?");
11822 Expr *E = FromExpr->IgnoreParens();
11823 if (isa<UnaryOperator>(E))
11824 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11825 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11826
11827 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11828 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11829 << ToParamRange << ToTy << Name << I + 1;
11830 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11831 return;
11832 }
11833
11834 // Do some hand-waving analysis to see if the non-viability is due
11835 // to a qualifier mismatch.
11836 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11837 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11838 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11839 CToTy = RT->getPointeeType();
11840 else {
11841 // TODO: detect and diagnose the full richness of const mismatches.
11842 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11843 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11844 CFromTy = FromPT->getPointeeType();
11845 CToTy = ToPT->getPointeeType();
11846 }
11847 }
11848
11849 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11850 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11851 Qualifiers FromQs = CFromTy.getQualifiers();
11852 Qualifiers ToQs = CToTy.getQualifiers();
11853
11854 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11855 if (isObjectArgument)
11856 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11857 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11858 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11859 else
11860 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11861 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11862 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11863 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11864 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11865 return;
11866 }
11867
11868 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11870 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11871 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11872 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11873 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11874 return;
11875 }
11876
11877 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11878 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11879 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11880 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11881 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11882 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11883 return;
11884 }
11885
11886 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11888 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11889 << FromTy << !!FromQs.getPointerAuth()
11890 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11891 << ToQs.getPointerAuth().getAsString() << I + 1
11892 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11893 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11894 return;
11895 }
11896
11897 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11898 assert(CVR && "expected qualifiers mismatch");
11899
11900 if (isObjectArgument) {
11901 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11902 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11903 << FromTy << (CVR - 1);
11904 } else {
11905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11906 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11907 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11908 }
11909 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11910 return;
11911 }
11912
11915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11916 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11917 << (unsigned)isObjectArgument << I + 1
11919 << ToParamRange;
11920 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11921 return;
11922 }
11923
11924 // Special diagnostic for failure to convert an initializer list, since
11925 // telling the user that it has type void is not useful.
11926 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11927 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11928 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11929 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11932 ? 2
11933 : 0);
11934 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11935 return;
11936 }
11937
11938 // Diagnose references or pointers to incomplete types differently,
11939 // since it's far from impossible that the incompleteness triggered
11940 // the failure.
11941 QualType TempFromTy = FromTy.getNonReferenceType();
11942 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11943 TempFromTy = PTy->getPointeeType();
11944 if (TempFromTy->isIncompleteType()) {
11945 // Emit the generic diagnostic and, optionally, add the hints to it.
11946 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11947 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11948 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11949 << (unsigned)(Cand->Fix.Kind);
11950
11951 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11952 return;
11953 }
11954
11955 // Diagnose base -> derived pointer conversions.
11956 unsigned BaseToDerivedConversion = 0;
11957 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11958 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11959 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11960 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11961 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11962 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11963 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11964 FromPtrTy->getPointeeType()))
11965 BaseToDerivedConversion = 1;
11966 }
11967 } else if (const ObjCObjectPointerType *FromPtrTy
11968 = FromTy->getAs<ObjCObjectPointerType>()) {
11969 if (const ObjCObjectPointerType *ToPtrTy
11970 = ToTy->getAs<ObjCObjectPointerType>())
11971 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11972 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11973 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11974 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11975 FromIface->isSuperClassOf(ToIface))
11976 BaseToDerivedConversion = 2;
11977 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11978 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11979 S.getASTContext()) &&
11980 !FromTy->isIncompleteType() &&
11981 !ToRefTy->getPointeeType()->isIncompleteType() &&
11982 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11983 BaseToDerivedConversion = 3;
11984 }
11985 }
11986
11987 if (BaseToDerivedConversion) {
11988 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11989 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11990 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11991 << I + 1;
11992 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11993 return;
11994 }
11995
11996 if (isa<ObjCObjectPointerType>(CFromTy) &&
11997 isa<PointerType>(CToTy)) {
11998 Qualifiers FromQs = CFromTy.getQualifiers();
11999 Qualifiers ToQs = CToTy.getQualifiers();
12000 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12001 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12002 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12003 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12004 << I + 1;
12005 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12006 return;
12007 }
12008 }
12009
12010 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12011 return;
12012
12013 // Emit the generic diagnostic and, optionally, add the hints to it.
12014 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12015 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12016 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12017 << (unsigned)(Cand->Fix.Kind);
12018
12019 // Check that location of Fn is not in system header.
12020 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12021 // If we can fix the conversion, suggest the FixIts.
12022 for (const FixItHint &HI : Cand->Fix.Hints)
12023 FDiag << HI;
12024 }
12025
12026 S.Diag(Fn->getLocation(), FDiag);
12027
12028 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12029}
12030
12031/// Additional arity mismatch diagnosis specific to a function overload
12032/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12033/// over a candidate in any candidate set.
12035 unsigned NumArgs, bool IsAddressOf = false) {
12036 assert(Cand->Function && "Candidate is required to be a function.");
12037 FunctionDecl *Fn = Cand->Function;
12038 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12039 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12040
12041 // With invalid overloaded operators, it's possible that we think we
12042 // have an arity mismatch when in fact it looks like we have the
12043 // right number of arguments, because only overloaded operators have
12044 // the weird behavior of overloading member and non-member functions.
12045 // Just don't report anything.
12046 if (Fn->isInvalidDecl() &&
12047 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12048 return true;
12049
12050 if (NumArgs < MinParams) {
12051 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12053 Cand->DeductionFailure.getResult() ==
12055 } else {
12056 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12058 Cand->DeductionFailure.getResult() ==
12060 }
12061
12062 return false;
12063}
12064
12065/// General arity mismatch diagnosis over a candidate in a candidate set.
12067 unsigned NumFormalArgs,
12068 bool IsAddressOf = false) {
12069 assert(isa<FunctionDecl>(D) &&
12070 "The templated declaration should at least be a function"
12071 " when diagnosing bad template argument deduction due to too many"
12072 " or too few arguments");
12073
12075
12076 // TODO: treat calls to a missing default constructor as a special case
12077 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12078 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12079 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12080
12081 // at least / at most / exactly
12082 bool HasExplicitObjectParam =
12083 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12084
12085 unsigned ParamCount =
12086 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12087 unsigned mode, modeCount;
12088
12089 if (NumFormalArgs < MinParams) {
12090 if (MinParams != ParamCount || FnTy->isVariadic() ||
12091 FnTy->isTemplateVariadic())
12092 mode = 0; // "at least"
12093 else
12094 mode = 2; // "exactly"
12095 modeCount = MinParams;
12096 } else {
12097 if (MinParams != ParamCount)
12098 mode = 1; // "at most"
12099 else
12100 mode = 2; // "exactly"
12101 modeCount = ParamCount;
12102 }
12103
12104 std::string Description;
12105 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12106 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12107
12108 if (modeCount == 1 && !IsAddressOf &&
12109 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12111 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12112 << Description << mode
12113 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12114 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12115 else
12116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12117 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12118 << Description << mode << modeCount << NumFormalArgs
12119 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12120
12121 MaybeEmitInheritedConstructorNote(S, Found);
12122}
12123
12124/// Arity mismatch diagnosis specific to a function overload candidate.
12126 unsigned NumFormalArgs) {
12127 assert(Cand->Function && "Candidate must be a function");
12128 FunctionDecl *Fn = Cand->Function;
12129 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12130 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12131 Cand->TookAddressOfOverload);
12132}
12133
12135 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12136 return TD;
12137 llvm_unreachable("Unsupported: Getting the described template declaration"
12138 " for bad deduction diagnosis");
12139}
12140
12141/// Diagnose a failed template-argument deduction.
12142static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12143 DeductionFailureInfo &DeductionFailure,
12144 unsigned NumArgs,
12145 bool TakingCandidateAddress) {
12146 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12147 NamedDecl *ParamD;
12148 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12149 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12150 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12151 switch (DeductionFailure.getResult()) {
12153 llvm_unreachable(
12154 "TemplateDeductionResult::Success while diagnosing bad deduction");
12156 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12157 "while diagnosing bad deduction");
12160 return;
12161
12163 assert(ParamD && "no parameter found for incomplete deduction result");
12164 S.Diag(Templated->getLocation(),
12165 diag::note_ovl_candidate_incomplete_deduction)
12166 << ParamD->getDeclName();
12167 MaybeEmitInheritedConstructorNote(S, Found);
12168 return;
12169 }
12170
12172 assert(ParamD && "no parameter found for incomplete deduction result");
12173 S.Diag(Templated->getLocation(),
12174 diag::note_ovl_candidate_incomplete_deduction_pack)
12175 << ParamD->getDeclName()
12176 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12177 << *DeductionFailure.getFirstArg();
12178 MaybeEmitInheritedConstructorNote(S, Found);
12179 return;
12180 }
12181
12183 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12185
12186 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12187
12188 // Param will have been canonicalized, but it should just be a
12189 // qualified version of ParamD, so move the qualifiers to that.
12191 Qs.strip(Param);
12192 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12193 assert(S.Context.hasSameType(Param, NonCanonParam));
12194
12195 // Arg has also been canonicalized, but there's nothing we can do
12196 // about that. It also doesn't matter as much, because it won't
12197 // have any template parameters in it (because deduction isn't
12198 // done on dependent types).
12199 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12200
12201 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12202 << ParamD->getDeclName() << Arg << NonCanonParam;
12203 MaybeEmitInheritedConstructorNote(S, Found);
12204 return;
12205 }
12206
12208 assert(ParamD && "no parameter found for inconsistent deduction result");
12209 int which = 0;
12210 if (isa<TemplateTypeParmDecl>(ParamD))
12211 which = 0;
12212 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12213 // Deduction might have failed because we deduced arguments of two
12214 // different types for a non-type template parameter.
12215 // FIXME: Use a different TDK value for this.
12216 QualType T1 =
12217 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12218 QualType T2 =
12219 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12220 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12221 S.Diag(Templated->getLocation(),
12222 diag::note_ovl_candidate_inconsistent_deduction_types)
12223 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12224 << *DeductionFailure.getSecondArg() << T2;
12225 MaybeEmitInheritedConstructorNote(S, Found);
12226 return;
12227 }
12228
12229 which = 1;
12230 } else {
12231 which = 2;
12232 }
12233
12234 // Tweak the diagnostic if the problem is that we deduced packs of
12235 // different arities. We'll print the actual packs anyway in case that
12236 // includes additional useful information.
12237 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12238 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12239 DeductionFailure.getFirstArg()->pack_size() !=
12240 DeductionFailure.getSecondArg()->pack_size()) {
12241 which = 3;
12242 }
12243
12244 S.Diag(Templated->getLocation(),
12245 diag::note_ovl_candidate_inconsistent_deduction)
12246 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12247 << *DeductionFailure.getSecondArg();
12248 MaybeEmitInheritedConstructorNote(S, Found);
12249 return;
12250 }
12251
12253 assert(ParamD && "no parameter found for invalid explicit arguments");
12254 if (ParamD->getDeclName())
12255 S.Diag(Templated->getLocation(),
12256 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12257 << ParamD->getDeclName();
12258 else {
12259 int index = 0;
12260 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12261 index = TTP->getIndex();
12262 else if (NonTypeTemplateParmDecl *NTTP
12263 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12264 index = NTTP->getIndex();
12265 else
12266 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12267 S.Diag(Templated->getLocation(),
12268 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12269 << (index + 1);
12270 }
12271 MaybeEmitInheritedConstructorNote(S, Found);
12272 return;
12273
12275 // Format the template argument list into the argument string.
12276 SmallString<128> TemplateArgString;
12277 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12278 TemplateArgString = " ";
12279 TemplateArgString += S.getTemplateArgumentBindingsText(
12280 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12281 if (TemplateArgString.size() == 1)
12282 TemplateArgString.clear();
12283 S.Diag(Templated->getLocation(),
12284 diag::note_ovl_candidate_unsatisfied_constraints)
12285 << TemplateArgString;
12286
12288 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12289 return;
12290 }
12293 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12294 return;
12295
12297 S.Diag(Templated->getLocation(),
12298 diag::note_ovl_candidate_instantiation_depth);
12299 MaybeEmitInheritedConstructorNote(S, Found);
12300 return;
12301
12303 // Format the template argument list into the argument string.
12304 SmallString<128> TemplateArgString;
12305 if (TemplateArgumentList *Args =
12306 DeductionFailure.getTemplateArgumentList()) {
12307 TemplateArgString = " ";
12308 TemplateArgString += S.getTemplateArgumentBindingsText(
12309 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12310 if (TemplateArgString.size() == 1)
12311 TemplateArgString.clear();
12312 }
12313
12314 // If this candidate was disabled by enable_if, say so.
12315 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12316 if (PDiag && PDiag->second.getDiagID() ==
12317 diag::err_typename_nested_not_found_enable_if) {
12318 // FIXME: Use the source range of the condition, and the fully-qualified
12319 // name of the enable_if template. These are both present in PDiag.
12320 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12321 << "'enable_if'" << TemplateArgString;
12322 return;
12323 }
12324
12325 // We found a specific requirement that disabled the enable_if.
12326 if (PDiag && PDiag->second.getDiagID() ==
12327 diag::err_typename_nested_not_found_requirement) {
12328 S.Diag(Templated->getLocation(),
12329 diag::note_ovl_candidate_disabled_by_requirement)
12330 << PDiag->second.getStringArg(0) << TemplateArgString;
12331 return;
12332 }
12333
12334 // Format the SFINAE diagnostic into the argument string.
12335 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12336 // formatted message in another diagnostic.
12337 SmallString<128> SFINAEArgString;
12338 SourceRange R;
12339 if (PDiag) {
12340 SFINAEArgString = ": ";
12341 R = SourceRange(PDiag->first, PDiag->first);
12342 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12343 }
12344
12345 S.Diag(Templated->getLocation(),
12346 diag::note_ovl_candidate_substitution_failure)
12347 << TemplateArgString << SFINAEArgString << R;
12348 MaybeEmitInheritedConstructorNote(S, Found);
12349 return;
12350 }
12351
12354 // Format the template argument list into the argument string.
12355 SmallString<128> TemplateArgString;
12356 if (TemplateArgumentList *Args =
12357 DeductionFailure.getTemplateArgumentList()) {
12358 TemplateArgString = " ";
12359 TemplateArgString += S.getTemplateArgumentBindingsText(
12360 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12361 if (TemplateArgString.size() == 1)
12362 TemplateArgString.clear();
12363 }
12364
12365 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12366 << (*DeductionFailure.getCallArgIndex() + 1)
12367 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12368 << TemplateArgString
12369 << (DeductionFailure.getResult() ==
12371 break;
12372 }
12373
12375 // FIXME: Provide a source location to indicate what we couldn't match.
12376 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12377 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12378 if (FirstTA.getKind() == TemplateArgument::Template &&
12379 SecondTA.getKind() == TemplateArgument::Template) {
12380 TemplateName FirstTN = FirstTA.getAsTemplate();
12381 TemplateName SecondTN = SecondTA.getAsTemplate();
12382 if (FirstTN.getKind() == TemplateName::Template &&
12383 SecondTN.getKind() == TemplateName::Template) {
12384 if (FirstTN.getAsTemplateDecl()->getName() ==
12385 SecondTN.getAsTemplateDecl()->getName()) {
12386 // FIXME: This fixes a bad diagnostic where both templates are named
12387 // the same. This particular case is a bit difficult since:
12388 // 1) It is passed as a string to the diagnostic printer.
12389 // 2) The diagnostic printer only attempts to find a better
12390 // name for types, not decls.
12391 // Ideally, this should folded into the diagnostic printer.
12392 S.Diag(Templated->getLocation(),
12393 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12394 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12395 return;
12396 }
12397 }
12398 }
12399
12400 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12402 return;
12403
12404 // FIXME: For generic lambda parameters, check if the function is a lambda
12405 // call operator, and if so, emit a prettier and more informative
12406 // diagnostic that mentions 'auto' and lambda in addition to
12407 // (or instead of?) the canonical template type parameters.
12408 S.Diag(Templated->getLocation(),
12409 diag::note_ovl_candidate_non_deduced_mismatch)
12410 << FirstTA << SecondTA;
12411 return;
12412 }
12413 // TODO: diagnose these individually, then kill off
12414 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12416 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12417 MaybeEmitInheritedConstructorNote(S, Found);
12418 return;
12420 S.Diag(Templated->getLocation(),
12421 diag::note_cuda_ovl_candidate_target_mismatch);
12422 return;
12423 }
12424}
12425
12426/// Diagnose a failed template-argument deduction, for function calls.
12428 unsigned NumArgs,
12429 bool TakingCandidateAddress) {
12430 assert(Cand->Function && "Candidate must be a function");
12431 FunctionDecl *Fn = Cand->Function;
12435 if (CheckArityMismatch(S, Cand, NumArgs))
12436 return;
12437 }
12438 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12439 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12440}
12441
12442/// CUDA: diagnose an invalid call across targets.
12444 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12445 assert(Cand->Function && "Candidate must be a Function.");
12446 FunctionDecl *Callee = Cand->Function;
12447
12448 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12449 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12450
12451 std::string FnDesc;
12452 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12453 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12454 Cand->getRewriteKind(), FnDesc);
12455
12456 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12457 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12458 << FnDesc /* Ignored */
12459 << CalleeTarget << CallerTarget;
12460
12461 // This could be an implicit constructor for which we could not infer the
12462 // target due to a collsion. Diagnose that case.
12463 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12464 if (Meth != nullptr && Meth->isImplicit()) {
12465 CXXRecordDecl *ParentClass = Meth->getParent();
12467
12468 switch (FnKindPair.first) {
12469 default:
12470 return;
12471 case oc_implicit_default_constructor:
12473 break;
12474 case oc_implicit_copy_constructor:
12476 break;
12477 case oc_implicit_move_constructor:
12479 break;
12480 case oc_implicit_copy_assignment:
12482 break;
12483 case oc_implicit_move_assignment:
12485 break;
12486 };
12487
12488 bool ConstRHS = false;
12489 if (Meth->getNumParams()) {
12490 if (const ReferenceType *RT =
12491 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12492 ConstRHS = RT->getPointeeType().isConstQualified();
12493 }
12494 }
12495
12496 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12497 /* ConstRHS */ ConstRHS,
12498 /* Diagnose */ true);
12499 }
12500}
12501
12503 assert(Cand->Function && "Candidate must be a function");
12504 FunctionDecl *Callee = Cand->Function;
12505 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12506
12507 S.Diag(Callee->getLocation(),
12508 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12509 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12510}
12511
12513 assert(Cand->Function && "Candidate must be a function");
12514 FunctionDecl *Fn = Cand->Function;
12516 assert(ES.isExplicit() && "not an explicit candidate");
12517
12518 unsigned Kind;
12519 switch (Fn->getDeclKind()) {
12520 case Decl::Kind::CXXConstructor:
12521 Kind = 0;
12522 break;
12523 case Decl::Kind::CXXConversion:
12524 Kind = 1;
12525 break;
12526 case Decl::Kind::CXXDeductionGuide:
12527 Kind = Fn->isImplicit() ? 0 : 2;
12528 break;
12529 default:
12530 llvm_unreachable("invalid Decl");
12531 }
12532
12533 // Note the location of the first (in-class) declaration; a redeclaration
12534 // (particularly an out-of-class definition) will typically lack the
12535 // 'explicit' specifier.
12536 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12537 FunctionDecl *First = Fn->getFirstDecl();
12538 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12539 First = Pattern->getFirstDecl();
12540
12541 S.Diag(First->getLocation(),
12542 diag::note_ovl_candidate_explicit)
12543 << Kind << (ES.getExpr() ? 1 : 0)
12544 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12545}
12546
12548 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12549 if (!DG)
12550 return;
12551 TemplateDecl *OriginTemplate =
12553 // We want to always print synthesized deduction guides for type aliases.
12554 // They would retain the explicit bit of the corresponding constructor.
12555 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12556 return;
12557 std::string FunctionProto;
12558 llvm::raw_string_ostream OS(FunctionProto);
12559 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12560 if (!Template) {
12561 // This also could be an instantiation. Find out the primary template.
12562 FunctionDecl *Pattern =
12563 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12564 if (!Pattern) {
12565 // The implicit deduction guide is built on an explicit non-template
12566 // deduction guide. Currently, this might be the case only for type
12567 // aliases.
12568 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12569 // gets merged.
12570 assert(OriginTemplate->isTypeAlias() &&
12571 "Non-template implicit deduction guides are only possible for "
12572 "type aliases");
12573 DG->print(OS);
12574 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12575 << FunctionProto;
12576 return;
12577 }
12579 assert(Template && "Cannot find the associated function template of "
12580 "CXXDeductionGuideDecl?");
12581 }
12582 Template->print(OS);
12583 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12584 << FunctionProto;
12585}
12586
12587/// Generates a 'note' diagnostic for an overload candidate. We've
12588/// already generated a primary error at the call site.
12589///
12590/// It really does need to be a single diagnostic with its caret
12591/// pointed at the candidate declaration. Yes, this creates some
12592/// major challenges of technical writing. Yes, this makes pointing
12593/// out problems with specific arguments quite awkward. It's still
12594/// better than generating twenty screens of text for every failed
12595/// overload.
12596///
12597/// It would be great to be able to express per-candidate problems
12598/// more richly for those diagnostic clients that cared, but we'd
12599/// still have to be just as careful with the default diagnostics.
12600/// \param CtorDestAS Addr space of object being constructed (for ctor
12601/// candidates only).
12603 unsigned NumArgs,
12604 bool TakingCandidateAddress,
12605 LangAS CtorDestAS = LangAS::Default) {
12606 assert(Cand->Function && "Candidate must be a function");
12607 FunctionDecl *Fn = Cand->Function;
12609 return;
12610
12611 // There is no physical candidate declaration to point to for OpenCL builtins.
12612 // Except for failed conversions, the notes are identical for each candidate,
12613 // so do not generate such notes.
12614 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12616 return;
12617
12618 // Skip implicit member functions when trying to resolve
12619 // the address of a an overload set for a function pointer.
12620 if (Cand->TookAddressOfOverload &&
12621 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12622 return;
12623
12624 // Note deleted candidates, but only if they're viable.
12625 if (Cand->Viable) {
12626 if (Fn->isDeleted()) {
12627 std::string FnDesc;
12628 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12629 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12630 Cand->getRewriteKind(), FnDesc);
12631
12632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12633 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12634 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12635 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12636 return;
12637 }
12638
12639 // We don't really have anything else to say about viable candidates.
12640 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12641 return;
12642 }
12643
12644 // If this is a synthesized deduction guide we're deducing against, add a note
12645 // for it. These deduction guides are not explicitly spelled in the source
12646 // code, so simply printing a deduction failure note mentioning synthesized
12647 // template parameters or pointing to the header of the surrounding RecordDecl
12648 // would be confusing.
12649 //
12650 // We prefer adding such notes at the end of the deduction failure because
12651 // duplicate code snippets appearing in the diagnostic would likely become
12652 // noisy.
12653 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12654
12655 switch (Cand->FailureKind) {
12658 return DiagnoseArityMismatch(S, Cand, NumArgs);
12659
12661 return DiagnoseBadDeduction(S, Cand, NumArgs,
12662 TakingCandidateAddress);
12663
12665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12666 << (Fn->getPrimaryTemplate() ? 1 : 0);
12667 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12668 return;
12669 }
12670
12672 Qualifiers QualsForPrinting;
12673 QualsForPrinting.setAddressSpace(CtorDestAS);
12674 S.Diag(Fn->getLocation(),
12675 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12676 << QualsForPrinting;
12677 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12678 return;
12679 }
12680
12684 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12685
12687 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12688 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12689 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12690 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12691
12692 // FIXME: this currently happens when we're called from SemaInit
12693 // when user-conversion overload fails. Figure out how to handle
12694 // those conditions and diagnose them well.
12695 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12696 }
12697
12699 return DiagnoseBadTarget(S, Cand);
12700
12701 case ovl_fail_enable_if:
12702 return DiagnoseFailedEnableIfAttr(S, Cand);
12703
12704 case ovl_fail_explicit:
12705 return DiagnoseFailedExplicitSpec(S, Cand);
12706
12708 // It's generally not interesting to note copy/move constructors here.
12709 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12710 return;
12711 S.Diag(Fn->getLocation(),
12712 diag::note_ovl_candidate_inherited_constructor_slice)
12713 << (Fn->getPrimaryTemplate() ? 1 : 0)
12714 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12715 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12716 return;
12717
12719 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12720 (void)Available;
12721 assert(!Available);
12722 break;
12723 }
12725 // Do nothing, these should simply be ignored.
12726 break;
12727
12729 std::string FnDesc;
12730 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12731 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12732 Cand->getRewriteKind(), FnDesc);
12733
12734 S.Diag(Fn->getLocation(),
12735 diag::note_ovl_candidate_constraints_not_satisfied)
12736 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12737 << FnDesc /* Ignored */;
12738 ConstraintSatisfaction Satisfaction;
12739 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12740 /*ForOverloadResolution=*/true))
12741 break;
12742 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12743 }
12744 }
12745}
12746
12749 return;
12750
12751 // Desugar the type of the surrogate down to a function type,
12752 // retaining as many typedefs as possible while still showing
12753 // the function type (and, therefore, its parameter types).
12754 QualType FnType = Cand->Surrogate->getConversionType();
12755 bool isLValueReference = false;
12756 bool isRValueReference = false;
12757 bool isPointer = false;
12758 if (const LValueReferenceType *FnTypeRef =
12759 FnType->getAs<LValueReferenceType>()) {
12760 FnType = FnTypeRef->getPointeeType();
12761 isLValueReference = true;
12762 } else if (const RValueReferenceType *FnTypeRef =
12763 FnType->getAs<RValueReferenceType>()) {
12764 FnType = FnTypeRef->getPointeeType();
12765 isRValueReference = true;
12766 }
12767 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12768 FnType = FnTypePtr->getPointeeType();
12769 isPointer = true;
12770 }
12771 // Desugar down to a function type.
12772 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12773 // Reconstruct the pointer/reference as appropriate.
12774 if (isPointer) FnType = S.Context.getPointerType(FnType);
12775 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12776 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12777
12778 if (!Cand->Viable &&
12780 S.Diag(Cand->Surrogate->getLocation(),
12781 diag::note_ovl_surrogate_constraints_not_satisfied)
12782 << Cand->Surrogate;
12783 ConstraintSatisfaction Satisfaction;
12784 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12785 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12786 } else {
12787 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12788 << FnType;
12789 }
12790}
12791
12792static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12793 SourceLocation OpLoc,
12794 OverloadCandidate *Cand) {
12795 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12796 std::string TypeStr("operator");
12797 TypeStr += Opc;
12798 TypeStr += "(";
12799 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12800 if (Cand->Conversions.size() == 1) {
12801 TypeStr += ")";
12802 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12803 } else {
12804 TypeStr += ", ";
12805 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12806 TypeStr += ")";
12807 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12808 }
12809}
12810
12812 OverloadCandidate *Cand) {
12813 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12814 if (ICS.isBad()) break; // all meaningless after first invalid
12815 if (!ICS.isAmbiguous()) continue;
12816
12818 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12819 }
12820}
12821
12823 if (Cand->Function)
12824 return Cand->Function->getLocation();
12825 if (Cand->IsSurrogate)
12826 return Cand->Surrogate->getLocation();
12827 return SourceLocation();
12828}
12829
12830static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12831 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12835 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12836
12840 return 1;
12841
12844 return 2;
12845
12853 return 3;
12854
12856 return 4;
12857
12859 return 5;
12860
12863 return 6;
12864 }
12865 llvm_unreachable("Unhandled deduction result");
12866}
12867
12868namespace {
12869
12870struct CompareOverloadCandidatesForDisplay {
12871 Sema &S;
12872 SourceLocation Loc;
12873 size_t NumArgs;
12875
12876 CompareOverloadCandidatesForDisplay(
12877 Sema &S, SourceLocation Loc, size_t NArgs,
12879 : S(S), NumArgs(NArgs), CSK(CSK) {}
12880
12881 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12882 // If there are too many or too few arguments, that's the high-order bit we
12883 // want to sort by, even if the immediate failure kind was something else.
12884 if (C->FailureKind == ovl_fail_too_many_arguments ||
12885 C->FailureKind == ovl_fail_too_few_arguments)
12886 return static_cast<OverloadFailureKind>(C->FailureKind);
12887
12888 if (C->Function) {
12889 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12891 if (NumArgs < C->Function->getMinRequiredArguments())
12893 }
12894
12895 return static_cast<OverloadFailureKind>(C->FailureKind);
12896 }
12897
12898 bool operator()(const OverloadCandidate *L,
12899 const OverloadCandidate *R) {
12900 // Fast-path this check.
12901 if (L == R) return false;
12902
12903 // Order first by viability.
12904 if (L->Viable) {
12905 if (!R->Viable) return true;
12906
12907 if (int Ord = CompareConversions(*L, *R))
12908 return Ord < 0;
12909 // Use other tie breakers.
12910 } else if (R->Viable)
12911 return false;
12912
12913 assert(L->Viable == R->Viable);
12914
12915 // Criteria by which we can sort non-viable candidates:
12916 if (!L->Viable) {
12917 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12918 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12919
12920 // 1. Arity mismatches come after other candidates.
12921 if (LFailureKind == ovl_fail_too_many_arguments ||
12922 LFailureKind == ovl_fail_too_few_arguments) {
12923 if (RFailureKind == ovl_fail_too_many_arguments ||
12924 RFailureKind == ovl_fail_too_few_arguments) {
12925 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12926 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12927 if (LDist == RDist) {
12928 if (LFailureKind == RFailureKind)
12929 // Sort non-surrogates before surrogates.
12930 return !L->IsSurrogate && R->IsSurrogate;
12931 // Sort candidates requiring fewer parameters than there were
12932 // arguments given after candidates requiring more parameters
12933 // than there were arguments given.
12934 return LFailureKind == ovl_fail_too_many_arguments;
12935 }
12936 return LDist < RDist;
12937 }
12938 return false;
12939 }
12940 if (RFailureKind == ovl_fail_too_many_arguments ||
12941 RFailureKind == ovl_fail_too_few_arguments)
12942 return true;
12943
12944 // 2. Bad conversions come first and are ordered by the number
12945 // of bad conversions and quality of good conversions.
12946 if (LFailureKind == ovl_fail_bad_conversion) {
12947 if (RFailureKind != ovl_fail_bad_conversion)
12948 return true;
12949
12950 // The conversion that can be fixed with a smaller number of changes,
12951 // comes first.
12952 unsigned numLFixes = L->Fix.NumConversionsFixed;
12953 unsigned numRFixes = R->Fix.NumConversionsFixed;
12954 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12955 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12956 if (numLFixes != numRFixes) {
12957 return numLFixes < numRFixes;
12958 }
12959
12960 // If there's any ordering between the defined conversions...
12961 if (int Ord = CompareConversions(*L, *R))
12962 return Ord < 0;
12963 } else if (RFailureKind == ovl_fail_bad_conversion)
12964 return false;
12965
12966 if (LFailureKind == ovl_fail_bad_deduction) {
12967 if (RFailureKind != ovl_fail_bad_deduction)
12968 return true;
12969
12971 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12972 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12973 if (LRank != RRank)
12974 return LRank < RRank;
12975 }
12976 } else if (RFailureKind == ovl_fail_bad_deduction)
12977 return false;
12978
12979 // TODO: others?
12980 }
12981
12982 // Sort everything else by location.
12983 SourceLocation LLoc = GetLocationForCandidate(L);
12984 SourceLocation RLoc = GetLocationForCandidate(R);
12985
12986 // Put candidates without locations (e.g. builtins) at the end.
12987 if (LLoc.isValid() && RLoc.isValid())
12988 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12989 if (LLoc.isValid() && !RLoc.isValid())
12990 return true;
12991 if (RLoc.isValid() && !LLoc.isValid())
12992 return false;
12993 assert(!LLoc.isValid() && !RLoc.isValid());
12994 // For builtins and other functions without locations, fallback to the order
12995 // in which they were added into the candidate set.
12996 return L < R;
12997 }
12998
12999private:
13000 struct ConversionSignals {
13001 unsigned KindRank = 0;
13003
13004 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13005 ConversionSignals Sig;
13006 Sig.KindRank = Seq.getKindRank();
13007 if (Seq.isStandard())
13008 Sig.Rank = Seq.Standard.getRank();
13009 else if (Seq.isUserDefined())
13010 Sig.Rank = Seq.UserDefined.After.getRank();
13011 // We intend StaticObjectArgumentConversion to compare the same as
13012 // StandardConversion with ICR_ExactMatch rank.
13013 return Sig;
13014 }
13015
13016 static ConversionSignals ForObjectArgument() {
13017 // We intend StaticObjectArgumentConversion to compare the same as
13018 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13019 return {};
13020 }
13021 };
13022
13023 // Returns -1 if conversions in L are considered better.
13024 // 0 if they are considered indistinguishable.
13025 // 1 if conversions in R are better.
13026 int CompareConversions(const OverloadCandidate &L,
13027 const OverloadCandidate &R) {
13028 // We cannot use `isBetterOverloadCandidate` because it is defined
13029 // according to the C++ standard and provides a partial order, but we need
13030 // a total order as this function is used in sort.
13031 assert(L.Conversions.size() == R.Conversions.size());
13032 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13033 auto LS = L.IgnoreObjectArgument && I == 0
13034 ? ConversionSignals::ForObjectArgument()
13035 : ConversionSignals::ForSequence(L.Conversions[I]);
13036 auto RS = R.IgnoreObjectArgument
13037 ? ConversionSignals::ForObjectArgument()
13038 : ConversionSignals::ForSequence(R.Conversions[I]);
13039 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13040 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13041 ? -1
13042 : 1;
13043 }
13044 // FIXME: find a way to compare templates for being more or less
13045 // specialized that provides a strict weak ordering.
13046 return 0;
13047 }
13048};
13049}
13050
13051/// CompleteNonViableCandidate - Normally, overload resolution only
13052/// computes up to the first bad conversion. Produces the FixIt set if
13053/// possible.
13054static void
13056 ArrayRef<Expr *> Args,
13058 assert(!Cand->Viable);
13059
13060 // Don't do anything on failures other than bad conversion.
13062 return;
13063
13064 // We only want the FixIts if all the arguments can be corrected.
13065 bool Unfixable = false;
13066 // Use a implicit copy initialization to check conversion fixes.
13068
13069 // Attempt to fix the bad conversion.
13070 unsigned ConvCount = Cand->Conversions.size();
13071 for (unsigned ConvIdx =
13072 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13073 : 0);
13074 /**/; ++ConvIdx) {
13075 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13076 if (Cand->Conversions[ConvIdx].isInitialized() &&
13077 Cand->Conversions[ConvIdx].isBad()) {
13078 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13079 break;
13080 }
13081 }
13082
13083 // FIXME: this should probably be preserved from the overload
13084 // operation somehow.
13085 bool SuppressUserConversions = false;
13086
13087 unsigned ConvIdx = 0;
13088 unsigned ArgIdx = 0;
13089 ArrayRef<QualType> ParamTypes;
13090 bool Reversed = Cand->isReversed();
13091
13092 if (Cand->IsSurrogate) {
13093 QualType ConvType
13095 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13096 ConvType = ConvPtrType->getPointeeType();
13097 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13098 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13099 ConvIdx = 1;
13100 } else if (Cand->Function) {
13101 ParamTypes =
13102 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13103 if (isa<CXXMethodDecl>(Cand->Function) &&
13106 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13107 ConvIdx = 1;
13109 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13111 OO_Subscript)
13112 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13113 ArgIdx = 1;
13114 }
13115 } else {
13116 // Builtin operator.
13117 assert(ConvCount <= 3);
13118 ParamTypes = Cand->BuiltinParamTypes;
13119 }
13120
13121 // Fill in the rest of the conversions.
13122 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13123 ConvIdx != ConvCount && ArgIdx < Args.size();
13124 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13125 if (Cand->Conversions[ConvIdx].isInitialized()) {
13126 // We've already checked this conversion.
13127 } else if (ParamIdx < ParamTypes.size()) {
13128 if (ParamTypes[ParamIdx]->isDependentType())
13129 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13130 Args[ArgIdx]->getType());
13131 else {
13132 Cand->Conversions[ConvIdx] =
13133 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13134 SuppressUserConversions,
13135 /*InOverloadResolution=*/true,
13136 /*AllowObjCWritebackConversion=*/
13137 S.getLangOpts().ObjCAutoRefCount);
13138 // Store the FixIt in the candidate if it exists.
13139 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13140 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13141 }
13142 } else
13143 Cand->Conversions[ConvIdx].setEllipsis();
13144 }
13145}
13146
13149 SourceLocation OpLoc,
13150 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13151
13153
13154 // Sort the candidates by viability and position. Sorting directly would
13155 // be prohibitive, so we make a set of pointers and sort those.
13157 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13158 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13159 Cand != LastCand; ++Cand) {
13160 if (!Filter(*Cand))
13161 continue;
13162 switch (OCD) {
13163 case OCD_AllCandidates:
13164 if (!Cand->Viable) {
13165 if (!Cand->Function && !Cand->IsSurrogate) {
13166 // This a non-viable builtin candidate. We do not, in general,
13167 // want to list every possible builtin candidate.
13168 continue;
13169 }
13170 CompleteNonViableCandidate(S, Cand, Args, Kind);
13171 }
13172 break;
13173
13175 if (!Cand->Viable)
13176 continue;
13177 break;
13178
13180 if (!Cand->Best)
13181 continue;
13182 break;
13183 }
13184
13185 Cands.push_back(Cand);
13186 }
13187
13188 llvm::stable_sort(
13189 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13190
13191 return Cands;
13192}
13193
13195 SourceLocation OpLoc) {
13196 bool DeferHint = false;
13197 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13198 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13199 // host device candidates.
13200 auto WrongSidedCands =
13201 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13202 return (Cand.Viable == false &&
13204 (Cand.Function &&
13205 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13206 Cand.Function->template hasAttr<CUDADeviceAttr>());
13207 });
13208 DeferHint = !WrongSidedCands.empty();
13209 }
13210 return DeferHint;
13211}
13212
13213/// When overload resolution fails, prints diagnostic messages containing the
13214/// candidates in the candidate set.
13217 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13218 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13219
13220 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13221
13222 {
13223 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13224 S.Diag(PD.first, PD.second);
13225 }
13226
13227 // In WebAssembly we don't want to emit further diagnostics if a table is
13228 // passed as an argument to a function.
13229 bool NoteCands = true;
13230 for (const Expr *Arg : Args) {
13231 if (Arg->getType()->isWebAssemblyTableType())
13232 NoteCands = false;
13233 }
13234
13235 if (NoteCands)
13236 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13237
13238 if (OCD == OCD_AmbiguousCandidates)
13240 {Candidates.begin(), Candidates.end()});
13241}
13242
13245 StringRef Opc, SourceLocation OpLoc) {
13246 bool ReportedAmbiguousConversions = false;
13247
13248 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13249 unsigned CandsShown = 0;
13250 auto I = Cands.begin(), E = Cands.end();
13251 for (; I != E; ++I) {
13252 OverloadCandidate *Cand = *I;
13253
13254 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13255 ShowOverloads == Ovl_Best) {
13256 break;
13257 }
13258 ++CandsShown;
13259
13260 if (Cand->Function)
13261 NoteFunctionCandidate(S, Cand, Args.size(),
13262 Kind == CSK_AddressOfOverloadSet, DestAS);
13263 else if (Cand->IsSurrogate)
13264 NoteSurrogateCandidate(S, Cand);
13265 else {
13266 assert(Cand->Viable &&
13267 "Non-viable built-in candidates are not added to Cands.");
13268 // Generally we only see ambiguities including viable builtin
13269 // operators if overload resolution got screwed up by an
13270 // ambiguous user-defined conversion.
13271 //
13272 // FIXME: It's quite possible for different conversions to see
13273 // different ambiguities, though.
13274 if (!ReportedAmbiguousConversions) {
13275 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13276 ReportedAmbiguousConversions = true;
13277 }
13278
13279 // If this is a viable builtin, print it.
13280 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13281 }
13282 }
13283
13284 // Inform S.Diags that we've shown an overload set with N elements. This may
13285 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13286 S.Diags.overloadCandidatesShown(CandsShown);
13287
13288 if (I != E) {
13289 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13290 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13291 }
13292}
13293
13294static SourceLocation
13296 return Cand->Specialization ? Cand->Specialization->getLocation()
13297 : SourceLocation();
13298}
13299
13300namespace {
13301struct CompareTemplateSpecCandidatesForDisplay {
13302 Sema &S;
13303 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13304
13305 bool operator()(const TemplateSpecCandidate *L,
13306 const TemplateSpecCandidate *R) {
13307 // Fast-path this check.
13308 if (L == R)
13309 return false;
13310
13311 // Assuming that both candidates are not matches...
13312
13313 // Sort by the ranking of deduction failures.
13317
13318 // Sort everything else by location.
13319 SourceLocation LLoc = GetLocationForCandidate(L);
13320 SourceLocation RLoc = GetLocationForCandidate(R);
13321
13322 // Put candidates without locations (e.g. builtins) at the end.
13323 if (LLoc.isInvalid())
13324 return false;
13325 if (RLoc.isInvalid())
13326 return true;
13327
13328 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13329 }
13330};
13331}
13332
13333/// Diagnose a template argument deduction failure.
13334/// We are treating these failures as overload failures due to bad
13335/// deductions.
13337 bool ForTakingAddress) {
13339 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13340}
13341
13342void TemplateSpecCandidateSet::destroyCandidates() {
13343 for (iterator i = begin(), e = end(); i != e; ++i) {
13344 i->DeductionFailure.Destroy();
13345 }
13346}
13347
13349 destroyCandidates();
13350 Candidates.clear();
13351}
13352
13353/// NoteCandidates - When no template specialization match is found, prints
13354/// diagnostic messages containing the non-matching specializations that form
13355/// the candidate set.
13356/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13357/// OCD == OCD_AllCandidates and Cand->Viable == false.
13359 // Sort the candidates by position (assuming no candidate is a match).
13360 // Sorting directly would be prohibitive, so we make a set of pointers
13361 // and sort those.
13363 Cands.reserve(size());
13364 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13365 if (Cand->Specialization)
13366 Cands.push_back(Cand);
13367 // Otherwise, this is a non-matching builtin candidate. We do not,
13368 // in general, want to list every possible builtin candidate.
13369 }
13370
13371 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13372
13373 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13374 // for generalization purposes (?).
13375 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13376
13378 unsigned CandsShown = 0;
13379 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13380 TemplateSpecCandidate *Cand = *I;
13381
13382 // Set an arbitrary limit on the number of candidates we'll spam
13383 // the user with. FIXME: This limit should depend on details of the
13384 // candidate list.
13385 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13386 break;
13387 ++CandsShown;
13388
13389 assert(Cand->Specialization &&
13390 "Non-matching built-in candidates are not added to Cands.");
13391 Cand->NoteDeductionFailure(S, ForTakingAddress);
13392 }
13393
13394 if (I != E)
13395 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13396}
13397
13398// [PossiblyAFunctionType] --> [Return]
13399// NonFunctionType --> NonFunctionType
13400// R (A) --> R(A)
13401// R (*)(A) --> R (A)
13402// R (&)(A) --> R (A)
13403// R (S::*)(A) --> R (A)
13405 QualType Ret = PossiblyAFunctionType;
13406 if (const PointerType *ToTypePtr =
13407 PossiblyAFunctionType->getAs<PointerType>())
13408 Ret = ToTypePtr->getPointeeType();
13409 else if (const ReferenceType *ToTypeRef =
13410 PossiblyAFunctionType->getAs<ReferenceType>())
13411 Ret = ToTypeRef->getPointeeType();
13412 else if (const MemberPointerType *MemTypePtr =
13413 PossiblyAFunctionType->getAs<MemberPointerType>())
13414 Ret = MemTypePtr->getPointeeType();
13415 Ret =
13416 Context.getCanonicalType(Ret).getUnqualifiedType();
13417 return Ret;
13418}
13419
13421 bool Complain = true) {
13422 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13423 S.DeduceReturnType(FD, Loc, Complain))
13424 return true;
13425
13426 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13427 if (S.getLangOpts().CPlusPlus17 &&
13428 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13429 !S.ResolveExceptionSpec(Loc, FPT))
13430 return true;
13431
13432 return false;
13433}
13434
13435namespace {
13436// A helper class to help with address of function resolution
13437// - allows us to avoid passing around all those ugly parameters
13438class AddressOfFunctionResolver {
13439 Sema& S;
13440 Expr* SourceExpr;
13441 const QualType& TargetType;
13442 QualType TargetFunctionType; // Extracted function type from target type
13443
13444 bool Complain;
13445 //DeclAccessPair& ResultFunctionAccessPair;
13446 ASTContext& Context;
13447
13448 bool TargetTypeIsNonStaticMemberFunction;
13449 bool FoundNonTemplateFunction;
13450 bool StaticMemberFunctionFromBoundPointer;
13451 bool HasComplained;
13452
13453 OverloadExpr::FindResult OvlExprInfo;
13454 OverloadExpr *OvlExpr;
13455 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13456 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13457 TemplateSpecCandidateSet FailedCandidates;
13458
13459public:
13460 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13461 const QualType &TargetType, bool Complain)
13462 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13463 Complain(Complain), Context(S.getASTContext()),
13464 TargetTypeIsNonStaticMemberFunction(
13465 !!TargetType->getAs<MemberPointerType>()),
13466 FoundNonTemplateFunction(false),
13467 StaticMemberFunctionFromBoundPointer(false),
13468 HasComplained(false),
13469 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13470 OvlExpr(OvlExprInfo.Expression),
13471 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13472 ExtractUnqualifiedFunctionTypeFromTargetType();
13473
13474 if (TargetFunctionType->isFunctionType()) {
13475 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13476 if (!UME->isImplicitAccess() &&
13478 StaticMemberFunctionFromBoundPointer = true;
13479 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13480 DeclAccessPair dap;
13481 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13482 OvlExpr, false, &dap)) {
13483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13484 if (!Method->isStatic()) {
13485 // If the target type is a non-function type and the function found
13486 // is a non-static member function, pretend as if that was the
13487 // target, it's the only possible type to end up with.
13488 TargetTypeIsNonStaticMemberFunction = true;
13489
13490 // And skip adding the function if its not in the proper form.
13491 // We'll diagnose this due to an empty set of functions.
13492 if (!OvlExprInfo.HasFormOfMemberPointer)
13493 return;
13494 }
13495
13496 Matches.push_back(std::make_pair(dap, Fn));
13497 }
13498 return;
13499 }
13500
13501 if (OvlExpr->hasExplicitTemplateArgs())
13502 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13503
13504 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13505 // C++ [over.over]p4:
13506 // If more than one function is selected, [...]
13507 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13508 if (FoundNonTemplateFunction) {
13509 EliminateAllTemplateMatches();
13510 EliminateLessPartialOrderingConstrainedMatches();
13511 } else
13512 EliminateAllExceptMostSpecializedTemplate();
13513 }
13514 }
13515
13516 if (S.getLangOpts().CUDA && Matches.size() > 1)
13517 EliminateSuboptimalCudaMatches();
13518 }
13519
13520 bool hasComplained() const { return HasComplained; }
13521
13522private:
13523 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13524 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13525 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13526 }
13527
13528 /// \return true if A is considered a better overload candidate for the
13529 /// desired type than B.
13530 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13531 // If A doesn't have exactly the correct type, we don't want to classify it
13532 // as "better" than anything else. This way, the user is required to
13533 // disambiguate for us if there are multiple candidates and no exact match.
13534 return candidateHasExactlyCorrectType(A) &&
13535 (!candidateHasExactlyCorrectType(B) ||
13536 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13537 }
13538
13539 /// \return true if we were able to eliminate all but one overload candidate,
13540 /// false otherwise.
13541 bool eliminiateSuboptimalOverloadCandidates() {
13542 // Same algorithm as overload resolution -- one pass to pick the "best",
13543 // another pass to be sure that nothing is better than the best.
13544 auto Best = Matches.begin();
13545 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13546 if (isBetterCandidate(I->second, Best->second))
13547 Best = I;
13548
13549 const FunctionDecl *BestFn = Best->second;
13550 auto IsBestOrInferiorToBest = [this, BestFn](
13551 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13552 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13553 };
13554
13555 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13556 // option, so we can potentially give the user a better error
13557 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13558 return false;
13559 Matches[0] = *Best;
13560 Matches.resize(1);
13561 return true;
13562 }
13563
13564 bool isTargetTypeAFunction() const {
13565 return TargetFunctionType->isFunctionType();
13566 }
13567
13568 // [ToType] [Return]
13569
13570 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13571 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13572 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13573 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13574 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13575 }
13576
13577 // return true if any matching specializations were found
13578 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13579 const DeclAccessPair& CurAccessFunPair) {
13580 if (CXXMethodDecl *Method
13581 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13582 // Skip non-static function templates when converting to pointer, and
13583 // static when converting to member pointer.
13584 bool CanConvertToFunctionPointer =
13585 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13586 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13587 return false;
13588 }
13589 else if (TargetTypeIsNonStaticMemberFunction)
13590 return false;
13591
13592 // C++ [over.over]p2:
13593 // If the name is a function template, template argument deduction is
13594 // done (14.8.2.2), and if the argument deduction succeeds, the
13595 // resulting template argument list is used to generate a single
13596 // function template specialization, which is added to the set of
13597 // overloaded functions considered.
13598 FunctionDecl *Specialization = nullptr;
13599 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13601 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13602 Specialization, Info, /*IsAddressOfFunction*/ true);
13603 Result != TemplateDeductionResult::Success) {
13604 // Make a note of the failed deduction for diagnostics.
13605 FailedCandidates.addCandidate()
13606 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13607 MakeDeductionFailureInfo(Context, Result, Info));
13608 return false;
13609 }
13610
13611 // Template argument deduction ensures that we have an exact match or
13612 // compatible pointer-to-function arguments that would be adjusted by ICS.
13613 // This function template specicalization works.
13615 Context.getCanonicalType(Specialization->getType()),
13616 Context.getCanonicalType(TargetFunctionType)));
13617
13619 return false;
13620
13621 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13622 return true;
13623 }
13624
13625 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13626 const DeclAccessPair& CurAccessFunPair) {
13627 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13628 // Skip non-static functions when converting to pointer, and static
13629 // when converting to member pointer.
13630 bool CanConvertToFunctionPointer =
13631 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13632 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13633 return false;
13634 }
13635 else if (TargetTypeIsNonStaticMemberFunction)
13636 return false;
13637
13638 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13639 if (S.getLangOpts().CUDA) {
13640 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13641 if (!(Caller && Caller->isImplicit()) &&
13642 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13643 return false;
13644 }
13645 if (FunDecl->isMultiVersion()) {
13646 const auto *TA = FunDecl->getAttr<TargetAttr>();
13647 if (TA && !TA->isDefaultVersion())
13648 return false;
13649 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13650 if (TVA && !TVA->isDefaultVersion())
13651 return false;
13652 }
13653
13654 // If any candidate has a placeholder return type, trigger its deduction
13655 // now.
13656 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13657 Complain)) {
13658 HasComplained |= Complain;
13659 return false;
13660 }
13661
13662 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13663 return false;
13664
13665 // If we're in C, we need to support types that aren't exactly identical.
13666 if (!S.getLangOpts().CPlusPlus ||
13667 candidateHasExactlyCorrectType(FunDecl)) {
13668 Matches.push_back(std::make_pair(
13669 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13670 FoundNonTemplateFunction = true;
13671 return true;
13672 }
13673 }
13674
13675 return false;
13676 }
13677
13678 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13679 bool Ret = false;
13680
13681 // If the overload expression doesn't have the form of a pointer to
13682 // member, don't try to convert it to a pointer-to-member type.
13683 if (IsInvalidFormOfPointerToMemberFunction())
13684 return false;
13685
13686 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13687 E = OvlExpr->decls_end();
13688 I != E; ++I) {
13689 // Look through any using declarations to find the underlying function.
13690 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13691
13692 // C++ [over.over]p3:
13693 // Non-member functions and static member functions match
13694 // targets of type "pointer-to-function" or "reference-to-function."
13695 // Nonstatic member functions match targets of
13696 // type "pointer-to-member-function."
13697 // Note that according to DR 247, the containing class does not matter.
13698 if (FunctionTemplateDecl *FunctionTemplate
13699 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13700 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13701 Ret = true;
13702 }
13703 // If we have explicit template arguments supplied, skip non-templates.
13704 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13705 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13706 Ret = true;
13707 }
13708 assert(Ret || Matches.empty());
13709 return Ret;
13710 }
13711
13712 void EliminateAllExceptMostSpecializedTemplate() {
13713 // [...] and any given function template specialization F1 is
13714 // eliminated if the set contains a second function template
13715 // specialization whose function template is more specialized
13716 // than the function template of F1 according to the partial
13717 // ordering rules of 14.5.5.2.
13718
13719 // The algorithm specified above is quadratic. We instead use a
13720 // two-pass algorithm (similar to the one used to identify the
13721 // best viable function in an overload set) that identifies the
13722 // best function template (if it exists).
13723
13724 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13725 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13726 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13727
13728 // TODO: It looks like FailedCandidates does not serve much purpose
13729 // here, since the no_viable diagnostic has index 0.
13730 UnresolvedSetIterator Result = S.getMostSpecialized(
13731 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13732 SourceExpr->getBeginLoc(), S.PDiag(),
13733 S.PDiag(diag::err_addr_ovl_ambiguous)
13734 << Matches[0].second->getDeclName(),
13735 S.PDiag(diag::note_ovl_candidate)
13736 << (unsigned)oc_function << (unsigned)ocs_described_template,
13737 Complain, TargetFunctionType);
13738
13739 if (Result != MatchesCopy.end()) {
13740 // Make it the first and only element
13741 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13742 Matches[0].second = cast<FunctionDecl>(*Result);
13743 Matches.resize(1);
13744 } else
13745 HasComplained |= Complain;
13746 }
13747
13748 void EliminateAllTemplateMatches() {
13749 // [...] any function template specializations in the set are
13750 // eliminated if the set also contains a non-template function, [...]
13751 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13752 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13753 ++I;
13754 else {
13755 Matches[I] = Matches[--N];
13756 Matches.resize(N);
13757 }
13758 }
13759 }
13760
13761 void EliminateLessPartialOrderingConstrainedMatches() {
13762 // C++ [over.over]p5:
13763 // [...] Any given non-template function F0 is eliminated if the set
13764 // contains a second non-template function that is more
13765 // partial-ordering-constrained than F0. [...]
13766 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13767 "Call EliminateAllTemplateMatches() first");
13768 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13769 Results.push_back(Matches[0]);
13770 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13771 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13772 FunctionDecl *F = getMorePartialOrderingConstrained(
13773 S, Matches[I].second, Results[0].second,
13774 /*IsFn1Reversed=*/false,
13775 /*IsFn2Reversed=*/false);
13776 if (!F) {
13777 Results.push_back(Matches[I]);
13778 continue;
13779 }
13780 if (F == Matches[I].second) {
13781 Results.clear();
13782 Results.push_back(Matches[I]);
13783 }
13784 }
13785 std::swap(Matches, Results);
13786 }
13787
13788 void EliminateSuboptimalCudaMatches() {
13789 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13790 Matches);
13791 }
13792
13793public:
13794 void ComplainNoMatchesFound() const {
13795 assert(Matches.empty());
13796 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13797 << OvlExpr->getName() << TargetFunctionType
13798 << OvlExpr->getSourceRange();
13799 if (FailedCandidates.empty())
13800 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13801 /*TakingAddress=*/true);
13802 else {
13803 // We have some deduction failure messages. Use them to diagnose
13804 // the function templates, and diagnose the non-template candidates
13805 // normally.
13806 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13807 IEnd = OvlExpr->decls_end();
13808 I != IEnd; ++I)
13809 if (FunctionDecl *Fun =
13810 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13812 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13813 /*TakingAddress=*/true);
13814 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13815 }
13816 }
13817
13818 bool IsInvalidFormOfPointerToMemberFunction() const {
13819 return TargetTypeIsNonStaticMemberFunction &&
13820 !OvlExprInfo.HasFormOfMemberPointer;
13821 }
13822
13823 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13824 // TODO: Should we condition this on whether any functions might
13825 // have matched, or is it more appropriate to do that in callers?
13826 // TODO: a fixit wouldn't hurt.
13827 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13828 << TargetType << OvlExpr->getSourceRange();
13829 }
13830
13831 bool IsStaticMemberFunctionFromBoundPointer() const {
13832 return StaticMemberFunctionFromBoundPointer;
13833 }
13834
13835 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13836 S.Diag(OvlExpr->getBeginLoc(),
13837 diag::err_invalid_form_pointer_member_function)
13838 << OvlExpr->getSourceRange();
13839 }
13840
13841 void ComplainOfInvalidConversion() const {
13842 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13843 << OvlExpr->getName() << TargetType;
13844 }
13845
13846 void ComplainMultipleMatchesFound() const {
13847 assert(Matches.size() > 1);
13848 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13849 << OvlExpr->getName() << OvlExpr->getSourceRange();
13850 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13851 /*TakingAddress=*/true);
13852 }
13853
13854 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13855
13856 int getNumMatches() const { return Matches.size(); }
13857
13858 FunctionDecl* getMatchingFunctionDecl() const {
13859 if (Matches.size() != 1) return nullptr;
13860 return Matches[0].second;
13861 }
13862
13863 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13864 if (Matches.size() != 1) return nullptr;
13865 return &Matches[0].first;
13866 }
13867};
13868}
13869
13870FunctionDecl *
13872 QualType TargetType,
13873 bool Complain,
13874 DeclAccessPair &FoundResult,
13875 bool *pHadMultipleCandidates) {
13876 assert(AddressOfExpr->getType() == Context.OverloadTy);
13877
13878 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13879 Complain);
13880 int NumMatches = Resolver.getNumMatches();
13881 FunctionDecl *Fn = nullptr;
13882 bool ShouldComplain = Complain && !Resolver.hasComplained();
13883 if (NumMatches == 0 && ShouldComplain) {
13884 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13885 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13886 else
13887 Resolver.ComplainNoMatchesFound();
13888 }
13889 else if (NumMatches > 1 && ShouldComplain)
13890 Resolver.ComplainMultipleMatchesFound();
13891 else if (NumMatches == 1) {
13892 Fn = Resolver.getMatchingFunctionDecl();
13893 assert(Fn);
13894 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13895 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13896 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13897 if (Complain) {
13898 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13899 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13900 else
13901 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13902 }
13903 }
13904
13905 if (pHadMultipleCandidates)
13906 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13907 return Fn;
13908}
13909
13913 OverloadExpr *Ovl = R.Expression;
13914 bool IsResultAmbiguous = false;
13915 FunctionDecl *Result = nullptr;
13916 DeclAccessPair DAP;
13917 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13918
13919 // Return positive for better, negative for worse, 0 for equal preference.
13920 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13921 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13922 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13923 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13924 };
13925
13926 // Don't use the AddressOfResolver because we're specifically looking for
13927 // cases where we have one overload candidate that lacks
13928 // enable_if/pass_object_size/...
13929 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13930 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13931 if (!FD)
13932 return nullptr;
13933
13935 continue;
13936
13937 // If we found a better result, update Result.
13938 auto FoundBetter = [&]() {
13939 IsResultAmbiguous = false;
13940 DAP = I.getPair();
13941 Result = FD;
13942 };
13943
13944 // We have more than one result - see if it is more
13945 // partial-ordering-constrained than the previous one.
13946 if (Result) {
13947 // Check CUDA preference first. If the candidates have differennt CUDA
13948 // preference, choose the one with higher CUDA preference. Otherwise,
13949 // choose the one with more constraints.
13950 if (getLangOpts().CUDA) {
13951 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13952 // FD has different preference than Result.
13953 if (PreferenceByCUDA != 0) {
13954 // FD is more preferable than Result.
13955 if (PreferenceByCUDA > 0)
13956 FoundBetter();
13957 continue;
13958 }
13959 }
13960 // FD has the same CUDA preference than Result. Continue to check
13961 // constraints.
13962
13963 // C++ [over.over]p5:
13964 // [...] Any given non-template function F0 is eliminated if the set
13965 // contains a second non-template function that is more
13966 // partial-ordering-constrained than F0 [...]
13967 FunctionDecl *MoreConstrained =
13969 /*IsFn1Reversed=*/false,
13970 /*IsFn2Reversed=*/false);
13971 if (MoreConstrained != FD) {
13972 if (!MoreConstrained) {
13973 IsResultAmbiguous = true;
13974 AmbiguousDecls.push_back(FD);
13975 }
13976 continue;
13977 }
13978 // FD is more constrained - replace Result with it.
13979 }
13980 FoundBetter();
13981 }
13982
13983 if (IsResultAmbiguous)
13984 return nullptr;
13985
13986 if (Result) {
13987 // We skipped over some ambiguous declarations which might be ambiguous with
13988 // the selected result.
13989 for (FunctionDecl *Skipped : AmbiguousDecls) {
13990 // If skipped candidate has different CUDA preference than the result,
13991 // there is no ambiguity. Otherwise check whether they have different
13992 // constraints.
13993 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13994 continue;
13995 if (!getMoreConstrainedFunction(Skipped, Result))
13996 return nullptr;
13997 }
13998 Pair = DAP;
13999 }
14000 return Result;
14001}
14002
14004 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14005 Expr *E = SrcExpr.get();
14006 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14007
14008 DeclAccessPair DAP;
14010 if (!Found || Found->isCPUDispatchMultiVersion() ||
14011 Found->isCPUSpecificMultiVersion())
14012 return false;
14013
14014 // Emitting multiple diagnostics for a function that is both inaccessible and
14015 // unavailable is consistent with our behavior elsewhere. So, always check
14016 // for both.
14020 if (Res.isInvalid())
14021 return false;
14022 Expr *Fixed = Res.get();
14023 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14024 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14025 else
14026 SrcExpr = Fixed;
14027 return true;
14028}
14029
14031 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14032 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14033 // C++ [over.over]p1:
14034 // [...] [Note: any redundant set of parentheses surrounding the
14035 // overloaded function name is ignored (5.1). ]
14036 // C++ [over.over]p1:
14037 // [...] The overloaded function name can be preceded by the &
14038 // operator.
14039
14040 // If we didn't actually find any template-ids, we're done.
14041 if (!ovl->hasExplicitTemplateArgs())
14042 return nullptr;
14043
14044 TemplateArgumentListInfo ExplicitTemplateArgs;
14045 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14046
14047 // Look through all of the overloaded functions, searching for one
14048 // whose type matches exactly.
14049 FunctionDecl *Matched = nullptr;
14050 for (UnresolvedSetIterator I = ovl->decls_begin(),
14051 E = ovl->decls_end(); I != E; ++I) {
14052 // C++0x [temp.arg.explicit]p3:
14053 // [...] In contexts where deduction is done and fails, or in contexts
14054 // where deduction is not done, if a template argument list is
14055 // specified and it, along with any default template arguments,
14056 // identifies a single function template specialization, then the
14057 // template-id is an lvalue for the function template specialization.
14059 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14060 if (!FunctionTemplate)
14061 continue;
14062
14063 // C++ [over.over]p2:
14064 // If the name is a function template, template argument deduction is
14065 // done (14.8.2.2), and if the argument deduction succeeds, the
14066 // resulting template argument list is used to generate a single
14067 // function template specialization, which is added to the set of
14068 // overloaded functions considered.
14069 FunctionDecl *Specialization = nullptr;
14070 TemplateDeductionInfo Info(ovl->getNameLoc());
14072 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14073 /*IsAddressOfFunction*/ true);
14075 // Make a note of the failed deduction for diagnostics.
14076 if (FailedTSC)
14077 FailedTSC->addCandidate().set(
14078 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14080 continue;
14081 }
14082
14083 assert(Specialization && "no specialization and no error?");
14084
14085 // C++ [temp.deduct.call]p6:
14086 // [...] If all successful deductions yield the same deduced A, that
14087 // deduced A is the result of deduction; otherwise, the parameter is
14088 // treated as a non-deduced context.
14089 if (Matched) {
14090 if (ForTypeDeduction &&
14092 Specialization->getType()))
14093 continue;
14094 // Multiple matches; we can't resolve to a single declaration.
14095 if (Complain) {
14096 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14097 << ovl->getName();
14099 }
14100 return nullptr;
14101 }
14102
14103 Matched = Specialization;
14104 if (FoundResult) *FoundResult = I.getPair();
14105 }
14106
14107 if (Matched &&
14108 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14109 return nullptr;
14110
14111 return Matched;
14112}
14113
14115 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14116 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14117 unsigned DiagIDForComplaining) {
14118 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14119
14121
14122 DeclAccessPair found;
14123 ExprResult SingleFunctionExpression;
14125 ovl.Expression, /*complain*/ false, &found)) {
14126 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14127 SrcExpr = ExprError();
14128 return true;
14129 }
14130
14131 // It is only correct to resolve to an instance method if we're
14132 // resolving a form that's permitted to be a pointer to member.
14133 // Otherwise we'll end up making a bound member expression, which
14134 // is illegal in all the contexts we resolve like this.
14135 if (!ovl.HasFormOfMemberPointer &&
14136 isa<CXXMethodDecl>(fn) &&
14137 cast<CXXMethodDecl>(fn)->isInstance()) {
14138 if (!complain) return false;
14139
14140 Diag(ovl.Expression->getExprLoc(),
14141 diag::err_bound_member_function)
14142 << 0 << ovl.Expression->getSourceRange();
14143
14144 // TODO: I believe we only end up here if there's a mix of
14145 // static and non-static candidates (otherwise the expression
14146 // would have 'bound member' type, not 'overload' type).
14147 // Ideally we would note which candidate was chosen and why
14148 // the static candidates were rejected.
14149 SrcExpr = ExprError();
14150 return true;
14151 }
14152
14153 // Fix the expression to refer to 'fn'.
14154 SingleFunctionExpression =
14155 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14156
14157 // If desired, do function-to-pointer decay.
14158 if (doFunctionPointerConversion) {
14159 SingleFunctionExpression =
14160 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14161 if (SingleFunctionExpression.isInvalid()) {
14162 SrcExpr = ExprError();
14163 return true;
14164 }
14165 }
14166 }
14167
14168 if (!SingleFunctionExpression.isUsable()) {
14169 if (complain) {
14170 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14171 << ovl.Expression->getName()
14172 << DestTypeForComplaining
14173 << OpRangeForComplaining
14175 NoteAllOverloadCandidates(SrcExpr.get());
14176
14177 SrcExpr = ExprError();
14178 return true;
14179 }
14180
14181 return false;
14182 }
14183
14184 SrcExpr = SingleFunctionExpression;
14185 return true;
14186}
14187
14188/// Add a single candidate to the overload set.
14190 DeclAccessPair FoundDecl,
14191 TemplateArgumentListInfo *ExplicitTemplateArgs,
14192 ArrayRef<Expr *> Args,
14193 OverloadCandidateSet &CandidateSet,
14194 bool PartialOverloading,
14195 bool KnownValid) {
14196 NamedDecl *Callee = FoundDecl.getDecl();
14197 if (isa<UsingShadowDecl>(Callee))
14198 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14199
14200 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14201 if (ExplicitTemplateArgs) {
14202 assert(!KnownValid && "Explicit template arguments?");
14203 return;
14204 }
14205 // Prevent ill-formed function decls to be added as overload candidates.
14206 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14207 return;
14208
14209 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14210 /*SuppressUserConversions=*/false,
14211 PartialOverloading);
14212 return;
14213 }
14214
14215 if (FunctionTemplateDecl *FuncTemplate
14216 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14217 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14218 ExplicitTemplateArgs, Args, CandidateSet,
14219 /*SuppressUserConversions=*/false,
14220 PartialOverloading);
14221 return;
14222 }
14223
14224 assert(!KnownValid && "unhandled case in overloaded call candidate");
14225}
14226
14228 ArrayRef<Expr *> Args,
14229 OverloadCandidateSet &CandidateSet,
14230 bool PartialOverloading) {
14231
14232#ifndef NDEBUG
14233 // Verify that ArgumentDependentLookup is consistent with the rules
14234 // in C++0x [basic.lookup.argdep]p3:
14235 //
14236 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14237 // and let Y be the lookup set produced by argument dependent
14238 // lookup (defined as follows). If X contains
14239 //
14240 // -- a declaration of a class member, or
14241 //
14242 // -- a block-scope function declaration that is not a
14243 // using-declaration, or
14244 //
14245 // -- a declaration that is neither a function or a function
14246 // template
14247 //
14248 // then Y is empty.
14249
14250 if (ULE->requiresADL()) {
14252 E = ULE->decls_end(); I != E; ++I) {
14253 assert(!(*I)->getDeclContext()->isRecord());
14254 assert(isa<UsingShadowDecl>(*I) ||
14255 !(*I)->getDeclContext()->isFunctionOrMethod());
14256 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14257 }
14258 }
14259#endif
14260
14261 // It would be nice to avoid this copy.
14262 TemplateArgumentListInfo TABuffer;
14263 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14264 if (ULE->hasExplicitTemplateArgs()) {
14265 ULE->copyTemplateArgumentsInto(TABuffer);
14266 ExplicitTemplateArgs = &TABuffer;
14267 }
14268
14270 E = ULE->decls_end(); I != E; ++I)
14271 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14272 CandidateSet, PartialOverloading,
14273 /*KnownValid*/ true);
14274
14275 if (ULE->requiresADL())
14277 Args, ExplicitTemplateArgs,
14278 CandidateSet, PartialOverloading);
14279}
14280
14282 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14283 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14284 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14285 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14286 CandidateSet, false, /*KnownValid*/ false);
14287}
14288
14289/// Determine whether a declaration with the specified name could be moved into
14290/// a different namespace.
14292 switch (Name.getCXXOverloadedOperator()) {
14293 case OO_New: case OO_Array_New:
14294 case OO_Delete: case OO_Array_Delete:
14295 return false;
14296
14297 default:
14298 return true;
14299 }
14300}
14301
14302/// Attempt to recover from an ill-formed use of a non-dependent name in a
14303/// template, where the non-dependent name was declared after the template
14304/// was defined. This is common in code written for a compilers which do not
14305/// correctly implement two-stage name lookup.
14306///
14307/// Returns true if a viable candidate was found and a diagnostic was issued.
14309 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14311 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14312 CXXRecordDecl **FoundInClass = nullptr) {
14313 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14314 return false;
14315
14316 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14317 if (DC->isTransparentContext())
14318 continue;
14319
14320 SemaRef.LookupQualifiedName(R, DC);
14321
14322 if (!R.empty()) {
14324
14325 OverloadCandidateSet Candidates(FnLoc, CSK);
14326 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14327 Candidates);
14328
14331 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14332
14333 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14334 // We either found non-function declarations or a best viable function
14335 // at class scope. A class-scope lookup result disables ADL. Don't
14336 // look past this, but let the caller know that we found something that
14337 // either is, or might be, usable in this class.
14338 if (FoundInClass) {
14339 *FoundInClass = RD;
14340 if (OR == OR_Success) {
14341 R.clear();
14342 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14343 R.resolveKind();
14344 }
14345 }
14346 return false;
14347 }
14348
14349 if (OR != OR_Success) {
14350 // There wasn't a unique best function or function template.
14351 return false;
14352 }
14353
14354 // Find the namespaces where ADL would have looked, and suggest
14355 // declaring the function there instead.
14356 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14357 Sema::AssociatedClassSet AssociatedClasses;
14358 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14359 AssociatedNamespaces,
14360 AssociatedClasses);
14361 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14363 DeclContext *Std = SemaRef.getStdNamespace();
14364 for (Sema::AssociatedNamespaceSet::iterator
14365 it = AssociatedNamespaces.begin(),
14366 end = AssociatedNamespaces.end(); it != end; ++it) {
14367 // Never suggest declaring a function within namespace 'std'.
14368 if (Std && Std->Encloses(*it))
14369 continue;
14370
14371 // Never suggest declaring a function within a namespace with a
14372 // reserved name, like __gnu_cxx.
14373 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14374 if (NS &&
14375 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14376 continue;
14377
14378 SuggestedNamespaces.insert(*it);
14379 }
14380 }
14381
14382 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14383 << R.getLookupName();
14384 if (SuggestedNamespaces.empty()) {
14385 SemaRef.Diag(Best->Function->getLocation(),
14386 diag::note_not_found_by_two_phase_lookup)
14387 << R.getLookupName() << 0;
14388 } else if (SuggestedNamespaces.size() == 1) {
14389 SemaRef.Diag(Best->Function->getLocation(),
14390 diag::note_not_found_by_two_phase_lookup)
14391 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14392 } else {
14393 // FIXME: It would be useful to list the associated namespaces here,
14394 // but the diagnostics infrastructure doesn't provide a way to produce
14395 // a localized representation of a list of items.
14396 SemaRef.Diag(Best->Function->getLocation(),
14397 diag::note_not_found_by_two_phase_lookup)
14398 << R.getLookupName() << 2;
14399 }
14400
14401 // Try to recover by calling this function.
14402 return true;
14403 }
14404
14405 R.clear();
14406 }
14407
14408 return false;
14409}
14410
14411/// Attempt to recover from ill-formed use of a non-dependent operator in a
14412/// template, where the non-dependent operator was declared after the template
14413/// was defined.
14414///
14415/// Returns true if a viable candidate was found and a diagnostic was issued.
14416static bool
14418 SourceLocation OpLoc,
14419 ArrayRef<Expr *> Args) {
14420 DeclarationName OpName =
14422 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14423 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14425 /*ExplicitTemplateArgs=*/nullptr, Args);
14426}
14427
14428namespace {
14429class BuildRecoveryCallExprRAII {
14430 Sema &SemaRef;
14431 Sema::SatisfactionStackResetRAII SatStack;
14432
14433public:
14434 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14435 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14436 SemaRef.IsBuildingRecoveryCallExpr = true;
14437 }
14438
14439 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14440};
14441}
14442
14443/// Attempts to recover from a call where no functions were found.
14444///
14445/// This function will do one of three things:
14446/// * Diagnose, recover, and return a recovery expression.
14447/// * Diagnose, fail to recover, and return ExprError().
14448/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14449/// expected to diagnose as appropriate.
14450static ExprResult
14453 SourceLocation LParenLoc,
14455 SourceLocation RParenLoc,
14456 bool EmptyLookup, bool AllowTypoCorrection) {
14457 // Do not try to recover if it is already building a recovery call.
14458 // This stops infinite loops for template instantiations like
14459 //
14460 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14461 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14462 if (SemaRef.IsBuildingRecoveryCallExpr)
14463 return ExprResult();
14464 BuildRecoveryCallExprRAII RCE(SemaRef);
14465
14466 CXXScopeSpec SS;
14467 SS.Adopt(ULE->getQualifierLoc());
14468 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14469
14470 TemplateArgumentListInfo TABuffer;
14471 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14472 if (ULE->hasExplicitTemplateArgs()) {
14473 ULE->copyTemplateArgumentsInto(TABuffer);
14474 ExplicitTemplateArgs = &TABuffer;
14475 }
14476
14477 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14479 CXXRecordDecl *FoundInClass = nullptr;
14480 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14482 ExplicitTemplateArgs, Args, &FoundInClass)) {
14483 // OK, diagnosed a two-phase lookup issue.
14484 } else if (EmptyLookup) {
14485 // Try to recover from an empty lookup with typo correction.
14486 R.clear();
14487 NoTypoCorrectionCCC NoTypoValidator{};
14488 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14489 ExplicitTemplateArgs != nullptr,
14490 dyn_cast<MemberExpr>(Fn));
14491 CorrectionCandidateCallback &Validator =
14492 AllowTypoCorrection
14493 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14494 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14495 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14496 Args))
14497 return ExprError();
14498 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14499 // We found a usable declaration of the name in a dependent base of some
14500 // enclosing class.
14501 // FIXME: We should also explain why the candidates found by name lookup
14502 // were not viable.
14503 if (SemaRef.DiagnoseDependentMemberLookup(R))
14504 return ExprError();
14505 } else {
14506 // We had viable candidates and couldn't recover; let the caller diagnose
14507 // this.
14508 return ExprResult();
14509 }
14510
14511 // If we get here, we should have issued a diagnostic and formed a recovery
14512 // lookup result.
14513 assert(!R.empty() && "lookup results empty despite recovery");
14514
14515 // If recovery created an ambiguity, just bail out.
14516 if (R.isAmbiguous()) {
14518 return ExprError();
14519 }
14520
14521 // Build an implicit member call if appropriate. Just drop the
14522 // casts and such from the call, we don't really care.
14523 ExprResult NewFn = ExprError();
14524 if ((*R.begin())->isCXXClassMember())
14525 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14526 ExplicitTemplateArgs, S);
14527 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14528 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14529 ExplicitTemplateArgs);
14530 else
14531 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14532
14533 if (NewFn.isInvalid())
14534 return ExprError();
14535
14536 // This shouldn't cause an infinite loop because we're giving it
14537 // an expression with viable lookup results, which should never
14538 // end up here.
14539 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14540 MultiExprArg(Args.data(), Args.size()),
14541 RParenLoc);
14542}
14543
14546 MultiExprArg Args,
14547 SourceLocation RParenLoc,
14548 OverloadCandidateSet *CandidateSet,
14549 ExprResult *Result) {
14550#ifndef NDEBUG
14551 if (ULE->requiresADL()) {
14552 // To do ADL, we must have found an unqualified name.
14553 assert(!ULE->getQualifier() && "qualified name with ADL");
14554
14555 // We don't perform ADL for implicit declarations of builtins.
14556 // Verify that this was correctly set up.
14557 FunctionDecl *F;
14558 if (ULE->decls_begin() != ULE->decls_end() &&
14559 ULE->decls_begin() + 1 == ULE->decls_end() &&
14560 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14561 F->getBuiltinID() && F->isImplicit())
14562 llvm_unreachable("performing ADL for builtin");
14563
14564 // We don't perform ADL in C.
14565 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14566 }
14567#endif
14568
14569 UnbridgedCastsSet UnbridgedCasts;
14570 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14571 *Result = ExprError();
14572 return true;
14573 }
14574
14575 // Add the functions denoted by the callee to the set of candidate
14576 // functions, including those from argument-dependent lookup.
14577 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14578
14579 if (getLangOpts().MSVCCompat &&
14580 CurContext->isDependentContext() && !isSFINAEContext() &&
14582
14584 if (CandidateSet->empty() ||
14585 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14587 // In Microsoft mode, if we are inside a template class member function
14588 // then create a type dependent CallExpr. The goal is to postpone name
14589 // lookup to instantiation time to be able to search into type dependent
14590 // base classes.
14591 CallExpr *CE =
14592 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14593 RParenLoc, CurFPFeatureOverrides());
14595 *Result = CE;
14596 return true;
14597 }
14598 }
14599
14600 if (CandidateSet->empty())
14601 return false;
14602
14603 UnbridgedCasts.restore();
14604 return false;
14605}
14606
14607// Guess at what the return type for an unresolvable overload should be.
14610 std::optional<QualType> Result;
14611 // Adjust Type after seeing a candidate.
14612 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14613 if (!Candidate.Function)
14614 return;
14615 if (Candidate.Function->isInvalidDecl())
14616 return;
14617 QualType T = Candidate.Function->getReturnType();
14618 if (T.isNull())
14619 return;
14620 if (!Result)
14621 Result = T;
14622 else if (Result != T)
14623 Result = QualType();
14624 };
14625
14626 // Look for an unambiguous type from a progressively larger subset.
14627 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14628 //
14629 // First, consider only the best candidate.
14630 if (Best && *Best != CS.end())
14631 ConsiderCandidate(**Best);
14632 // Next, consider only viable candidates.
14633 if (!Result)
14634 for (const auto &C : CS)
14635 if (C.Viable)
14636 ConsiderCandidate(C);
14637 // Finally, consider all candidates.
14638 if (!Result)
14639 for (const auto &C : CS)
14640 ConsiderCandidate(C);
14641
14642 if (!Result)
14643 return QualType();
14644 auto Value = *Result;
14645 if (Value.isNull() || Value->isUndeducedType())
14646 return QualType();
14647 return Value;
14648}
14649
14650/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14651/// the completed call expression. If overload resolution fails, emits
14652/// diagnostics and returns ExprError()
14655 SourceLocation LParenLoc,
14656 MultiExprArg Args,
14657 SourceLocation RParenLoc,
14658 Expr *ExecConfig,
14659 OverloadCandidateSet *CandidateSet,
14661 OverloadingResult OverloadResult,
14662 bool AllowTypoCorrection) {
14663 switch (OverloadResult) {
14664 case OR_Success: {
14665 FunctionDecl *FDecl = (*Best)->Function;
14666 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14667 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14668 return ExprError();
14669 ExprResult Res =
14670 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14671 if (Res.isInvalid())
14672 return ExprError();
14673 return SemaRef.BuildResolvedCallExpr(
14674 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14675 /*IsExecConfig=*/false,
14676 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14677 }
14678
14679 case OR_No_Viable_Function: {
14680 if (*Best != CandidateSet->end() &&
14681 CandidateSet->getKind() ==
14683 if (CXXMethodDecl *M =
14684 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14686 CandidateSet->NoteCandidates(
14688 Fn->getBeginLoc(),
14689 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14690 SemaRef, OCD_AmbiguousCandidates, Args);
14691 return ExprError();
14692 }
14693 }
14694
14695 // Try to recover by looking for viable functions which the user might
14696 // have meant to call.
14697 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14698 Args, RParenLoc,
14699 CandidateSet->empty(),
14700 AllowTypoCorrection);
14701 if (Recovery.isInvalid() || Recovery.isUsable())
14702 return Recovery;
14703
14704 // If the user passes in a function that we can't take the address of, we
14705 // generally end up emitting really bad error messages. Here, we attempt to
14706 // emit better ones.
14707 for (const Expr *Arg : Args) {
14708 if (!Arg->getType()->isFunctionType())
14709 continue;
14710 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14711 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14712 if (FD &&
14713 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14714 Arg->getExprLoc()))
14715 return ExprError();
14716 }
14717 }
14718
14719 CandidateSet->NoteCandidates(
14721 Fn->getBeginLoc(),
14722 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14723 << ULE->getName() << Fn->getSourceRange()),
14724 SemaRef, OCD_AllCandidates, Args);
14725 break;
14726 }
14727
14728 case OR_Ambiguous:
14729 CandidateSet->NoteCandidates(
14730 PartialDiagnosticAt(Fn->getBeginLoc(),
14731 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14732 << ULE->getName() << Fn->getSourceRange()),
14733 SemaRef, OCD_AmbiguousCandidates, Args);
14734 break;
14735
14736 case OR_Deleted: {
14737 FunctionDecl *FDecl = (*Best)->Function;
14738 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14739 Fn->getSourceRange(), ULE->getName(),
14740 *CandidateSet, FDecl, Args);
14741
14742 // We emitted an error for the unavailable/deleted function call but keep
14743 // the call in the AST.
14744 ExprResult Res =
14745 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14746 if (Res.isInvalid())
14747 return ExprError();
14748 return SemaRef.BuildResolvedCallExpr(
14749 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14750 /*IsExecConfig=*/false,
14751 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14752 }
14753 }
14754
14755 // Overload resolution failed, try to recover.
14756 SmallVector<Expr *, 8> SubExprs = {Fn};
14757 SubExprs.append(Args.begin(), Args.end());
14758 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14759 chooseRecoveryType(*CandidateSet, Best));
14760}
14761
14764 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14765 if (I->Viable &&
14766 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14767 I->Viable = false;
14768 I->FailureKind = ovl_fail_addr_not_available;
14769 }
14770 }
14771}
14772
14775 SourceLocation LParenLoc,
14776 MultiExprArg Args,
14777 SourceLocation RParenLoc,
14778 Expr *ExecConfig,
14779 bool AllowTypoCorrection,
14780 bool CalleesAddressIsTaken) {
14781
14785
14786 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14787 ExprResult result;
14788
14789 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14790 &result))
14791 return result;
14792
14793 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14794 // functions that aren't addressible are considered unviable.
14795 if (CalleesAddressIsTaken)
14796 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14797
14799 OverloadingResult OverloadResult =
14800 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14801
14802 // [C++23][over.call.func]
14803 // if overload resolution selects a non-static member function,
14804 // the call is ill-formed;
14806 Best != CandidateSet.end()) {
14807 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14808 M && M->isImplicitObjectMemberFunction()) {
14809 OverloadResult = OR_No_Viable_Function;
14810 }
14811 }
14812
14813 // Model the case with a call to a templated function whose definition
14814 // encloses the call and whose return type contains a placeholder type as if
14815 // the UnresolvedLookupExpr was type-dependent.
14816 if (OverloadResult == OR_Success) {
14817 const FunctionDecl *FDecl = Best->Function;
14818 if (LangOpts.CUDA)
14819 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14820 if (FDecl && FDecl->isTemplateInstantiation() &&
14821 FDecl->getReturnType()->isUndeducedType()) {
14822
14823 // Creating dependent CallExpr is not okay if the enclosing context itself
14824 // is not dependent. This situation notably arises if a non-dependent
14825 // member function calls the later-defined overloaded static function.
14826 //
14827 // For example, in
14828 // class A {
14829 // void c() { callee(1); }
14830 // static auto callee(auto x) { }
14831 // };
14832 //
14833 // Here callee(1) is unresolved at the call site, but is not inside a
14834 // dependent context. There will be no further attempt to resolve this
14835 // call if it is made dependent.
14836
14837 if (const auto *TP =
14838 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14839 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14840 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14841 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14842 }
14843 }
14844 }
14845
14846 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14847 ExecConfig, &CandidateSet, &Best,
14848 OverloadResult, AllowTypoCorrection);
14849}
14850
14854 const UnresolvedSetImpl &Fns,
14855 bool PerformADL) {
14857 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14858 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14859}
14860
14863 bool HadMultipleCandidates) {
14864 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14865 // the FoundDecl as it impedes TransformMemberExpr.
14866 // We go a bit further here: if there's no difference in UnderlyingDecl,
14867 // then using FoundDecl vs Method shouldn't make a difference either.
14868 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14869 FoundDecl = Method;
14870 // Convert the expression to match the conversion function's implicit object
14871 // parameter.
14872 ExprResult Exp;
14873 if (Method->isExplicitObjectMemberFunction())
14875 else
14877 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14878 if (Exp.isInvalid())
14879 return true;
14880
14881 if (Method->getParent()->isLambda() &&
14882 Method->getConversionType()->isBlockPointerType()) {
14883 // This is a lambda conversion to block pointer; check if the argument
14884 // was a LambdaExpr.
14885 Expr *SubE = E;
14886 auto *CE = dyn_cast<CastExpr>(SubE);
14887 if (CE && CE->getCastKind() == CK_NoOp)
14888 SubE = CE->getSubExpr();
14889 SubE = SubE->IgnoreParens();
14890 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14891 SubE = BE->getSubExpr();
14892 if (isa<LambdaExpr>(SubE)) {
14893 // For the conversion to block pointer on a lambda expression, we
14894 // construct a special BlockLiteral instead; this doesn't really make
14895 // a difference in ARC, but outside of ARC the resulting block literal
14896 // follows the normal lifetime rules for block literals instead of being
14897 // autoreleased.
14901 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14903
14904 // FIXME: This note should be produced by a CodeSynthesisContext.
14905 if (BlockExp.isInvalid())
14906 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14907 return BlockExp;
14908 }
14909 }
14910 CallExpr *CE;
14911 QualType ResultType = Method->getReturnType();
14913 ResultType = ResultType.getNonLValueExprType(Context);
14914 if (Method->isExplicitObjectMemberFunction()) {
14915 ExprResult FnExpr =
14916 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14917 HadMultipleCandidates, E->getBeginLoc());
14918 if (FnExpr.isInvalid())
14919 return ExprError();
14920 Expr *ObjectParam = Exp.get();
14921 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14922 ResultType, VK, Exp.get()->getEndLoc(),
14924 CE->setUsesMemberSyntax(true);
14925 } else {
14926 MemberExpr *ME =
14927 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14929 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14930 HadMultipleCandidates, DeclarationNameInfo(),
14931 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14932
14933 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14934 Exp.get()->getEndLoc(),
14936 }
14937
14938 if (CheckFunctionCall(Method, CE,
14939 Method->getType()->castAs<FunctionProtoType>()))
14940 return ExprError();
14941
14943}
14944
14947 const UnresolvedSetImpl &Fns,
14948 Expr *Input, bool PerformADL) {
14950 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14951 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14952 // TODO: provide better source location info.
14953 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14954
14955 if (checkPlaceholderForOverload(*this, Input))
14956 return ExprError();
14957
14958 Expr *Args[2] = { Input, nullptr };
14959 unsigned NumArgs = 1;
14960
14961 // For post-increment and post-decrement, add the implicit '0' as
14962 // the second argument, so that we know this is a post-increment or
14963 // post-decrement.
14964 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14965 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14966 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14967 SourceLocation());
14968 NumArgs = 2;
14969 }
14970
14971 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14972
14973 if (Input->isTypeDependent()) {
14975 // [C++26][expr.unary.op][expr.pre.incr]
14976 // The * operator yields an lvalue of type
14977 // The pre/post increment operators yied an lvalue.
14978 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14979 VK = VK_LValue;
14980
14981 if (Fns.empty())
14982 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14983 OK_Ordinary, OpLoc, false,
14985
14986 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14988 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14989 if (Fn.isInvalid())
14990 return ExprError();
14991 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14992 Context.DependentTy, VK_PRValue, OpLoc,
14994 }
14995
14996 // Build an empty overload set.
14998
14999 // Add the candidates from the given function set.
15000 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15001
15002 // Add operator candidates that are member functions.
15003 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15004
15005 // Add candidates from ADL.
15006 if (PerformADL) {
15007 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15008 /*ExplicitTemplateArgs*/nullptr,
15009 CandidateSet);
15010 }
15011
15012 // Add builtin operator candidates.
15013 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15014
15015 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15016
15017 // Perform overload resolution.
15019 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15020 case OR_Success: {
15021 // We found a built-in operator or an overloaded operator.
15022 FunctionDecl *FnDecl = Best->Function;
15023
15024 if (FnDecl) {
15025 Expr *Base = nullptr;
15026 // We matched an overloaded operator. Build a call to that
15027 // operator.
15028
15029 // Convert the arguments.
15030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15031 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15032
15033 ExprResult InputInit;
15034 if (Method->isExplicitObjectMemberFunction())
15035 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15036 else
15038 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15039 if (InputInit.isInvalid())
15040 return ExprError();
15041 Base = Input = InputInit.get();
15042 } else {
15043 // Convert the arguments.
15044 ExprResult InputInit
15046 Context,
15047 FnDecl->getParamDecl(0)),
15049 Input);
15050 if (InputInit.isInvalid())
15051 return ExprError();
15052 Input = InputInit.get();
15053 }
15054
15055 // Build the actual expression node.
15056 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15057 Base, HadMultipleCandidates,
15058 OpLoc);
15059 if (FnExpr.isInvalid())
15060 return ExprError();
15061
15062 // Determine the result type.
15063 QualType ResultTy = FnDecl->getReturnType();
15065 ResultTy = ResultTy.getNonLValueExprType(Context);
15066
15067 Args[0] = Input;
15069 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15071 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15072
15073 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15074 return ExprError();
15075
15076 if (CheckFunctionCall(FnDecl, TheCall,
15077 FnDecl->getType()->castAs<FunctionProtoType>()))
15078 return ExprError();
15079 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15080 } else {
15081 // We matched a built-in operator. Convert the arguments, then
15082 // break out so that we will build the appropriate built-in
15083 // operator node.
15085 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15088 if (InputRes.isInvalid())
15089 return ExprError();
15090 Input = InputRes.get();
15091 break;
15092 }
15093 }
15094
15096 // This is an erroneous use of an operator which can be overloaded by
15097 // a non-member function. Check for non-member operators which were
15098 // defined too late to be candidates.
15099 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15100 // FIXME: Recover by calling the found function.
15101 return ExprError();
15102
15103 // No viable function; fall through to handling this as a
15104 // built-in operator, which will produce an error message for us.
15105 break;
15106
15107 case OR_Ambiguous:
15108 CandidateSet.NoteCandidates(
15109 PartialDiagnosticAt(OpLoc,
15110 PDiag(diag::err_ovl_ambiguous_oper_unary)
15112 << Input->getType() << Input->getSourceRange()),
15113 *this, OCD_AmbiguousCandidates, ArgsArray,
15114 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15115 return ExprError();
15116
15117 case OR_Deleted: {
15118 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15119 // object whose method was called. Later in NoteCandidates size of ArgsArray
15120 // is passed further and it eventually ends up compared to number of
15121 // function candidate parameters which never includes the object parameter,
15122 // so slice ArgsArray to make sure apples are compared to apples.
15123 StringLiteral *Msg = Best->Function->getDeletedMessage();
15124 CandidateSet.NoteCandidates(
15125 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15127 << (Msg != nullptr)
15128 << (Msg ? Msg->getString() : StringRef())
15129 << Input->getSourceRange()),
15130 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15131 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15132 return ExprError();
15133 }
15134 }
15135
15136 // Either we found no viable overloaded operator or we matched a
15137 // built-in operator. In either case, fall through to trying to
15138 // build a built-in operation.
15139 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15140}
15141
15144 const UnresolvedSetImpl &Fns,
15145 ArrayRef<Expr *> Args, bool PerformADL) {
15146 SourceLocation OpLoc = CandidateSet.getLocation();
15147
15148 OverloadedOperatorKind ExtraOp =
15151 : OO_None;
15152
15153 // Add the candidates from the given function set. This also adds the
15154 // rewritten candidates using these functions if necessary.
15155 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15156
15157 // As template candidates are not deduced immediately,
15158 // persist the array in the overload set.
15159 ArrayRef<Expr *> ReversedArgs;
15160 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15161 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15162 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15163
15164 // Add operator candidates that are member functions.
15165 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15166 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15167 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15169
15170 // In C++20, also add any rewritten member candidates.
15171 if (ExtraOp) {
15172 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15173 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15174 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15176 }
15177
15178 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15179 // performed for an assignment operator (nor for operator[] nor operator->,
15180 // which don't get here).
15181 if (Op != OO_Equal && PerformADL) {
15182 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15183 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15184 /*ExplicitTemplateArgs*/ nullptr,
15185 CandidateSet);
15186 if (ExtraOp) {
15187 DeclarationName ExtraOpName =
15188 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15189 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15190 /*ExplicitTemplateArgs*/ nullptr,
15191 CandidateSet);
15192 }
15193 }
15194
15195 // Add builtin operator candidates.
15196 //
15197 // FIXME: We don't add any rewritten candidates here. This is strictly
15198 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15199 // resulting in our selecting a rewritten builtin candidate. For example:
15200 //
15201 // enum class E { e };
15202 // bool operator!=(E, E) requires false;
15203 // bool k = E::e != E::e;
15204 //
15205 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15206 // it seems unreasonable to consider rewritten builtin candidates. A core
15207 // issue has been filed proposing to removed this requirement.
15208 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15209}
15210
15213 const UnresolvedSetImpl &Fns, Expr *LHS,
15214 Expr *RHS, bool PerformADL,
15215 bool AllowRewrittenCandidates,
15216 FunctionDecl *DefaultedFn) {
15217 Expr *Args[2] = { LHS, RHS };
15218 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15219
15220 if (!getLangOpts().CPlusPlus20)
15221 AllowRewrittenCandidates = false;
15222
15224
15225 // If either side is type-dependent, create an appropriate dependent
15226 // expression.
15227 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15228 if (Fns.empty()) {
15229 // If there are no functions to store, just build a dependent
15230 // BinaryOperator or CompoundAssignment.
15233 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15234 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15235 Context.DependentTy);
15237 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15239 }
15240
15241 // FIXME: save results of ADL from here?
15242 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15243 // TODO: provide better source location info in DNLoc component.
15244 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15245 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15247 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15248 if (Fn.isInvalid())
15249 return ExprError();
15250 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15251 Context.DependentTy, VK_PRValue, OpLoc,
15253 }
15254
15255 // If this is the .* operator, which is not overloadable, just
15256 // create a built-in binary operator.
15257 if (Opc == BO_PtrMemD) {
15258 auto CheckPlaceholder = [&](Expr *&Arg) {
15260 if (Res.isUsable())
15261 Arg = Res.get();
15262 return !Res.isUsable();
15263 };
15264
15265 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15266 // expression that contains placeholders (in either the LHS or RHS).
15267 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15268 return ExprError();
15269 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15270 }
15271
15272 // Always do placeholder-like conversions on the RHS.
15273 if (checkPlaceholderForOverload(*this, Args[1]))
15274 return ExprError();
15275
15276 // Do placeholder-like conversion on the LHS; note that we should
15277 // not get here with a PseudoObject LHS.
15278 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15279 if (checkPlaceholderForOverload(*this, Args[0]))
15280 return ExprError();
15281
15282 // If this is the assignment operator, we only perform overload resolution
15283 // if the left-hand side is a class or enumeration type. This is actually
15284 // a hack. The standard requires that we do overload resolution between the
15285 // various built-in candidates, but as DR507 points out, this can lead to
15286 // problems. So we do it this way, which pretty much follows what GCC does.
15287 // Note that we go the traditional code path for compound assignment forms.
15288 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15289 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15290
15291 // Build the overload set.
15294 Op, OpLoc, AllowRewrittenCandidates));
15295 if (DefaultedFn)
15296 CandidateSet.exclude(DefaultedFn);
15297 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15298
15299 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15300
15301 // Perform overload resolution.
15303 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15304 case OR_Success: {
15305 // We found a built-in operator or an overloaded operator.
15306 FunctionDecl *FnDecl = Best->Function;
15307
15308 bool IsReversed = Best->isReversed();
15309 if (IsReversed)
15310 std::swap(Args[0], Args[1]);
15311
15312 if (FnDecl) {
15313
15314 if (FnDecl->isInvalidDecl())
15315 return ExprError();
15316
15317 Expr *Base = nullptr;
15318 // We matched an overloaded operator. Build a call to that
15319 // operator.
15320
15321 OverloadedOperatorKind ChosenOp =
15323
15324 // C++2a [over.match.oper]p9:
15325 // If a rewritten operator== candidate is selected by overload
15326 // resolution for an operator@, its return type shall be cv bool
15327 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15328 !FnDecl->getReturnType()->isBooleanType()) {
15329 bool IsExtension =
15331 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15332 : diag::err_ovl_rewrite_equalequal_not_bool)
15333 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15334 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15335 Diag(FnDecl->getLocation(), diag::note_declared_at);
15336 if (!IsExtension)
15337 return ExprError();
15338 }
15339
15340 if (AllowRewrittenCandidates && !IsReversed &&
15341 CandidateSet.getRewriteInfo().isReversible()) {
15342 // We could have reversed this operator, but didn't. Check if some
15343 // reversed form was a viable candidate, and if so, if it had a
15344 // better conversion for either parameter. If so, this call is
15345 // formally ambiguous, and allowing it is an extension.
15347 for (OverloadCandidate &Cand : CandidateSet) {
15348 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15349 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15350 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15352 *this, OpLoc, Cand.Conversions[ArgIdx],
15353 Best->Conversions[ArgIdx]) ==
15355 AmbiguousWith.push_back(Cand.Function);
15356 break;
15357 }
15358 }
15359 }
15360 }
15361
15362 if (!AmbiguousWith.empty()) {
15363 bool AmbiguousWithSelf =
15364 AmbiguousWith.size() == 1 &&
15365 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15366 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15368 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15369 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15370 if (AmbiguousWithSelf) {
15371 Diag(FnDecl->getLocation(),
15372 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15373 // Mark member== const or provide matching != to disallow reversed
15374 // args. Eg.
15375 // struct S { bool operator==(const S&); };
15376 // S()==S();
15377 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15378 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15379 !MD->isConst() &&
15380 !MD->hasCXXExplicitFunctionObjectParameter() &&
15381 Context.hasSameUnqualifiedType(
15382 MD->getFunctionObjectParameterType(),
15383 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15384 Context.hasSameUnqualifiedType(
15385 MD->getFunctionObjectParameterType(),
15386 Args[0]->getType()) &&
15387 Context.hasSameUnqualifiedType(
15388 MD->getFunctionObjectParameterType(),
15389 Args[1]->getType()))
15390 Diag(FnDecl->getLocation(),
15391 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15392 } else {
15393 Diag(FnDecl->getLocation(),
15394 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15395 for (auto *F : AmbiguousWith)
15396 Diag(F->getLocation(),
15397 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15398 }
15399 }
15400 }
15401
15402 // Check for nonnull = nullable.
15403 // This won't be caught in the arg's initialization: the parameter to
15404 // the assignment operator is not marked nonnull.
15405 if (Op == OO_Equal)
15407 Args[1]->getType(), OpLoc);
15408
15409 // Convert the arguments.
15410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15411 // Best->Access is only meaningful for class members.
15412 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15413
15414 ExprResult Arg0, Arg1;
15415 unsigned ParamIdx = 0;
15416 if (Method->isExplicitObjectMemberFunction()) {
15417 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15418 ParamIdx = 1;
15419 } else {
15421 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15422 }
15425 Context, FnDecl->getParamDecl(ParamIdx)),
15426 SourceLocation(), Args[1]);
15427 if (Arg0.isInvalid() || Arg1.isInvalid())
15428 return ExprError();
15429
15430 Base = Args[0] = Arg0.getAs<Expr>();
15431 Args[1] = RHS = Arg1.getAs<Expr>();
15432 } else {
15433 // Convert the arguments.
15436 FnDecl->getParamDecl(0)),
15437 SourceLocation(), Args[0]);
15438 if (Arg0.isInvalid())
15439 return ExprError();
15440
15441 ExprResult Arg1 =
15444 FnDecl->getParamDecl(1)),
15445 SourceLocation(), Args[1]);
15446 if (Arg1.isInvalid())
15447 return ExprError();
15448 Args[0] = LHS = Arg0.getAs<Expr>();
15449 Args[1] = RHS = Arg1.getAs<Expr>();
15450 }
15451
15452 // Build the actual expression node.
15453 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15454 Best->FoundDecl, Base,
15455 HadMultipleCandidates, OpLoc);
15456 if (FnExpr.isInvalid())
15457 return ExprError();
15458
15459 // Determine the result type.
15460 QualType ResultTy = FnDecl->getReturnType();
15462 ResultTy = ResultTy.getNonLValueExprType(Context);
15463
15464 CallExpr *TheCall;
15465 ArrayRef<const Expr *> ArgsArray(Args, 2);
15466 const Expr *ImplicitThis = nullptr;
15467
15468 // We always create a CXXOperatorCallExpr, even for explicit object
15469 // members; CodeGen should take care not to emit the this pointer.
15471 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15473 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15474
15475 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15476 Method && Method->isImplicitObjectMemberFunction()) {
15477 // Cut off the implicit 'this'.
15478 ImplicitThis = ArgsArray[0];
15479 ArgsArray = ArgsArray.slice(1);
15480 }
15481
15482 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15483 FnDecl))
15484 return ExprError();
15485
15486 if (Op == OO_Equal) {
15487 // Check for a self move.
15488 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15489 // lifetime check.
15491 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15492 Args[1]);
15493 }
15494 if (ImplicitThis) {
15495 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15496 QualType ThisTypeFromDecl = Context.getPointerType(
15497 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15498
15499 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15500 ThisTypeFromDecl);
15501 }
15502
15503 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15504 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15506
15507 ExprResult R = MaybeBindToTemporary(TheCall);
15508 if (R.isInvalid())
15509 return ExprError();
15510
15511 R = CheckForImmediateInvocation(R, FnDecl);
15512 if (R.isInvalid())
15513 return ExprError();
15514
15515 // For a rewritten candidate, we've already reversed the arguments
15516 // if needed. Perform the rest of the rewrite now.
15517 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15518 (Op == OO_Spaceship && IsReversed)) {
15519 if (Op == OO_ExclaimEqual) {
15520 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15521 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15522 } else {
15523 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15524 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15525 Expr *ZeroLiteral =
15527
15530 Ctx.Entity = FnDecl;
15532
15534 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15535 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15536 /*AllowRewrittenCandidates=*/false);
15537
15539 }
15540 if (R.isInvalid())
15541 return ExprError();
15542 } else {
15543 assert(ChosenOp == Op && "unexpected operator name");
15544 }
15545
15546 // Make a note in the AST if we did any rewriting.
15547 if (Best->RewriteKind != CRK_None)
15548 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15549
15550 return R;
15551 } else {
15552 // We matched a built-in operator. Convert the arguments, then
15553 // break out so that we will build the appropriate built-in
15554 // operator node.
15556 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15559 if (ArgsRes0.isInvalid())
15560 return ExprError();
15561 Args[0] = ArgsRes0.get();
15562
15564 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15567 if (ArgsRes1.isInvalid())
15568 return ExprError();
15569 Args[1] = ArgsRes1.get();
15570 break;
15571 }
15572 }
15573
15574 case OR_No_Viable_Function: {
15575 // C++ [over.match.oper]p9:
15576 // If the operator is the operator , [...] and there are no
15577 // viable functions, then the operator is assumed to be the
15578 // built-in operator and interpreted according to clause 5.
15579 if (Opc == BO_Comma)
15580 break;
15581
15582 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15583 // compare result using '==' and '<'.
15584 if (DefaultedFn && Opc == BO_Cmp) {
15585 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15586 Args[1], DefaultedFn);
15587 if (E.isInvalid() || E.isUsable())
15588 return E;
15589 }
15590
15591 // For class as left operand for assignment or compound assignment
15592 // operator do not fall through to handling in built-in, but report that
15593 // no overloaded assignment operator found
15595 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15596 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15597 Args, OpLoc);
15598 DeferDiagsRAII DDR(*this,
15599 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15600 if (Args[0]->getType()->isRecordType() &&
15601 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15602 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15604 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15605 if (Args[0]->getType()->isIncompleteType()) {
15606 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15607 << Args[0]->getType()
15608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15609 }
15610 } else {
15611 // This is an erroneous use of an operator which can be overloaded by
15612 // a non-member function. Check for non-member operators which were
15613 // defined too late to be candidates.
15614 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15615 // FIXME: Recover by calling the found function.
15616 return ExprError();
15617
15618 // No viable function; try to create a built-in operation, which will
15619 // produce an error. Then, show the non-viable candidates.
15620 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15621 }
15622 assert(Result.isInvalid() &&
15623 "C++ binary operator overloading is missing candidates!");
15624 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15625 return Result;
15626 }
15627
15628 case OR_Ambiguous:
15629 CandidateSet.NoteCandidates(
15630 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15632 << Args[0]->getType()
15633 << Args[1]->getType()
15634 << Args[0]->getSourceRange()
15635 << Args[1]->getSourceRange()),
15637 OpLoc);
15638 return ExprError();
15639
15640 case OR_Deleted: {
15641 if (isImplicitlyDeleted(Best->Function)) {
15642 FunctionDecl *DeletedFD = Best->Function;
15644 if (DFK.isSpecialMember()) {
15645 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15646 << Args[0]->getType() << DFK.asSpecialMember();
15647 } else {
15648 assert(DFK.isComparison());
15649 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15650 << Args[0]->getType() << DeletedFD;
15651 }
15652
15653 // The user probably meant to call this special member. Just
15654 // explain why it's deleted.
15655 NoteDeletedFunction(DeletedFD);
15656 return ExprError();
15657 }
15658
15659 StringLiteral *Msg = Best->Function->getDeletedMessage();
15660 CandidateSet.NoteCandidates(
15662 OpLoc,
15663 PDiag(diag::err_ovl_deleted_oper)
15664 << getOperatorSpelling(Best->Function->getDeclName()
15665 .getCXXOverloadedOperator())
15666 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15667 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15669 OpLoc);
15670 return ExprError();
15671 }
15672 }
15673
15674 // We matched a built-in operator; build it.
15675 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15676}
15677
15679 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15680 FunctionDecl *DefaultedFn) {
15681 const ComparisonCategoryInfo *Info =
15682 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15683 // If we're not producing a known comparison category type, we can't
15684 // synthesize a three-way comparison. Let the caller diagnose this.
15685 if (!Info)
15686 return ExprResult((Expr*)nullptr);
15687
15688 // If we ever want to perform this synthesis more generally, we will need to
15689 // apply the temporary materialization conversion to the operands.
15690 assert(LHS->isGLValue() && RHS->isGLValue() &&
15691 "cannot use prvalue expressions more than once");
15692 Expr *OrigLHS = LHS;
15693 Expr *OrigRHS = RHS;
15694
15695 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15696 // each of them multiple times below.
15697 LHS = new (Context)
15698 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15699 LHS->getObjectKind(), LHS);
15700 RHS = new (Context)
15701 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15702 RHS->getObjectKind(), RHS);
15703
15704 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15705 DefaultedFn);
15706 if (Eq.isInvalid())
15707 return ExprError();
15708
15709 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15710 true, DefaultedFn);
15711 if (Less.isInvalid())
15712 return ExprError();
15713
15715 if (Info->isPartial()) {
15716 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15717 DefaultedFn);
15718 if (Greater.isInvalid())
15719 return ExprError();
15720 }
15721
15722 // Form the list of comparisons we're going to perform.
15723 struct Comparison {
15724 ExprResult Cmp;
15726 } Comparisons[4] =
15732 };
15733
15734 int I = Info->isPartial() ? 3 : 2;
15735
15736 // Combine the comparisons with suitable conditional expressions.
15738 for (; I >= 0; --I) {
15739 // Build a reference to the comparison category constant.
15740 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15741 // FIXME: Missing a constant for a comparison category. Diagnose this?
15742 if (!VI)
15743 return ExprResult((Expr*)nullptr);
15744 ExprResult ThisResult =
15746 if (ThisResult.isInvalid())
15747 return ExprError();
15748
15749 // Build a conditional unless this is the final case.
15750 if (Result.get()) {
15751 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15752 ThisResult.get(), Result.get());
15753 if (Result.isInvalid())
15754 return ExprError();
15755 } else {
15756 Result = ThisResult;
15757 }
15758 }
15759
15760 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15761 // bind the OpaqueValueExprs before they're (repeatedly) used.
15762 Expr *SyntacticForm = BinaryOperator::Create(
15763 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15764 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15766 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15767 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15768}
15769
15771 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15772 MultiExprArg Args, SourceLocation LParenLoc) {
15773
15774 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15775 unsigned NumParams = Proto->getNumParams();
15776 unsigned NumArgsSlots =
15777 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15778 // Build the full argument list for the method call (the implicit object
15779 // parameter is placed at the beginning of the list).
15780 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15781 bool IsError = false;
15782 // Initialize the implicit object parameter.
15783 // Check the argument types.
15784 for (unsigned i = 0; i != NumParams; i++) {
15785 Expr *Arg;
15786 if (i < Args.size()) {
15787 Arg = Args[i];
15788 ExprResult InputInit =
15790 S.Context, Method->getParamDecl(i)),
15791 SourceLocation(), Arg);
15792 IsError |= InputInit.isInvalid();
15793 Arg = InputInit.getAs<Expr>();
15794 } else {
15795 ExprResult DefArg =
15796 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15797 if (DefArg.isInvalid()) {
15798 IsError = true;
15799 break;
15800 }
15801 Arg = DefArg.getAs<Expr>();
15802 }
15803
15804 MethodArgs.push_back(Arg);
15805 }
15806 return IsError;
15807}
15808
15810 SourceLocation RLoc,
15811 Expr *Base,
15812 MultiExprArg ArgExpr) {
15814 Args.push_back(Base);
15815 for (auto *e : ArgExpr) {
15816 Args.push_back(e);
15817 }
15818 DeclarationName OpName =
15819 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15820
15821 SourceRange Range = ArgExpr.empty()
15822 ? SourceRange{}
15823 : SourceRange(ArgExpr.front()->getBeginLoc(),
15824 ArgExpr.back()->getEndLoc());
15825
15826 // If either side is type-dependent, create an appropriate dependent
15827 // expression.
15829
15830 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15831 // CHECKME: no 'operator' keyword?
15832 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15833 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15835 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15836 if (Fn.isInvalid())
15837 return ExprError();
15838 // Can't add any actual overloads yet
15839
15840 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15841 Context.DependentTy, VK_PRValue, RLoc,
15843 }
15844
15845 // Handle placeholders
15846 UnbridgedCastsSet UnbridgedCasts;
15847 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15848 return ExprError();
15849 }
15850 // Build an empty overload set.
15852
15853 // Subscript can only be overloaded as a member function.
15854
15855 // Add operator candidates that are member functions.
15856 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15857
15858 // Add builtin operator candidates.
15859 if (Args.size() == 2)
15860 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15861
15862 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15863
15864 // Perform overload resolution.
15866 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15867 case OR_Success: {
15868 // We found a built-in operator or an overloaded operator.
15869 FunctionDecl *FnDecl = Best->Function;
15870
15871 if (FnDecl) {
15872 // We matched an overloaded operator. Build a call to that
15873 // operator.
15874
15875 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15876
15877 // Convert the arguments.
15879 SmallVector<Expr *, 2> MethodArgs;
15880
15881 // Initialize the object parameter.
15882 if (Method->isExplicitObjectMemberFunction()) {
15883 ExprResult Res =
15885 if (Res.isInvalid())
15886 return ExprError();
15887 Args[0] = Res.get();
15888 ArgExpr = Args;
15889 } else {
15891 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15892 if (Arg0.isInvalid())
15893 return ExprError();
15894
15895 MethodArgs.push_back(Arg0.get());
15896 }
15897
15899 *this, MethodArgs, Method, ArgExpr, LLoc);
15900 if (IsError)
15901 return ExprError();
15902
15903 // Build the actual expression node.
15904 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15905 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15907 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15908 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15909 if (FnExpr.isInvalid())
15910 return ExprError();
15911
15912 // Determine the result type
15913 QualType ResultTy = FnDecl->getReturnType();
15915 ResultTy = ResultTy.getNonLValueExprType(Context);
15916
15918 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15920
15921 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15922 return ExprError();
15923
15924 if (CheckFunctionCall(Method, TheCall,
15925 Method->getType()->castAs<FunctionProtoType>()))
15926 return ExprError();
15927
15929 FnDecl);
15930 } else {
15931 // We matched a built-in operator. Convert the arguments, then
15932 // break out so that we will build the appropriate built-in
15933 // operator node.
15935 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15938 if (ArgsRes0.isInvalid())
15939 return ExprError();
15940 Args[0] = ArgsRes0.get();
15941
15943 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15946 if (ArgsRes1.isInvalid())
15947 return ExprError();
15948 Args[1] = ArgsRes1.get();
15949
15950 break;
15951 }
15952 }
15953
15954 case OR_No_Viable_Function: {
15956 CandidateSet.empty()
15957 ? (PDiag(diag::err_ovl_no_oper)
15958 << Args[0]->getType() << /*subscript*/ 0
15959 << Args[0]->getSourceRange() << Range)
15960 : (PDiag(diag::err_ovl_no_viable_subscript)
15961 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15962 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15963 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15964 return ExprError();
15965 }
15966
15967 case OR_Ambiguous:
15968 if (Args.size() == 2) {
15969 CandidateSet.NoteCandidates(
15971 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15972 << "[]" << Args[0]->getType() << Args[1]->getType()
15973 << Args[0]->getSourceRange() << Range),
15974 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15975 } else {
15976 CandidateSet.NoteCandidates(
15978 PDiag(diag::err_ovl_ambiguous_subscript_call)
15979 << Args[0]->getType()
15980 << Args[0]->getSourceRange() << Range),
15981 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15982 }
15983 return ExprError();
15984
15985 case OR_Deleted: {
15986 StringLiteral *Msg = Best->Function->getDeletedMessage();
15987 CandidateSet.NoteCandidates(
15989 PDiag(diag::err_ovl_deleted_oper)
15990 << "[]" << (Msg != nullptr)
15991 << (Msg ? Msg->getString() : StringRef())
15992 << Args[0]->getSourceRange() << Range),
15993 *this, OCD_AllCandidates, Args, "[]", LLoc);
15994 return ExprError();
15995 }
15996 }
15997
15998 // We matched a built-in operator; build it.
15999 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16000}
16001
16003 SourceLocation LParenLoc,
16004 MultiExprArg Args,
16005 SourceLocation RParenLoc,
16006 Expr *ExecConfig, bool IsExecConfig,
16007 bool AllowRecovery) {
16008 assert(MemExprE->getType() == Context.BoundMemberTy ||
16009 MemExprE->getType() == Context.OverloadTy);
16010
16011 // Dig out the member expression. This holds both the object
16012 // argument and the member function we're referring to.
16013 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16014
16015 // Determine whether this is a call to a pointer-to-member function.
16016 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16017 assert(op->getType() == Context.BoundMemberTy);
16018 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16019
16020 QualType fnType =
16021 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16022
16023 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16024 QualType resultType = proto->getCallResultType(Context);
16026
16027 // Check that the object type isn't more qualified than the
16028 // member function we're calling.
16029 Qualifiers funcQuals = proto->getMethodQuals();
16030
16031 QualType objectType = op->getLHS()->getType();
16032 if (op->getOpcode() == BO_PtrMemI)
16033 objectType = objectType->castAs<PointerType>()->getPointeeType();
16034 Qualifiers objectQuals = objectType.getQualifiers();
16035
16036 Qualifiers difference = objectQuals - funcQuals;
16037 difference.removeObjCGCAttr();
16038 difference.removeAddressSpace();
16039 if (difference) {
16040 std::string qualsString = difference.getAsString();
16041 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16042 << fnType.getUnqualifiedType()
16043 << qualsString
16044 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16045 }
16046
16048 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16050
16051 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16052 call, nullptr))
16053 return ExprError();
16054
16055 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16056 return ExprError();
16057
16058 if (CheckOtherCall(call, proto))
16059 return ExprError();
16060
16061 return MaybeBindToTemporary(call);
16062 }
16063
16064 // We only try to build a recovery expr at this level if we can preserve
16065 // the return type, otherwise we return ExprError() and let the caller
16066 // recover.
16067 auto BuildRecoveryExpr = [&](QualType Type) {
16068 if (!AllowRecovery)
16069 return ExprError();
16070 std::vector<Expr *> SubExprs = {MemExprE};
16071 llvm::append_range(SubExprs, Args);
16072 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16073 Type);
16074 };
16075 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16076 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16077 RParenLoc, CurFPFeatureOverrides());
16078
16079 UnbridgedCastsSet UnbridgedCasts;
16080 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16081 return ExprError();
16082
16083 MemberExpr *MemExpr;
16084 CXXMethodDecl *Method = nullptr;
16085 bool HadMultipleCandidates = false;
16086 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16087 NestedNameSpecifier Qualifier = std::nullopt;
16088 if (isa<MemberExpr>(NakedMemExpr)) {
16089 MemExpr = cast<MemberExpr>(NakedMemExpr);
16091 FoundDecl = MemExpr->getFoundDecl();
16092 Qualifier = MemExpr->getQualifier();
16093 UnbridgedCasts.restore();
16094 } else {
16095 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16096 Qualifier = UnresExpr->getQualifier();
16097
16098 QualType ObjectType = UnresExpr->getBaseType();
16099 Expr::Classification ObjectClassification
16101 : UnresExpr->getBase()->Classify(Context);
16102
16103 // Add overload candidates
16104 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16106
16107 // FIXME: avoid copy.
16108 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16109 if (UnresExpr->hasExplicitTemplateArgs()) {
16110 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16111 TemplateArgs = &TemplateArgsBuffer;
16112 }
16113
16115 E = UnresExpr->decls_end(); I != E; ++I) {
16116
16117 QualType ExplicitObjectType = ObjectType;
16118
16119 NamedDecl *Func = *I;
16120 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16122 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16123
16124 bool HasExplicitParameter = false;
16125 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16126 M && M->hasCXXExplicitFunctionObjectParameter())
16127 HasExplicitParameter = true;
16128 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16129 M &&
16130 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16131 HasExplicitParameter = true;
16132
16133 if (HasExplicitParameter)
16134 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16135
16136 // Microsoft supports direct constructor calls.
16137 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16139 CandidateSet,
16140 /*SuppressUserConversions*/ false);
16141 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16142 // If explicit template arguments were provided, we can't call a
16143 // non-template member function.
16144 if (TemplateArgs)
16145 continue;
16146
16147 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16148 ObjectClassification, Args, CandidateSet,
16149 /*SuppressUserConversions=*/false);
16150 } else {
16152 I.getPair(), ActingDC, TemplateArgs,
16153 ExplicitObjectType, ObjectClassification,
16154 Args, CandidateSet,
16155 /*SuppressUserConversions=*/false);
16156 }
16157 }
16158
16159 HadMultipleCandidates = (CandidateSet.size() > 1);
16160
16161 DeclarationName DeclName = UnresExpr->getMemberName();
16162
16163 UnbridgedCasts.restore();
16164
16166 bool Succeeded = false;
16167 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16168 Best)) {
16169 case OR_Success:
16170 Method = cast<CXXMethodDecl>(Best->Function);
16171 FoundDecl = Best->FoundDecl;
16172 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16173 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16174 break;
16175 // If FoundDecl is different from Method (such as if one is a template
16176 // and the other a specialization), make sure DiagnoseUseOfDecl is
16177 // called on both.
16178 // FIXME: This would be more comprehensively addressed by modifying
16179 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16180 // being used.
16181 if (Method != FoundDecl.getDecl() &&
16183 break;
16184 Succeeded = true;
16185 break;
16186
16188 CandidateSet.NoteCandidates(
16190 UnresExpr->getMemberLoc(),
16191 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16192 << DeclName << MemExprE->getSourceRange()),
16193 *this, OCD_AllCandidates, Args);
16194 break;
16195 case OR_Ambiguous:
16196 CandidateSet.NoteCandidates(
16197 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16198 PDiag(diag::err_ovl_ambiguous_member_call)
16199 << DeclName << MemExprE->getSourceRange()),
16200 *this, OCD_AmbiguousCandidates, Args);
16201 break;
16202 case OR_Deleted:
16204 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16205 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16206 break;
16207 }
16208 // Overload resolution fails, try to recover.
16209 if (!Succeeded)
16210 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16211
16212 ExprResult Res =
16213 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16214 if (Res.isInvalid())
16215 return ExprError();
16216 MemExprE = Res.get();
16217
16218 // If overload resolution picked a static member
16219 // build a non-member call based on that function.
16220 if (Method->isStatic()) {
16221 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16222 ExecConfig, IsExecConfig);
16223 }
16224
16225 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16226 }
16227
16228 QualType ResultType = Method->getReturnType();
16230 ResultType = ResultType.getNonLValueExprType(Context);
16231
16232 assert(Method && "Member call to something that isn't a method?");
16233 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16234
16235 CallExpr *TheCall = nullptr;
16237 if (Method->isExplicitObjectMemberFunction()) {
16238 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16239 NewArgs))
16240 return ExprError();
16241
16242 // Build the actual expression node.
16243 ExprResult FnExpr =
16244 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16245 HadMultipleCandidates, MemExpr->getExprLoc());
16246 if (FnExpr.isInvalid())
16247 return ExprError();
16248
16249 TheCall =
16250 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16251 CurFPFeatureOverrides(), Proto->getNumParams());
16252 TheCall->setUsesMemberSyntax(true);
16253 } else {
16254 // Convert the object argument (for a non-static member function call).
16256 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16257 if (ObjectArg.isInvalid())
16258 return ExprError();
16259 MemExpr->setBase(ObjectArg.get());
16260 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16261 RParenLoc, CurFPFeatureOverrides(),
16262 Proto->getNumParams());
16263 }
16264
16265 // Check for a valid return type.
16266 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16267 TheCall, Method))
16268 return BuildRecoveryExpr(ResultType);
16269
16270 // Convert the rest of the arguments
16271 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16272 RParenLoc))
16273 return BuildRecoveryExpr(ResultType);
16274
16275 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16276
16277 if (CheckFunctionCall(Method, TheCall, Proto))
16278 return ExprError();
16279
16280 // In the case the method to call was not selected by the overloading
16281 // resolution process, we still need to handle the enable_if attribute. Do
16282 // that here, so it will not hide previous -- and more relevant -- errors.
16283 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16284 if (const EnableIfAttr *Attr =
16285 CheckEnableIf(Method, LParenLoc, Args, true)) {
16286 Diag(MemE->getMemberLoc(),
16287 diag::err_ovl_no_viable_member_function_in_call)
16288 << Method << Method->getSourceRange();
16289 Diag(Method->getLocation(),
16290 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16291 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16292 return ExprError();
16293 }
16294 }
16295
16297 TheCall->getDirectCallee()->isPureVirtual()) {
16298 const FunctionDecl *MD = TheCall->getDirectCallee();
16299
16300 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16302 Diag(MemExpr->getBeginLoc(),
16303 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16305 << MD->getParent();
16306
16307 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16308 if (getLangOpts().AppleKext)
16309 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16310 << MD->getParent() << MD->getDeclName();
16311 }
16312 }
16313
16314 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16315 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16316 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16317 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16318 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16319 MemExpr->getMemberLoc());
16320 }
16321
16323 TheCall->getDirectCallee());
16324}
16325
16328 SourceLocation LParenLoc,
16329 MultiExprArg Args,
16330 SourceLocation RParenLoc) {
16331 if (checkPlaceholderForOverload(*this, Obj))
16332 return ExprError();
16333 ExprResult Object = Obj;
16334
16335 UnbridgedCastsSet UnbridgedCasts;
16336 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16337 return ExprError();
16338
16339 assert(Object.get()->getType()->isRecordType() &&
16340 "Requires object type argument");
16341
16342 // C++ [over.call.object]p1:
16343 // If the primary-expression E in the function call syntax
16344 // evaluates to a class object of type "cv T", then the set of
16345 // candidate functions includes at least the function call
16346 // operators of T. The function call operators of T are obtained by
16347 // ordinary lookup of the name operator() in the context of
16348 // (E).operator().
16349 OverloadCandidateSet CandidateSet(LParenLoc,
16351 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16352
16353 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16354 diag::err_incomplete_object_call, Object.get()))
16355 return true;
16356
16357 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16358 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16361
16362 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16363 Oper != OperEnd; ++Oper) {
16364 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16365 Object.get()->Classify(Context), Args, CandidateSet,
16366 /*SuppressUserConversion=*/false);
16367 }
16368
16369 // When calling a lambda, both the call operator, and
16370 // the conversion operator to function pointer
16371 // are considered. But when constraint checking
16372 // on the call operator fails, it will also fail on the
16373 // conversion operator as the constraints are always the same.
16374 // As the user probably does not intend to perform a surrogate call,
16375 // we filter them out to produce better error diagnostics, ie to avoid
16376 // showing 2 failed overloads instead of one.
16377 bool IgnoreSurrogateFunctions = false;
16378 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16379 const OverloadCandidate &Candidate = *CandidateSet.begin();
16380 if (!Candidate.Viable &&
16382 IgnoreSurrogateFunctions = true;
16383 }
16384
16385 // C++ [over.call.object]p2:
16386 // In addition, for each (non-explicit in C++0x) conversion function
16387 // declared in T of the form
16388 //
16389 // operator conversion-type-id () cv-qualifier;
16390 //
16391 // where cv-qualifier is the same cv-qualification as, or a
16392 // greater cv-qualification than, cv, and where conversion-type-id
16393 // denotes the type "pointer to function of (P1,...,Pn) returning
16394 // R", or the type "reference to pointer to function of
16395 // (P1,...,Pn) returning R", or the type "reference to function
16396 // of (P1,...,Pn) returning R", a surrogate call function [...]
16397 // is also considered as a candidate function. Similarly,
16398 // surrogate call functions are added to the set of candidate
16399 // functions for each conversion function declared in an
16400 // accessible base class provided the function is not hidden
16401 // within T by another intervening declaration.
16402 const auto &Conversions = Record->getVisibleConversionFunctions();
16403 for (auto I = Conversions.begin(), E = Conversions.end();
16404 !IgnoreSurrogateFunctions && I != E; ++I) {
16405 NamedDecl *D = *I;
16406 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16407 if (isa<UsingShadowDecl>(D))
16408 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16409
16410 // Skip over templated conversion functions; they aren't
16411 // surrogates.
16413 continue;
16414
16416 if (!Conv->isExplicit()) {
16417 // Strip the reference type (if any) and then the pointer type (if
16418 // any) to get down to what might be a function type.
16419 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16420 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16421 ConvType = ConvPtrType->getPointeeType();
16422
16423 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16424 {
16425 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16426 Object.get(), Args, CandidateSet);
16427 }
16428 }
16429 }
16430
16431 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16432
16433 // Perform overload resolution.
16435 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16436 Best)) {
16437 case OR_Success:
16438 // Overload resolution succeeded; we'll build the appropriate call
16439 // below.
16440 break;
16441
16442 case OR_No_Viable_Function: {
16444 CandidateSet.empty()
16445 ? (PDiag(diag::err_ovl_no_oper)
16446 << Object.get()->getType() << /*call*/ 1
16447 << Object.get()->getSourceRange())
16448 : (PDiag(diag::err_ovl_no_viable_object_call)
16449 << Object.get()->getType() << Object.get()->getSourceRange());
16450 CandidateSet.NoteCandidates(
16451 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16452 OCD_AllCandidates, Args);
16453 break;
16454 }
16455 case OR_Ambiguous:
16456 if (!R.isAmbiguous())
16457 CandidateSet.NoteCandidates(
16458 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16459 PDiag(diag::err_ovl_ambiguous_object_call)
16460 << Object.get()->getType()
16461 << Object.get()->getSourceRange()),
16462 *this, OCD_AmbiguousCandidates, Args);
16463 break;
16464
16465 case OR_Deleted: {
16466 // FIXME: Is this diagnostic here really necessary? It seems that
16467 // 1. we don't have any tests for this diagnostic, and
16468 // 2. we already issue err_deleted_function_use for this later on anyway.
16469 StringLiteral *Msg = Best->Function->getDeletedMessage();
16470 CandidateSet.NoteCandidates(
16471 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16472 PDiag(diag::err_ovl_deleted_object_call)
16473 << Object.get()->getType() << (Msg != nullptr)
16474 << (Msg ? Msg->getString() : StringRef())
16475 << Object.get()->getSourceRange()),
16476 *this, OCD_AllCandidates, Args);
16477 break;
16478 }
16479 }
16480
16481 if (Best == CandidateSet.end())
16482 return true;
16483
16484 UnbridgedCasts.restore();
16485
16486 if (Best->Function == nullptr) {
16487 // Since there is no function declaration, this is one of the
16488 // surrogate candidates. Dig out the conversion function.
16489 CXXConversionDecl *Conv
16491 Best->Conversions[0].UserDefined.ConversionFunction);
16492
16493 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16494 Best->FoundDecl);
16495 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16496 return ExprError();
16497 assert(Conv == Best->FoundDecl.getDecl() &&
16498 "Found Decl & conversion-to-functionptr should be same, right?!");
16499 // We selected one of the surrogate functions that converts the
16500 // object parameter to a function pointer. Perform the conversion
16501 // on the object argument, then let BuildCallExpr finish the job.
16502
16503 // Create an implicit member expr to refer to the conversion operator.
16504 // and then call it.
16505 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16506 Conv, HadMultipleCandidates);
16507 if (Call.isInvalid())
16508 return ExprError();
16509 // Record usage of conversion in an implicit cast.
16511 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16512 nullptr, VK_PRValue, CurFPFeatureOverrides());
16513
16514 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16515 }
16516
16517 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16518
16519 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16520 // that calls this method, using Object for the implicit object
16521 // parameter and passing along the remaining arguments.
16522 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16523
16524 // An error diagnostic has already been printed when parsing the declaration.
16525 if (Method->isInvalidDecl())
16526 return ExprError();
16527
16528 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16529 unsigned NumParams = Proto->getNumParams();
16530
16531 DeclarationNameInfo OpLocInfo(
16532 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16533 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16534 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16535 Obj, HadMultipleCandidates,
16536 OpLocInfo.getLoc(),
16537 OpLocInfo.getInfo());
16538 if (NewFn.isInvalid())
16539 return true;
16540
16541 SmallVector<Expr *, 8> MethodArgs;
16542 MethodArgs.reserve(NumParams + 1);
16543
16544 bool IsError = false;
16545
16546 // Initialize the object parameter.
16548 if (Method->isExplicitObjectMemberFunction()) {
16549 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16550 } else {
16552 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16553 if (ObjRes.isInvalid())
16554 IsError = true;
16555 else
16556 Object = ObjRes;
16557 MethodArgs.push_back(Object.get());
16558 }
16559
16561 *this, MethodArgs, Method, Args, LParenLoc);
16562
16563 // If this is a variadic call, handle args passed through "...".
16564 if (Proto->isVariadic()) {
16565 // Promote the arguments (C99 6.5.2.2p7).
16566 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16568 Args[i], VariadicCallType::Method, nullptr);
16569 IsError |= Arg.isInvalid();
16570 MethodArgs.push_back(Arg.get());
16571 }
16572 }
16573
16574 if (IsError)
16575 return true;
16576
16577 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16578
16579 // Once we've built TheCall, all of the expressions are properly owned.
16580 QualType ResultTy = Method->getReturnType();
16582 ResultTy = ResultTy.getNonLValueExprType(Context);
16583
16585 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16587
16588 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16589 return true;
16590
16591 if (CheckFunctionCall(Method, TheCall, Proto))
16592 return true;
16593
16595}
16596
16598 SourceLocation OpLoc,
16599 bool *NoArrowOperatorFound) {
16600 assert(Base->getType()->isRecordType() &&
16601 "left-hand side must have class type");
16602
16604 return ExprError();
16605
16606 SourceLocation Loc = Base->getExprLoc();
16607
16608 // C++ [over.ref]p1:
16609 //
16610 // [...] An expression x->m is interpreted as (x.operator->())->m
16611 // for a class object x of type T if T::operator->() exists and if
16612 // the operator is selected as the best match function by the
16613 // overload resolution mechanism (13.3).
16614 DeclarationName OpName =
16615 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16617
16618 if (RequireCompleteType(Loc, Base->getType(),
16619 diag::err_typecheck_incomplete_tag, Base))
16620 return ExprError();
16621
16622 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16623 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16625
16626 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16627 Oper != OperEnd; ++Oper) {
16628 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16629 {}, CandidateSet,
16630 /*SuppressUserConversion=*/false);
16631 }
16632
16633 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16634
16635 // Perform overload resolution.
16637 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16638 case OR_Success:
16639 // Overload resolution succeeded; we'll build the call below.
16640 break;
16641
16642 case OR_No_Viable_Function: {
16643 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16644 if (CandidateSet.empty()) {
16645 QualType BaseType = Base->getType();
16646 if (NoArrowOperatorFound) {
16647 // Report this specific error to the caller instead of emitting a
16648 // diagnostic, as requested.
16649 *NoArrowOperatorFound = true;
16650 return ExprError();
16651 }
16652 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16653 << BaseType << Base->getSourceRange();
16654 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16655 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16656 << FixItHint::CreateReplacement(OpLoc, ".");
16657 }
16658 } else
16659 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16660 << "operator->" << Base->getSourceRange();
16661 CandidateSet.NoteCandidates(*this, Base, Cands);
16662 return ExprError();
16663 }
16664 case OR_Ambiguous:
16665 if (!R.isAmbiguous())
16666 CandidateSet.NoteCandidates(
16667 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16668 << "->" << Base->getType()
16669 << Base->getSourceRange()),
16671 return ExprError();
16672
16673 case OR_Deleted: {
16674 StringLiteral *Msg = Best->Function->getDeletedMessage();
16675 CandidateSet.NoteCandidates(
16676 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16677 << "->" << (Msg != nullptr)
16678 << (Msg ? Msg->getString() : StringRef())
16679 << Base->getSourceRange()),
16680 *this, OCD_AllCandidates, Base);
16681 return ExprError();
16682 }
16683 }
16684
16685 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16686
16687 // Convert the object parameter.
16688 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16689
16690 if (Method->isExplicitObjectMemberFunction()) {
16692 if (R.isInvalid())
16693 return ExprError();
16694 Base = R.get();
16695 } else {
16697 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16698 if (BaseResult.isInvalid())
16699 return ExprError();
16700 Base = BaseResult.get();
16701 }
16702
16703 // Build the operator call.
16704 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16705 Base, HadMultipleCandidates, OpLoc);
16706 if (FnExpr.isInvalid())
16707 return ExprError();
16708
16709 QualType ResultTy = Method->getReturnType();
16711 ResultTy = ResultTy.getNonLValueExprType(Context);
16712
16713 CallExpr *TheCall =
16714 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16715 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16716
16717 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16718 return ExprError();
16719
16720 if (CheckFunctionCall(Method, TheCall,
16721 Method->getType()->castAs<FunctionProtoType>()))
16722 return ExprError();
16723
16725}
16726
16728 DeclarationNameInfo &SuffixInfo,
16729 ArrayRef<Expr*> Args,
16730 SourceLocation LitEndLoc,
16731 TemplateArgumentListInfo *TemplateArgs) {
16732 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16733
16734 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16736 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16737 TemplateArgs);
16738
16739 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16740
16741 // Perform overload resolution. This will usually be trivial, but might need
16742 // to perform substitutions for a literal operator template.
16744 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16745 case OR_Success:
16746 case OR_Deleted:
16747 break;
16748
16750 CandidateSet.NoteCandidates(
16751 PartialDiagnosticAt(UDSuffixLoc,
16752 PDiag(diag::err_ovl_no_viable_function_in_call)
16753 << R.getLookupName()),
16754 *this, OCD_AllCandidates, Args);
16755 return ExprError();
16756
16757 case OR_Ambiguous:
16758 CandidateSet.NoteCandidates(
16759 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16760 << R.getLookupName()),
16761 *this, OCD_AmbiguousCandidates, Args);
16762 return ExprError();
16763 }
16764
16765 FunctionDecl *FD = Best->Function;
16766 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16767 nullptr, HadMultipleCandidates,
16768 SuffixInfo.getLoc(),
16769 SuffixInfo.getInfo());
16770 if (Fn.isInvalid())
16771 return true;
16772
16773 // Check the argument types. This should almost always be a no-op, except
16774 // that array-to-pointer decay is applied to string literals.
16775 Expr *ConvArgs[2];
16776 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16779 SourceLocation(), Args[ArgIdx]);
16780 if (InputInit.isInvalid())
16781 return true;
16782 ConvArgs[ArgIdx] = InputInit.get();
16783 }
16784
16785 QualType ResultTy = FD->getReturnType();
16787 ResultTy = ResultTy.getNonLValueExprType(Context);
16788
16790 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16791 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16792
16793 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16794 return ExprError();
16795
16796 if (CheckFunctionCall(FD, UDL, nullptr))
16797 return ExprError();
16798
16800}
16801
16804 SourceLocation RangeLoc,
16805 const DeclarationNameInfo &NameInfo,
16806 LookupResult &MemberLookup,
16807 OverloadCandidateSet *CandidateSet,
16808 Expr *Range, ExprResult *CallExpr) {
16809 Scope *S = nullptr;
16810
16812 if (!MemberLookup.empty()) {
16813 ExprResult MemberRef =
16814 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16815 /*IsPtr=*/false, CXXScopeSpec(),
16816 /*TemplateKWLoc=*/SourceLocation(),
16817 /*FirstQualifierInScope=*/nullptr,
16818 MemberLookup,
16819 /*TemplateArgs=*/nullptr, S);
16820 if (MemberRef.isInvalid()) {
16821 *CallExpr = ExprError();
16822 return FRS_DiagnosticIssued;
16823 }
16824 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16825 if (CallExpr->isInvalid()) {
16826 *CallExpr = ExprError();
16827 return FRS_DiagnosticIssued;
16828 }
16829 } else {
16830 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16832 NameInfo, UnresolvedSet<0>());
16833 if (FnR.isInvalid())
16834 return FRS_DiagnosticIssued;
16836
16837 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16838 CandidateSet, CallExpr);
16839 if (CandidateSet->empty() || CandidateSetError) {
16840 *CallExpr = ExprError();
16841 return FRS_NoViableFunction;
16842 }
16844 OverloadingResult OverloadResult =
16845 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16846
16847 if (OverloadResult == OR_No_Viable_Function) {
16848 *CallExpr = ExprError();
16849 return FRS_NoViableFunction;
16850 }
16851 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16852 Loc, nullptr, CandidateSet, &Best,
16853 OverloadResult,
16854 /*AllowTypoCorrection=*/false);
16855 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16856 *CallExpr = ExprError();
16857 return FRS_DiagnosticIssued;
16858 }
16859 }
16860 return FRS_Success;
16861}
16862
16864 FunctionDecl *Fn) {
16865 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16866 ExprResult SubExpr =
16867 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16868 if (SubExpr.isInvalid())
16869 return ExprError();
16870 if (SubExpr.get() == PE->getSubExpr())
16871 return PE;
16872
16873 return new (Context)
16874 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16875 }
16876
16877 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16878 ExprResult SubExpr =
16879 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16880 if (SubExpr.isInvalid())
16881 return ExprError();
16882 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16883 SubExpr.get()->getType()) &&
16884 "Implicit cast type cannot be determined from overload");
16885 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16886 if (SubExpr.get() == ICE->getSubExpr())
16887 return ICE;
16888
16889 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16890 SubExpr.get(), nullptr, ICE->getValueKind(),
16892 }
16893
16894 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16895 if (!GSE->isResultDependent()) {
16896 ExprResult SubExpr =
16897 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16898 if (SubExpr.isInvalid())
16899 return ExprError();
16900 if (SubExpr.get() == GSE->getResultExpr())
16901 return GSE;
16902
16903 // Replace the resulting type information before rebuilding the generic
16904 // selection expression.
16905 ArrayRef<Expr *> A = GSE->getAssocExprs();
16906 SmallVector<Expr *, 4> AssocExprs(A);
16907 unsigned ResultIdx = GSE->getResultIndex();
16908 AssocExprs[ResultIdx] = SubExpr.get();
16909
16910 if (GSE->isExprPredicate())
16912 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16913 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16914 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16915 ResultIdx);
16917 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16918 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16919 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16920 ResultIdx);
16921 }
16922 // Rather than fall through to the unreachable, return the original generic
16923 // selection expression.
16924 return GSE;
16925 }
16926
16927 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16928 assert(UnOp->getOpcode() == UO_AddrOf &&
16929 "Can only take the address of an overloaded function");
16930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16931 if (!Method->isImplicitObjectMemberFunction()) {
16932 // Do nothing: the address of static and
16933 // explicit object member functions is a (non-member) function pointer.
16934 } else {
16935 // Fix the subexpression, which really has to be an
16936 // UnresolvedLookupExpr holding an overloaded member function
16937 // or template.
16938 ExprResult SubExpr =
16939 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16940 if (SubExpr.isInvalid())
16941 return ExprError();
16942 if (SubExpr.get() == UnOp->getSubExpr())
16943 return UnOp;
16944
16945 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16946 SubExpr.get(), Method))
16947 return ExprError();
16948
16949 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16950 "fixed to something other than a decl ref");
16951 NestedNameSpecifier Qualifier =
16952 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
16953 assert(Qualifier &&
16954 "fixed to a member ref with no nested name qualifier");
16955
16956 // We have taken the address of a pointer to member
16957 // function. Perform the computation here so that we get the
16958 // appropriate pointer to member type.
16959 QualType MemPtrType = Context.getMemberPointerType(
16960 Fn->getType(), Qualifier,
16961 cast<CXXRecordDecl>(Method->getDeclContext()));
16962 // Under the MS ABI, lock down the inheritance model now.
16963 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16964 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16965
16966 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16967 MemPtrType, VK_PRValue, OK_Ordinary,
16968 UnOp->getOperatorLoc(), false,
16970 }
16971 }
16972 ExprResult SubExpr =
16973 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16974 if (SubExpr.isInvalid())
16975 return ExprError();
16976 if (SubExpr.get() == UnOp->getSubExpr())
16977 return UnOp;
16978
16979 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16980 SubExpr.get());
16981 }
16982
16983 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16984 if (Found.getAccess() == AS_none) {
16986 }
16987 // FIXME: avoid copy.
16988 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16989 if (ULE->hasExplicitTemplateArgs()) {
16990 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16991 TemplateArgs = &TemplateArgsBuffer;
16992 }
16993
16994 QualType Type = Fn->getType();
16995 ExprValueKind ValueKind =
16996 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16997 ? VK_LValue
16998 : VK_PRValue;
16999
17000 // FIXME: Duplicated from BuildDeclarationNameExpr.
17001 if (unsigned BID = Fn->getBuiltinID()) {
17002 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17003 Type = Context.BuiltinFnTy;
17004 ValueKind = VK_PRValue;
17005 }
17006 }
17007
17009 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17010 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17011 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17012 return DRE;
17013 }
17014
17015 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17016 // FIXME: avoid copy.
17017 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17018 if (MemExpr->hasExplicitTemplateArgs()) {
17019 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17020 TemplateArgs = &TemplateArgsBuffer;
17021 }
17022
17023 Expr *Base;
17024
17025 // If we're filling in a static method where we used to have an
17026 // implicit member access, rewrite to a simple decl ref.
17027 if (MemExpr->isImplicitAccess()) {
17028 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17030 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17031 MemExpr->getQualifierLoc(), Found.getDecl(),
17032 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17033 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17034 return DRE;
17035 } else {
17036 SourceLocation Loc = MemExpr->getMemberLoc();
17037 if (MemExpr->getQualifier())
17038 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17039 Base =
17040 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17041 }
17042 } else
17043 Base = MemExpr->getBase();
17044
17045 ExprValueKind valueKind;
17046 QualType type;
17047 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17048 valueKind = VK_LValue;
17049 type = Fn->getType();
17050 } else {
17051 valueKind = VK_PRValue;
17052 type = Context.BoundMemberTy;
17053 }
17054
17055 return BuildMemberExpr(
17056 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17057 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17058 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17059 type, valueKind, OK_Ordinary, TemplateArgs);
17060 }
17061
17062 llvm_unreachable("Invalid reference to overloaded function");
17063}
17064
17070
17071bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17073 if (!PartialOverloading || !Function)
17074 return true;
17075 if (Function->isVariadic())
17076 return false;
17077 if (const auto *Proto =
17078 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17079 if (Proto->isTemplateVariadic())
17080 return false;
17081 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17082 if (const auto *Proto =
17083 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17084 if (Proto->isTemplateVariadic())
17085 return false;
17086 return true;
17087}
17088
17090 DeclarationName Name,
17091 OverloadCandidateSet &CandidateSet,
17092 FunctionDecl *Fn, MultiExprArg Args,
17093 bool IsMember) {
17094 StringLiteral *Msg = Fn->getDeletedMessage();
17095 CandidateSet.NoteCandidates(
17096 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17097 << IsMember << Name << (Msg != nullptr)
17098 << (Msg ? Msg->getString() : StringRef())
17099 << Range),
17100 *this, OCD_AllCandidates, Args);
17101}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:109
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
__device__ __2f16 b
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:463
bool isFloat() const
Definition APValue.h:468
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:776
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType NullPtrTy
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:892
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
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 ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
CanQualType WCharTy
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType Char8Ty
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:279
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8077
Attr - This represents one attribute.
Definition Attr.h:45
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:4977
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
Pointer to a block type.
Definition TypeBase.h:3542
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3019
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3056
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2979
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2983
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:692
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition ExprCXX.cpp:624
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1977
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:286
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1513
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3041
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3259
Represents a canonical, potentially-qualified type.
bool isAtLeastAsQualifiedAs(CanQual< T > Other, const ASTContext &Ctx) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
static CanQual< Type > CreateUnsafe(QualType Other)
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isVolatileQualified() const
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:4999
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition Expr.h:1463
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
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:273
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:777
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:762
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:753
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1948
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1932
const Expr * getExpr() const
Definition DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2354
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:337
bool isLValue() const
Definition Expr.h:387
bool isPRValue() const
Definition Expr.h:390
bool isXValue() const
Definition Expr.h:388
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:395
bool isRValue() const
Definition Expr.h:391
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3334
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4203
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4042
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:412
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4187
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3756
param_iterator param_end()
Definition Decl.h:2787
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3660
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3859
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4258
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4307
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3741
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3127
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4323
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4251
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3863
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4124
bool isConsteval() const
Definition Decl.h:2482
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3704
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2862
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition Decl.cpp:3709
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3820
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5758
unsigned getNumParams() const
Definition TypeBase.h:5532
Qualifiers getMethodQuals() const
Definition TypeBase.h:5680
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5694
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:4561
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4632
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4489
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
CallingConv getCallConv() const
Definition TypeBase.h:4805
QualType getReturnType() const
Definition TypeBase.h:4790
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4818
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:4599
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:615
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:666
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:763
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:670
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:820
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:674
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:805
bool hasInitializerListContainerType() const
Definition Overload.h:802
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:727
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:809
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:678
QualType getInitializerListContainerType() const
Definition Overload.h:812
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5348
unsigned getNumInits() const
Definition Expr.h:5263
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2491
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2509
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3617
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Represents the results of name lookup.
Definition Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition Lookup.h:643
const UnresolvedSetImpl & asUnresolvedSet() const
Definition Lookup.h:354
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3487
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3409
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3395
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3375
void setBase(Expr *E)
Definition Expr.h:3374
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1790
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3493
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3385
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3685
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5449
QualType getPointeeType() const
Definition TypeBase.h:3671
Describes a module or submodule.
Definition Module.h:144
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7840
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7896
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:7985
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7954
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7908
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7948
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:7960
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:3128
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3280
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3189
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3244
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3241
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3219
decls_iterator decls_begin() const
Definition ExprCXX.h:3221
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3232
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3254
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3250
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3342
decls_iterator decls_end() const
Definition ExprCXX.h:3224
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3238
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:273
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3052
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:5071
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8356
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8367
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3555
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:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8318
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:8463
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
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:8432
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8399
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8324
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:8443
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8310
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8218
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8225
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4659
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:860
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
bool hasOnlyConst() const
Definition TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasRestrict() const
Definition TypeBase.h:477
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeUnaligned()
Definition TypeBase.h:515
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3635
Represents a struct/union/class.
Definition Decl.h:4312
field_range fields() const
Definition Decl.h:4515
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
Definition SemaARM.cpp:1487
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1531
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
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:10283
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:6338
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6367
RAII class to control scope of DeferDiags.
Definition Sema.h:10020
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:12418
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12452
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.
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:10036
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:9309
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9336
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9321
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9317
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:411
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:168
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:1441
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:10366
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10369
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10375
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10373
@ AR_dependent
Definition Sema.h:1656
@ AR_accessible
Definition Sema.h:1654
@ AR_inaccessible
Definition Sema.h:1655
@ AR_delayed
Definition Sema.h:1657
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:2045
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:1651
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:1486
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:754
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:10754
@ FRS_DiagnosticIssued
Definition Sema.h:10756
@ FRS_NoViableFunction
Definition Sema.h:10755
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9302
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:10087
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3572
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:12118
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:1451
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9301
MemberPointerConversionDirection
Definition Sema.h:10207
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:10394
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
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:639
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:15415
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:6957
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:1414
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8152
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:13891
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 ?
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:7452
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 isSFINAEContext() const
Definition Sema.h:13626
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:224
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:15370
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:6723
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6692
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:10199
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:515
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.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6400
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:1421
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:8631
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:362
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
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:676
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:730
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:715
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3538
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isObjCBuiltinType() const
Definition TypeBase.h:8735
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:8622
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:8880
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:8547
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:8618
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9031
bool isArrayType() const
Definition TypeBase.h:8614
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:8939
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2337
bool isPointerType() const
Definition TypeBase.h:8515
bool isArrayParameterType() const
Definition TypeBase.h:8630
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2573
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8705
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:8989
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:8662
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8692
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:8543
bool isBitIntType() const
Definition TypeBase.h:8780
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:8650
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8927
bool isHalfType() const
Definition TypeBase.h:8875
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8853
bool isQueueT() const
Definition TypeBase.h:8761
bool isMemberPointerType() const
Definition TypeBase.h:8596
bool isObjCIdType() const
Definition TypeBase.h:8717
bool isMatrixType() const
Definition TypeBase.h:8672
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
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:8753
bool isBFloat16Type() const
Definition TypeBase.h:8892
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool isVectorType() const
Definition TypeBase.h:8654
bool isObjCClassType() const
Definition TypeBase.h:8723
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2594
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:8828
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:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSamplerT() const
Definition TypeBase.h:8749
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
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:5034
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:3390
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3459
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:4126
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4234
QualType getBaseType() const
Definition ExprCXX.h:4208
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4218
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4199
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4244
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4238
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:640
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:966
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:224
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:809
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:60
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind, bool PartialOverloading=false)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition Overload.h:852
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:880
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:889
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:872
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:876
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition Overload.h:917
@ ovl_fail_too_few_arguments
Definition Overload.h:854
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:896
@ ovl_fail_too_many_arguments
Definition Overload.h:853
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:904
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:913
@ ovl_fail_bad_conversion
Definition Overload.h:855
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:885
@ ovl_fail_bad_deduction
Definition Overload.h:856
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:900
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:909
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:893
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:861
@ Comparison
A comparison.
Definition Sema.h:665
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:215
@ ICR_Conversion
Conversion.
Definition Overload.h:229
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:251
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:257
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:220
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:244
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:232
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:238
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:235
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:254
@ ICR_Promotion
Promotion.
Definition Overload.h:223
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:217
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:248
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:226
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:922
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:205
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:208
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:710
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:731
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:689
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:727
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:585
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:214
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:425
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:268
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:280
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:308
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:304
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:417
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:412
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:388
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:374
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:410
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:407
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:377
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:371
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:391
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:380
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:394
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:383
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:404
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:398
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:401
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1512
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
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:5867
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:446
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h:515
ConversionSet::const_iterator const_iterator
Definition Overload.h:551
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:516
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:542
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:600
QualType getFromType() const
Definition Overload.h:599
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
DeferredTemplateOverloadCandidate * Next
Definition Overload.h:1095
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
Extra information about a function prototype.
Definition TypeBase.h:5339
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5344
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1188
bool allowsReversed(OverloadedOperatorKind Op) const
Determine whether reversing parameter order is allowed for operator Op.
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD) const
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool isAcceptableCandidate(const FunctionDecl *FD) const
Definition Overload.h:1210
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1237
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
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:10486
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10493
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13060
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13148
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13186
Abstract class used to diagnose incomplete types.
Definition Sema.h:8233
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.