clang 23.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
127 const StandardConversionSequence& SCS1,
128 const StandardConversionSequence& SCS2);
129
130/// GetConversionRank - Retrieve the implicit conversion rank
131/// corresponding to the given implicit conversion kind.
133 static const ImplicitConversionRank Rank[] = {
160 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
161 // it was omitted by the patch that added
162 // ICK_Zero_Event_Conversion
163 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Queue_Conversion
174 };
175 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
176 return Rank[(int)Kind];
177}
178
197
198/// GetImplicitConversionName - Return the name of this kind of
199/// implicit conversion.
201 static const char *const Name[] = {
202 "No conversion",
203 "Lvalue-to-rvalue",
204 "Array-to-pointer",
205 "Function-to-pointer",
206 "Function pointer conversion",
207 "Qualification",
208 "Integral promotion",
209 "Floating point promotion",
210 "Complex promotion",
211 "Integral conversion",
212 "Floating conversion",
213 "Complex conversion",
214 "Floating-integral conversion",
215 "Pointer conversion",
216 "Pointer-to-member conversion",
217 "Boolean conversion",
218 "Compatible-types conversion",
219 "Derived-to-base conversion",
220 "Vector conversion",
221 "SVE Vector conversion",
222 "RVV Vector conversion",
223 "Vector splat",
224 "Complex-real conversion",
225 "Block Pointer conversion",
226 "Transparent Union Conversion",
227 "Writeback conversion",
228 "OpenCL Zero Event Conversion",
229 "OpenCL Zero Queue Conversion",
230 "C specific type conversion",
231 "Incompatible pointer conversion",
232 "Fixed point conversion",
233 "HLSL vector truncation",
234 "HLSL matrix truncation",
235 "Non-decaying array conversion",
236 "HLSL vector splat",
237 "HLSL matrix splat",
238 };
239 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
240 return Name[Kind];
241}
242
243/// StandardConversionSequence - Set the standard conversion
244/// sequence to the identity conversion.
262
263/// getRank - Retrieve the rank of this standard conversion sequence
264/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
265/// implicit conversions.
278
279/// isPointerConversionToBool - Determines whether this conversion is
280/// a conversion of a pointer or pointer-to-member to bool. This is
281/// used as part of the ranking of standard conversion sequences
282/// (C++ 13.3.3.2p4).
284 // Note that FromType has not necessarily been transformed by the
285 // array-to-pointer or function-to-pointer implicit conversions, so
286 // check for their presence as well as checking whether FromType is
287 // a pointer.
288 if (getToType(1)->isBooleanType() &&
289 (getFromType()->isPointerType() ||
290 getFromType()->isMemberPointerType() ||
291 getFromType()->isObjCObjectPointerType() ||
292 getFromType()->isBlockPointerType() ||
294 return true;
295
296 return false;
297}
298
299/// isPointerConversionToVoidPointer - Determines whether this
300/// conversion is a conversion of a pointer to a void pointer. This is
301/// used as part of the ranking of standard conversion sequences (C++
302/// 13.3.3.2p4).
303bool
306 QualType FromType = getFromType();
307 QualType ToType = getToType(1);
308
309 // Note that FromType has not necessarily been transformed by the
310 // array-to-pointer implicit conversion, so check for its presence
311 // and redo the conversion to get a pointer.
313 FromType = Context.getArrayDecayedType(FromType);
314
315 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
316 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
317 return ToPtrType->getPointeeType()->isVoidType();
318
319 return false;
320}
321
322/// Skip any implicit casts which could be either part of a narrowing conversion
323/// or after one in an implicit conversion.
325 const Expr *Converted) {
326 // We can have cleanups wrapping the converted expression; these need to be
327 // preserved so that destructors run if necessary.
328 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
329 Expr *Inner =
330 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
331 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
332 EWC->getObjects());
333 }
334
335 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
336 switch (ICE->getCastKind()) {
337 case CK_NoOp:
338 case CK_IntegralCast:
339 case CK_IntegralToBoolean:
340 case CK_IntegralToFloating:
341 case CK_BooleanToSignedIntegral:
342 case CK_FloatingToIntegral:
343 case CK_FloatingToBoolean:
344 case CK_FloatingCast:
345 Converted = ICE->getSubExpr();
346 continue;
347
348 default:
349 return Converted;
350 }
351 }
352
353 return Converted;
354}
355
356/// Check if this standard conversion sequence represents a narrowing
357/// conversion, according to C++11 [dcl.init.list]p7.
358///
359/// \param Ctx The AST context.
360/// \param Converted The result of applying this standard conversion sequence.
361/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
362/// value of the expression prior to the narrowing conversion.
363/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
364/// type of the expression prior to the narrowing conversion.
365/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
366/// from floating point types to integral types should be ignored.
368 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
369 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
370 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
371 "narrowing check outside C++");
372
373 // C++11 [dcl.init.list]p7:
374 // A narrowing conversion is an implicit conversion ...
375 QualType FromType = getToType(0);
376 QualType ToType = getToType(1);
377
378 // A conversion to an enumeration type is narrowing if the conversion to
379 // the underlying type is narrowing. This only arises for expressions of
380 // the form 'Enum{init}'.
381 if (const auto *ED = ToType->getAsEnumDecl())
382 ToType = ED->getIntegerType();
383
384 switch (Second) {
385 // 'bool' is an integral type; dispatch to the right place to handle it.
387 if (FromType->isRealFloatingType())
388 goto FloatingIntegralConversion;
390 goto IntegralConversion;
391 // -- from a pointer type or pointer-to-member type to bool, or
392 return NK_Type_Narrowing;
393
394 // -- from a floating-point type to an integer type, or
395 //
396 // -- from an integer type or unscoped enumeration type to a floating-point
397 // type, except where the source is a constant expression and the actual
398 // value after conversion will fit into the target type and will produce
399 // the original value when converted back to the original type, or
401 FloatingIntegralConversion:
402 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
403 return NK_Type_Narrowing;
404 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
405 ToType->isRealFloatingType()) {
406 if (IgnoreFloatToIntegralConversion)
407 return NK_Not_Narrowing;
408 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
409 assert(Initializer && "Unknown conversion expression");
410
411 // If it's value-dependent, we can't tell whether it's narrowing.
412 if (Initializer->isValueDependent())
414
415 if (std::optional<llvm::APSInt> IntConstantValue =
416 Initializer->getIntegerConstantExpr(Ctx)) {
417 // Convert the integer to the floating type.
418 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
419 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
420 llvm::APFloat::rmNearestTiesToEven);
421 // And back.
422 llvm::APSInt ConvertedValue = *IntConstantValue;
423 bool ignored;
424 llvm::APFloat::opStatus Status = Result.convertToInteger(
425 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
426 // If the converted-back integer has unspecified value, or if the
427 // resulting value is different, this was a narrowing conversion.
428 if (Status == llvm::APFloat::opInvalidOp ||
429 *IntConstantValue != ConvertedValue) {
430 ConstantValue = APValue(*IntConstantValue);
431 ConstantType = Initializer->getType();
433 }
434 } else {
435 // Variables are always narrowings.
437 }
438 }
439 return NK_Not_Narrowing;
440
441 // -- from long double to double or float, or from double to float, except
442 // where the source is a constant expression and the actual value after
443 // conversion is within the range of values that can be represented (even
444 // if it cannot be represented exactly), or
446 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
447 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
448 // FromType is larger than ToType.
449 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
450
451 // If it's value-dependent, we can't tell whether it's narrowing.
452 if (Initializer->isValueDependent())
454
456 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
457 ((Ctx.getLangOpts().CPlusPlus &&
458 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
459 // Constant!
460 if (Ctx.getLangOpts().C23)
461 ConstantValue = R.Val;
462 assert(ConstantValue.isFloat());
463 llvm::APFloat FloatVal = ConstantValue.getFloat();
464 // Convert the source value into the target type.
465 bool ignored;
466 llvm::APFloat Converted = FloatVal;
467 llvm::APFloat::opStatus ConvertStatus =
468 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
469 llvm::APFloat::rmNearestTiesToEven, &ignored);
470 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
471 llvm::APFloat::rmNearestTiesToEven, &ignored);
472 if (Ctx.getLangOpts().C23) {
473 if (FloatVal.isNaN() && Converted.isNaN() &&
474 !FloatVal.isSignaling() && !Converted.isSignaling()) {
475 // Quiet NaNs are considered the same value, regardless of
476 // payloads.
477 return NK_Not_Narrowing;
478 }
479 // For normal values, check exact equality.
480 if (!Converted.bitwiseIsEqual(FloatVal)) {
481 ConstantType = Initializer->getType();
483 }
484 } else {
485 // If there was no overflow, the source value is within the range of
486 // values that can be represented.
487 if (ConvertStatus & llvm::APFloat::opOverflow) {
488 ConstantType = Initializer->getType();
490 }
491 }
492 } else {
494 }
495 }
496 return NK_Not_Narrowing;
497
498 // -- from an integer type or unscoped enumeration type to an integer type
499 // that cannot represent all the values of the original type, except where
500 // (CWG2627) -- the source is a bit-field whose width w is less than that
501 // of its type (or, for an enumeration type, its underlying type) and the
502 // target type can represent all the values of a hypothetical extended
503 // integer type with width w and with the same signedness as the original
504 // type or
505 // -- the source is a constant expression and the actual value after
506 // conversion will fit into the target type and will produce the original
507 // value when converted back to the original type.
509 IntegralConversion: {
510 assert(FromType->isIntegralOrUnscopedEnumerationType());
511 assert(ToType->isIntegralOrUnscopedEnumerationType());
512 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
513 unsigned FromWidth = Ctx.getIntWidth(FromType);
514 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
515 const unsigned ToWidth = Ctx.getIntWidth(ToType);
516
517 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
518 bool ToSigned, unsigned ToWidth) {
519 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
520 !(FromSigned && !ToSigned);
521 };
522
523 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
524 return NK_Not_Narrowing;
525
526 // Not all values of FromType can be represented in ToType.
527 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
528
529 bool DependentBitField = false;
530 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
531 if (BitField->getBitWidth()->isValueDependent())
532 DependentBitField = true;
533 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
534 BitFieldWidth < FromWidth) {
535 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
536 return NK_Not_Narrowing;
537
538 // The initializer will be truncated to the bit-field width
539 FromWidth = BitFieldWidth;
540 }
541 }
542
543 // If it's value-dependent, we can't tell whether it's narrowing.
544 if (Initializer->isValueDependent())
546
547 std::optional<llvm::APSInt> OptInitializerValue =
548 Initializer->getIntegerConstantExpr(Ctx);
549 if (!OptInitializerValue) {
550 // If the bit-field width was dependent, it might end up being small
551 // enough to fit in the target type (unless the target type is unsigned
552 // and the source type is signed, in which case it will never fit)
553 if (DependentBitField && !(FromSigned && !ToSigned))
555
556 // Otherwise, such a conversion is always narrowing
558 }
559 llvm::APSInt &InitializerValue = *OptInitializerValue;
560 bool Narrowing = false;
561 if (FromWidth < ToWidth) {
562 // Negative -> unsigned is narrowing. Otherwise, more bits is never
563 // narrowing.
564 if (InitializerValue.isSigned() && InitializerValue.isNegative())
565 Narrowing = true;
566 } else {
567 // Add a bit to the InitializerValue so we don't have to worry about
568 // signed vs. unsigned comparisons.
569 InitializerValue =
570 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
571 // Convert the initializer to and from the target width and signed-ness.
572 llvm::APSInt ConvertedValue = InitializerValue;
573 ConvertedValue = ConvertedValue.trunc(ToWidth);
574 ConvertedValue.setIsSigned(ToSigned);
575 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
576 ConvertedValue.setIsSigned(InitializerValue.isSigned());
577 // If the result is different, this was a narrowing conversion.
578 if (ConvertedValue != InitializerValue)
579 Narrowing = true;
580 }
581 if (Narrowing) {
582 ConstantType = Initializer->getType();
583 ConstantValue = APValue(InitializerValue);
585 }
586
587 return NK_Not_Narrowing;
588 }
589 case ICK_Complex_Real:
590 if (FromType->isComplexType() && !ToType->isComplexType())
591 return NK_Type_Narrowing;
592 return NK_Not_Narrowing;
593
595 if (Ctx.getLangOpts().C23) {
596 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
598 if (Initializer->EvaluateAsRValue(R, Ctx)) {
599 ConstantValue = R.Val;
600 assert(ConstantValue.isFloat());
601 llvm::APFloat FloatVal = ConstantValue.getFloat();
602 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
603 // value, the unqualified versions of the type of the initializer and
604 // the corresponding real type of the object declared shall be
605 // compatible.
606 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
607 ConstantType = Initializer->getType();
609 }
610 }
611 }
612 return NK_Not_Narrowing;
613 default:
614 // Other kinds of conversions are not narrowings.
615 return NK_Not_Narrowing;
616 }
617}
618
619/// dump - Print this standard conversion sequence to standard
620/// error. Useful for debugging overloading issues.
621LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
622 raw_ostream &OS = llvm::errs();
623 bool PrintedSomething = false;
624 if (First != ICK_Identity) {
626 PrintedSomething = true;
627 }
628
629 if (Second != ICK_Identity) {
630 if (PrintedSomething) {
631 OS << " -> ";
632 }
634
635 if (CopyConstructor) {
636 OS << " (by copy constructor)";
637 } else if (DirectBinding) {
638 OS << " (direct reference binding)";
639 } else if (ReferenceBinding) {
640 OS << " (reference binding)";
641 }
642 PrintedSomething = true;
643 }
644
645 if (Third != ICK_Identity) {
646 if (PrintedSomething) {
647 OS << " -> ";
648 }
650 PrintedSomething = true;
651 }
652
653 if (!PrintedSomething) {
654 OS << "No conversions required";
655 }
656}
657
658/// dump - Print this user-defined conversion sequence to standard
659/// error. Useful for debugging overloading issues.
661 raw_ostream &OS = llvm::errs();
662 if (Before.First || Before.Second || Before.Third) {
663 Before.dump();
664 OS << " -> ";
665 }
667 OS << '\'' << *ConversionFunction << '\'';
668 else
669 OS << "aggregate initialization";
670 if (After.First || After.Second || After.Third) {
671 OS << " -> ";
672 After.dump();
673 }
674}
675
676/// dump - Print this implicit conversion sequence to standard
677/// error. Useful for debugging overloading issues.
679 raw_ostream &OS = llvm::errs();
681 OS << "Worst list element conversion: ";
682 switch (ConversionKind) {
684 OS << "Standard conversion: ";
685 Standard.dump();
686 break;
688 OS << "User-defined conversion: ";
689 UserDefined.dump();
690 break;
692 OS << "Ellipsis conversion";
693 break;
695 OS << "Ambiguous conversion";
696 break;
697 case BadConversion:
698 OS << "Bad conversion";
699 break;
700 }
701
702 OS << "\n";
703}
704
708
710 conversions().~ConversionSet();
711}
712
713void
719
720namespace {
721 // Structure used by DeductionFailureInfo to store
722 // template argument information.
723 struct DFIArguments {
724 TemplateArgument FirstArg;
725 TemplateArgument SecondArg;
726 };
727 // Structure used by DeductionFailureInfo to store
728 // template parameter and template argument information.
729 struct DFIParamWithArguments : DFIArguments {
730 TemplateParameter Param;
731 };
732 // Structure used by DeductionFailureInfo to store template argument
733 // information and the index of the problematic call argument.
734 struct DFIDeducedMismatchArgs : DFIArguments {
735 TemplateArgumentList *TemplateArgs;
736 unsigned CallArgIndex;
737 };
738 // Structure used by DeductionFailureInfo to store information about
739 // unsatisfied constraints.
740 struct CNSInfo {
741 TemplateArgumentList *TemplateArgs;
742 ConstraintSatisfaction Satisfaction;
743 };
744}
745
746/// Convert from Sema's representation of template deduction information
747/// to the form used in overload-candidate information.
751 TemplateDeductionInfo &Info) {
753 Result.Result = static_cast<unsigned>(TDK);
754 Result.HasDiagnostic = false;
755 switch (TDK) {
762 Result.Data = nullptr;
763 break;
764
767 Result.Data = Info.Param.getOpaqueValue();
768 break;
769
772 // FIXME: Should allocate from normal heap so that we can free this later.
773 auto *Saved = new (Context) DFIDeducedMismatchArgs;
774 Saved->FirstArg = Info.FirstArg;
775 Saved->SecondArg = Info.SecondArg;
776 Saved->TemplateArgs = Info.takeSugared();
777 Saved->CallArgIndex = Info.CallArgIndex;
778 Result.Data = Saved;
779 break;
780 }
781
783 // FIXME: Should allocate from normal heap so that we can free this later.
784 DFIArguments *Saved = new (Context) DFIArguments;
785 Saved->FirstArg = Info.FirstArg;
786 Saved->SecondArg = Info.SecondArg;
787 Result.Data = Saved;
788 break;
789 }
790
792 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
795 // FIXME: Should allocate from normal heap so that we can free this later.
796 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
797 Saved->Param = Info.Param;
798 Saved->FirstArg = Info.FirstArg;
799 Saved->SecondArg = Info.SecondArg;
800 Result.Data = Saved;
801 break;
802 }
803
805 Result.Data = Info.takeSugared();
806 if (Info.hasSFINAEDiagnostic()) {
810 Result.HasDiagnostic = true;
811 }
812 break;
813
815 CNSInfo *Saved = new (Context) CNSInfo;
816 Saved->TemplateArgs = Info.takeSugared();
817 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
818 Result.Data = Saved;
819 break;
820 }
821
825 llvm_unreachable("not a deduction failure");
826 }
827
828 return Result;
829}
830
832 switch (static_cast<TemplateDeductionResult>(Result)) {
842 break;
843
850 // FIXME: Destroy the data?
851 Data = nullptr;
852 break;
853
855 // FIXME: Destroy the template argument list?
856 Data = nullptr;
858 Diag->~PartialDiagnosticAt();
859 HasDiagnostic = false;
860 }
861 break;
862
864 // FIXME: Destroy the template argument list?
865 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
866 Data = nullptr;
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
873 // Unhandled
876 break;
877 }
878}
879
881 if (HasDiagnostic)
882 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
883 return nullptr;
884}
885
919
955
987
1019
1021 switch (static_cast<TemplateDeductionResult>(Result)) {
1024 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1025
1026 default:
1027 return std::nullopt;
1028 }
1029}
1030
1032 const FunctionDecl *Y) {
1033 if (!X || !Y)
1034 return false;
1035 if (X->getNumParams() != Y->getNumParams())
1036 return false;
1037 // FIXME: when do rewritten comparison operators
1038 // with explicit object parameters correspond?
1039 // https://cplusplus.github.io/CWG/issues/2797.html
1040 for (unsigned I = 0; I < X->getNumParams(); ++I)
1041 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1042 Y->getParamDecl(I)->getType()))
1043 return false;
1044 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1045 auto *FTY = Y->getDescribedFunctionTemplate();
1046 if (!FTY)
1047 return false;
1048 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1049 FTY->getTemplateParameters()))
1050 return false;
1051 }
1052 return true;
1053}
1054
1056 Expr *FirstOperand, FunctionDecl *EqFD) {
1057 assert(EqFD->getOverloadedOperator() ==
1058 OverloadedOperatorKind::OO_EqualEqual);
1059 // C++2a [over.match.oper]p4:
1060 // A non-template function or function template F named operator== is a
1061 // rewrite target with first operand o unless a search for the name operator!=
1062 // in the scope S from the instantiation context of the operator expression
1063 // finds a function or function template that would correspond
1064 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1065 // scope of the class type of o if F is a class member, and the namespace
1066 // scope of which F is a member otherwise. A function template specialization
1067 // named operator== is a rewrite target if its function template is a rewrite
1068 // target.
1070 OverloadedOperatorKind::OO_ExclaimEqual);
1071 if (isa<CXXMethodDecl>(EqFD)) {
1072 // If F is a class member, search scope is class type of first operand.
1073 QualType RHS = FirstOperand->getType();
1074 auto *RHSRec = RHS->getAsCXXRecordDecl();
1075 if (!RHSRec)
1076 return true;
1077 LookupResult Members(S, NotEqOp, OpLoc,
1079 S.LookupQualifiedName(Members, RHSRec);
1080 Members.suppressAccessDiagnostics();
1081 for (NamedDecl *Op : Members)
1082 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1083 return false;
1084 return true;
1085 }
1086 // Otherwise the search scope is the namespace scope of which F is a member.
1087 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1088 auto *NotEqFD = Op->getAsFunction();
1089 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1090 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1091 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1093 cast<Decl>(Op->getLexicalDeclContext())))
1094 return false;
1095 }
1096 return true;
1097}
1098
1100 OverloadedOperatorKind Op) const {
1102 return false;
1103 return Op == OO_EqualEqual || Op == OO_Spaceship;
1104}
1105
1107 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1108 auto Op = FD->getOverloadedOperator();
1109 if (!allowsReversed(Op))
1110 return false;
1111 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1112 assert(OriginalArgs.size() == 2);
1114 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1115 return false;
1116 }
1117 // Don't bother adding a reversed candidate that can never be a better
1118 // match than the non-reversed version.
1119 return FD->getNumNonObjectParams() != 2 ||
1121 FD->getParamDecl(1)->getType()) ||
1122 FD->hasAttr<EnableIfAttr>();
1123}
1124
1125void OverloadCandidateSet::destroyCandidates() {
1126 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1127 for (auto &C : i->Conversions)
1128 C.~ImplicitConversionSequence();
1129 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1130 i->DeductionFailure.Destroy();
1131 }
1132}
1133
1135 destroyCandidates();
1136 SlabAllocator.Reset();
1137 NumInlineBytesUsed = 0;
1138 Candidates.clear();
1139 Functions.clear();
1140 Kind = CSK;
1141 FirstDeferredCandidate = nullptr;
1142 DeferredCandidatesCount = 0;
1143 HasDeferredTemplateConstructors = false;
1144 ResolutionByPerfectCandidateIsDisabled = false;
1145}
1146
1147namespace {
1148 class UnbridgedCastsSet {
1149 struct Entry {
1150 Expr **Addr;
1151 Expr *Saved;
1152 };
1153 SmallVector<Entry, 2> Entries;
1154
1155 public:
1156 void save(Sema &S, Expr *&E) {
1157 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1158 Entry entry = { &E, E };
1159 Entries.push_back(entry);
1160 E = S.ObjC().stripARCUnbridgedCast(E);
1161 }
1162
1163 void restore() {
1164 for (SmallVectorImpl<Entry>::iterator
1165 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1166 *i->Addr = i->Saved;
1167 }
1168 };
1169}
1170
1171/// checkPlaceholderForOverload - Do any interesting placeholder-like
1172/// preprocessing on the given expression.
1173///
1174/// \param unbridgedCasts a collection to which to add unbridged casts;
1175/// without this, they will be immediately diagnosed as errors
1176///
1177/// Return true on unrecoverable error.
1178static bool
1180 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1181 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1182 // We can't handle overloaded expressions here because overload
1183 // resolution might reasonably tweak them.
1184 if (placeholder->getKind() == BuiltinType::Overload) return false;
1185
1186 // If the context potentially accepts unbridged ARC casts, strip
1187 // the unbridged cast and add it to the collection for later restoration.
1188 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1189 unbridgedCasts) {
1190 unbridgedCasts->save(S, E);
1191 return false;
1192 }
1193
1194 // Go ahead and check everything else.
1195 ExprResult result = S.CheckPlaceholderExpr(E);
1196 if (result.isInvalid())
1197 return true;
1198
1199 E = result.get();
1200 return false;
1201 }
1202
1203 // Nothing to do.
1204 return false;
1205}
1206
1207/// checkArgPlaceholdersForOverload - Check a set of call operands for
1208/// placeholders.
1210 UnbridgedCastsSet &unbridged) {
1211 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1212 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1213 return true;
1214
1215 return false;
1216}
1217
1219 const LookupResult &Old, NamedDecl *&Match,
1220 bool NewIsUsingDecl) {
1221 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1222 I != E; ++I) {
1223 NamedDecl *OldD = *I;
1224
1225 bool OldIsUsingDecl = false;
1226 if (isa<UsingShadowDecl>(OldD)) {
1227 OldIsUsingDecl = true;
1228
1229 // We can always introduce two using declarations into the same
1230 // context, even if they have identical signatures.
1231 if (NewIsUsingDecl) continue;
1232
1233 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1234 }
1235
1236 // A using-declaration does not conflict with another declaration
1237 // if one of them is hidden.
1238 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1239 continue;
1240
1241 // If either declaration was introduced by a using declaration,
1242 // we'll need to use slightly different rules for matching.
1243 // Essentially, these rules are the normal rules, except that
1244 // function templates hide function templates with different
1245 // return types or template parameter lists.
1246 bool UseMemberUsingDeclRules =
1247 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1248 !New->getFriendObjectKind();
1249
1250 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1251 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1252 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1254 continue;
1255 }
1256
1257 if (!isa<FunctionTemplateDecl>(OldD) &&
1258 !shouldLinkPossiblyHiddenDecl(*I, New))
1259 continue;
1260
1261 Match = *I;
1262 return OverloadKind::Match;
1263 }
1264
1265 // Builtins that have custom typechecking or have a reference should
1266 // not be overloadable or redeclarable.
1267 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1268 Match = *I;
1270 }
1271 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1272 // We can overload with these, which can show up when doing
1273 // redeclaration checks for UsingDecls.
1274 assert(Old.getLookupKind() == LookupUsingDeclName);
1275 } else if (isa<TagDecl>(OldD)) {
1276 // We can always overload with tags by hiding them.
1277 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1278 // Optimistically assume that an unresolved using decl will
1279 // overload; if it doesn't, we'll have to diagnose during
1280 // template instantiation.
1281 //
1282 // Exception: if the scope is dependent and this is not a class
1283 // member, the using declaration can only introduce an enumerator.
1284 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1285 Match = *I;
1287 }
1288 } else {
1289 // (C++ 13p1):
1290 // Only function declarations can be overloaded; object and type
1291 // declarations cannot be overloaded.
1292 Match = *I;
1294 }
1295 }
1296
1297 // C++ [temp.friend]p1:
1298 // For a friend function declaration that is not a template declaration:
1299 // -- if the name of the friend is a qualified or unqualified template-id,
1300 // [...], otherwise
1301 // -- if the name of the friend is a qualified-id and a matching
1302 // non-template function is found in the specified class or namespace,
1303 // the friend declaration refers to that function, otherwise,
1304 // -- if the name of the friend is a qualified-id and a matching function
1305 // template is found in the specified class or namespace, the friend
1306 // declaration refers to the deduced specialization of that function
1307 // template, otherwise
1308 // -- the name shall be an unqualified-id [...]
1309 // If we get here for a qualified friend declaration, we've just reached the
1310 // third bullet. If the type of the friend is dependent, skip this lookup
1311 // until instantiation.
1312 if (New->getFriendObjectKind() && New->getQualifier() &&
1313 !New->getDescribedFunctionTemplate() &&
1314 !New->getDependentSpecializationInfo() &&
1315 !New->getType()->isDependentType()) {
1316 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1317 TemplateSpecResult.addAllDecls(Old);
1318 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1319 /*QualifiedFriend*/true)) {
1320 New->setInvalidDecl();
1322 }
1323
1324 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1325 return OverloadKind::Match;
1326 }
1327
1329}
1330
1331template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1332 assert(D && "function decl should not be null");
1333 if (auto *A = D->getAttr<AttrT>())
1334 return !A->isImplicit();
1335 return false;
1336}
1337
1339 FunctionDecl *Old,
1340 bool UseMemberUsingDeclRules,
1341 bool ConsiderCudaAttrs,
1342 bool UseOverrideRules = false) {
1343 // C++ [basic.start.main]p2: This function shall not be overloaded.
1344 if (New->isMain())
1345 return false;
1346
1347 // MSVCRT user defined entry points cannot be overloaded.
1348 if (New->isMSVCRTEntryPoint())
1349 return false;
1350
1351 NamedDecl *OldDecl = Old;
1352 NamedDecl *NewDecl = New;
1354 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1355
1356 // C++ [temp.fct]p2:
1357 // A function template can be overloaded with other function templates
1358 // and with normal (non-template) functions.
1359 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1360 return true;
1361
1362 // Is the function New an overload of the function Old?
1363 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1364 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1365
1366 // Compare the signatures (C++ 1.3.10) of the two functions to
1367 // determine whether they are overloads. If we find any mismatch
1368 // in the signature, they are overloads.
1369
1370 // If either of these functions is a K&R-style function (no
1371 // prototype), then we consider them to have matching signatures.
1372 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1374 return false;
1375
1376 const auto *OldType = cast<FunctionProtoType>(OldQType);
1377 const auto *NewType = cast<FunctionProtoType>(NewQType);
1378
1379 // The signature of a function includes the types of its
1380 // parameters (C++ 1.3.10), which includes the presence or absence
1381 // of the ellipsis; see C++ DR 357).
1382 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1383 return true;
1384
1385 // For member-like friends, the enclosing class is part of the signature.
1386 if ((New->isMemberLikeConstrainedFriend() ||
1388 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1389 return true;
1390
1391 // Compare the parameter lists.
1392 // This can only be done once we have establish that friend functions
1393 // inhabit the same context, otherwise we might tried to instantiate
1394 // references to non-instantiated entities during constraint substitution.
1395 // GH78101.
1396 if (NewTemplate) {
1397 OldDecl = OldTemplate;
1398 NewDecl = NewTemplate;
1399 // C++ [temp.over.link]p4:
1400 // The signature of a function template consists of its function
1401 // signature, its return type and its template parameter list. The names
1402 // of the template parameters are significant only for establishing the
1403 // relationship between the template parameters and the rest of the
1404 // signature.
1405 //
1406 // We check the return type and template parameter lists for function
1407 // templates first; the remaining checks follow.
1408 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1409 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1410 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1411 bool SameReturnType = SemaRef.Context.hasSameType(
1412 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1413 // FIXME(GH58571): Match template parameter list even for non-constrained
1414 // template heads. This currently ensures that the code prior to C++20 is
1415 // not newly broken.
1416 bool ConstraintsInTemplateHead =
1419 // C++ [namespace.udecl]p11:
1420 // The set of declarations named by a using-declarator that inhabits a
1421 // class C does not include member functions and member function
1422 // templates of a base class that "correspond" to (and thus would
1423 // conflict with) a declaration of a function or function template in
1424 // C.
1425 // Comparing return types is not required for the "correspond" check to
1426 // decide whether a member introduced by a shadow declaration is hidden.
1427 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1428 !SameTemplateParameterList)
1429 return true;
1430 if (!UseMemberUsingDeclRules &&
1431 (!SameTemplateParameterList || !SameReturnType))
1432 return true;
1433 }
1434
1435 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1436 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1437
1438 int OldParamsOffset = 0;
1439 int NewParamsOffset = 0;
1440
1441 // When determining if a method is an overload from a base class, act as if
1442 // the implicit object parameter are of the same type.
1443
1444 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1446 auto ThisType = M->getFunctionObjectParameterReferenceType();
1447 if (ThisType.isConstQualified())
1448 Q.removeConst();
1449 return Q;
1450 }
1451
1452 // We do not allow overloading based off of '__restrict'.
1453 Q.removeRestrict();
1454
1455 // We may not have applied the implicit const for a constexpr member
1456 // function yet (because we haven't yet resolved whether this is a static
1457 // or non-static member function). Add it now, on the assumption that this
1458 // is a redeclaration of OldMethod.
1459 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1460 (M->isConstexpr() || M->isConsteval()) &&
1461 !isa<CXXConstructorDecl>(NewMethod))
1462 Q.addConst();
1463 return Q;
1464 };
1465
1466 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1467 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1468 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1469
1470 if (OldMethod->isExplicitObjectMemberFunction()) {
1471 BS.Quals.removeVolatile();
1472 DS.Quals.removeVolatile();
1473 }
1474
1475 return BS.Quals == DS.Quals;
1476 };
1477
1478 auto CompareType = [&](QualType Base, QualType D) {
1479 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1480 auto DS = D.getNonReferenceType().getCanonicalType().split();
1481
1482 if (!AreQualifiersEqual(BS, DS))
1483 return false;
1484
1485 if (OldMethod->isImplicitObjectMemberFunction() &&
1486 OldMethod->getParent() != NewMethod->getParent()) {
1487 CanQualType ParentType =
1488 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1489 if (ParentType.getTypePtr() != BS.Ty)
1490 return false;
1491 BS.Ty = DS.Ty;
1492 }
1493
1494 // FIXME: should we ignore some type attributes here?
1495 if (BS.Ty != DS.Ty)
1496 return false;
1497
1498 if (Base->isLValueReferenceType())
1499 return D->isLValueReferenceType();
1500 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1501 };
1502
1503 // If the function is a class member, its signature includes the
1504 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1505 auto DiagnoseInconsistentRefQualifiers = [&]() {
1506 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1507 return false;
1508 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1509 return false;
1510 if (OldMethod->isExplicitObjectMemberFunction() ||
1511 NewMethod->isExplicitObjectMemberFunction())
1512 return false;
1513 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1514 NewMethod->getRefQualifier() == RQ_None)) {
1515 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1516 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1517 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1518 return true;
1519 }
1520 return false;
1521 };
1522
1523 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1524 OldParamsOffset++;
1525 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1526 NewParamsOffset++;
1527
1528 if (OldType->getNumParams() - OldParamsOffset !=
1529 NewType->getNumParams() - NewParamsOffset ||
1531 {OldType->param_type_begin() + OldParamsOffset,
1532 OldType->param_type_end()},
1533 {NewType->param_type_begin() + NewParamsOffset,
1534 NewType->param_type_end()},
1535 nullptr)) {
1536 return true;
1537 }
1538
1539 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1540 !NewMethod->isStatic()) {
1541 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1542 const CXXMethodDecl *New) {
1543 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1544 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1545
1546 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1547 return F->getRefQualifier() == RQ_None &&
1548 !F->isExplicitObjectMemberFunction();
1549 };
1550
1551 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1552 CompareType(OldObjectType.getNonReferenceType(),
1553 NewObjectType.getNonReferenceType()))
1554 return true;
1555 return CompareType(OldObjectType, NewObjectType);
1556 }(OldMethod, NewMethod);
1557
1558 if (!HaveCorrespondingObjectParameters) {
1559 if (DiagnoseInconsistentRefQualifiers())
1560 return true;
1561 // CWG2554
1562 // and, if at least one is an explicit object member function, ignoring
1563 // object parameters
1564 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1565 !OldMethod->isExplicitObjectMemberFunction()))
1566 return true;
1567 }
1568 }
1569
1570 if (!UseOverrideRules &&
1571 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1572 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1573 OldRC = Old->getTrailingRequiresClause();
1574 if (!NewRC != !OldRC)
1575 return true;
1576 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1577 return true;
1578 if (NewRC &&
1579 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1580 NewDecl, NewRC.ConstraintExpr))
1581 return true;
1582 }
1583
1584 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1585 NewMethod->isImplicitObjectMemberFunction()) {
1586 if (DiagnoseInconsistentRefQualifiers())
1587 return true;
1588 }
1589
1590 // Though pass_object_size is placed on parameters and takes an argument, we
1591 // consider it to be a function-level modifier for the sake of function
1592 // identity. Either the function has one or more parameters with
1593 // pass_object_size or it doesn't.
1596 return true;
1597
1598 // enable_if attributes are an order-sensitive part of the signature.
1600 NewI = New->specific_attr_begin<EnableIfAttr>(),
1601 NewE = New->specific_attr_end<EnableIfAttr>(),
1602 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1603 OldE = Old->specific_attr_end<EnableIfAttr>();
1604 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1605 if (NewI == NewE || OldI == OldE)
1606 return true;
1607 llvm::FoldingSetNodeID NewID, OldID;
1608 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1609 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1610 if (NewID != OldID)
1611 return true;
1612 }
1613
1614 // At this point, it is known that the two functions have the same signature.
1615 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1616 // Don't allow overloading of destructors. (In theory we could, but it
1617 // would be a giant change to clang.)
1619 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1620 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1621 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1622 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1623 "Unexpected invalid target.");
1624
1625 // Allow overloading of functions with same signature and different CUDA
1626 // target attributes.
1627 if (NewTarget != OldTarget) {
1628 // Special case: non-constexpr function is allowed to override
1629 // constexpr virtual function
1630 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1631 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1636 return false;
1637 }
1638 return true;
1639 }
1640 }
1641 }
1642 }
1643
1644 // The signatures match; this is not an overload.
1645 return false;
1646}
1647
1649 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1650 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1651 ConsiderCudaAttrs);
1652}
1653
1655 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1656 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1657 /*UseMemberUsingDeclRules=*/false,
1658 /*ConsiderCudaAttrs=*/true,
1659 /*UseOverrideRules=*/true);
1660}
1661
1662/// Tries a user-defined conversion from From to ToType.
1663///
1664/// Produces an implicit conversion sequence for when a standard conversion
1665/// is not an option. See TryImplicitConversion for more information.
1668 bool SuppressUserConversions,
1669 AllowedExplicit AllowExplicit,
1670 bool InOverloadResolution,
1671 bool CStyle,
1672 bool AllowObjCWritebackConversion,
1673 bool AllowObjCConversionOnExplicit) {
1675
1676 if (SuppressUserConversions) {
1677 // We're not in the case above, so there is no conversion that
1678 // we can perform.
1680 return ICS;
1681 }
1682
1683 // Attempt user-defined conversion.
1684 OverloadCandidateSet Conversions(From->getExprLoc(),
1686 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1687 Conversions, AllowExplicit,
1688 AllowObjCConversionOnExplicit)) {
1689 case OR_Success:
1690 case OR_Deleted:
1691 ICS.setUserDefined();
1692 // C++ [over.ics.user]p4:
1693 // A conversion of an expression of class type to the same class
1694 // type is given Exact Match rank, and a conversion of an
1695 // expression of class type to a base class of that type is
1696 // given Conversion rank, in spite of the fact that a copy
1697 // constructor (i.e., a user-defined conversion function) is
1698 // called for those cases.
1700 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1701 QualType FromType;
1702 SourceLocation FromLoc;
1703 // C++11 [over.ics.list]p6, per DR2137:
1704 // C++17 [over.ics.list]p6:
1705 // If C is not an initializer-list constructor and the initializer list
1706 // has a single element of type cv U, where U is X or a class derived
1707 // from X, the implicit conversion sequence has Exact Match rank if U is
1708 // X, or Conversion rank if U is derived from X.
1709 bool FromListInit = false;
1710 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1711 InitList && InitList->getNumInits() == 1 &&
1713 const Expr *SingleInit = InitList->getInit(0);
1714 FromType = SingleInit->getType();
1715 FromLoc = SingleInit->getBeginLoc();
1716 FromListInit = true;
1717 } else {
1718 FromType = From->getType();
1719 FromLoc = From->getBeginLoc();
1720 }
1721 QualType FromCanon =
1723 QualType ToCanon
1725 if ((FromCanon == ToCanon ||
1726 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1727 // Turn this into a "standard" conversion sequence, so that it
1728 // gets ranked with standard conversion sequences.
1730 ICS.setStandard();
1732 ICS.Standard.setFromType(FromType);
1733 ICS.Standard.setAllToTypes(ToType);
1734 ICS.Standard.FromBracedInitList = FromListInit;
1737 if (ToCanon != FromCanon)
1739 }
1740 }
1741 break;
1742
1743 case OR_Ambiguous:
1744 ICS.setAmbiguous();
1745 ICS.Ambiguous.setFromType(From->getType());
1746 ICS.Ambiguous.setToType(ToType);
1747 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1748 Cand != Conversions.end(); ++Cand)
1749 if (Cand->Best)
1750 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1751 break;
1752
1753 // Fall through.
1756 break;
1757 }
1758
1759 return ICS;
1760}
1761
1762/// TryImplicitConversion - Attempt to perform an implicit conversion
1763/// from the given expression (Expr) to the given type (ToType). This
1764/// function returns an implicit conversion sequence that can be used
1765/// to perform the initialization. Given
1766///
1767/// void f(float f);
1768/// void g(int i) { f(i); }
1769///
1770/// this routine would produce an implicit conversion sequence to
1771/// describe the initialization of f from i, which will be a standard
1772/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1773/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1774//
1775/// Note that this routine only determines how the conversion can be
1776/// performed; it does not actually perform the conversion. As such,
1777/// it will not produce any diagnostics if no conversion is available,
1778/// but will instead return an implicit conversion sequence of kind
1779/// "BadConversion".
1780///
1781/// If @p SuppressUserConversions, then user-defined conversions are
1782/// not permitted.
1783/// If @p AllowExplicit, then explicit user-defined conversions are
1784/// permitted.
1785///
1786/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1787/// writeback conversion, which allows __autoreleasing id* parameters to
1788/// be initialized with __strong id* or __weak id* arguments.
1789static ImplicitConversionSequence
1791 bool SuppressUserConversions,
1792 AllowedExplicit AllowExplicit,
1793 bool InOverloadResolution,
1794 bool CStyle,
1795 bool AllowObjCWritebackConversion,
1796 bool AllowObjCConversionOnExplicit) {
1798 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1799 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1800 ICS.setStandard();
1801 return ICS;
1802 }
1803
1804 if (!S.getLangOpts().CPlusPlus) {
1806 return ICS;
1807 }
1808
1809 // C++ [over.ics.user]p4:
1810 // A conversion of an expression of class type to the same class
1811 // type is given Exact Match rank, and a conversion of an
1812 // expression of class type to a base class of that type is
1813 // given Conversion rank, in spite of the fact that a copy/move
1814 // constructor (i.e., a user-defined conversion function) is
1815 // called for those cases.
1816 QualType FromType = From->getType();
1817 if (ToType->isRecordType() &&
1818 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1819 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1820 ICS.setStandard();
1822 ICS.Standard.setFromType(FromType);
1823 ICS.Standard.setAllToTypes(ToType);
1824
1825 // We don't actually check at this point whether there is a valid
1826 // copy/move constructor, since overloading just assumes that it
1827 // exists. When we actually perform initialization, we'll find the
1828 // appropriate constructor to copy the returned object, if needed.
1829 ICS.Standard.CopyConstructor = nullptr;
1830
1831 // Determine whether this is considered a derived-to-base conversion.
1832 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1834
1835 return ICS;
1836 }
1837
1838 if (S.getLangOpts().HLSL) {
1839 // Handle conversion of the HLSL resource types.
1840 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1841 if (FromTy->isHLSLAttributedResourceType()) {
1842 // Attributed resource types can convert to other attributed
1843 // resource types with the same attributes and contained types,
1844 // or to __hlsl_resource_t without any attributes.
1845 bool CanConvert = false;
1846 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1847 if (ToTy->isHLSLAttributedResourceType()) {
1848 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1849 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1850 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1851 FromResType->getWrappedType()) &&
1852 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1853 FromResType->getContainedType()) &&
1854 ToResType->getAttrs() == FromResType->getAttrs())
1855 CanConvert = true;
1856 } else if (ToTy->isHLSLResourceType()) {
1857 CanConvert = true;
1858 }
1859 if (CanConvert) {
1860 ICS.setStandard();
1862 ICS.Standard.setFromType(FromType);
1863 ICS.Standard.setAllToTypes(ToType);
1864 return ICS;
1865 }
1866 }
1867 }
1868
1869 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1870 AllowExplicit, InOverloadResolution, CStyle,
1871 AllowObjCWritebackConversion,
1872 AllowObjCConversionOnExplicit);
1873}
1874
1875ImplicitConversionSequence
1877 bool SuppressUserConversions,
1878 AllowedExplicit AllowExplicit,
1879 bool InOverloadResolution,
1880 bool CStyle,
1881 bool AllowObjCWritebackConversion) {
1882 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1883 AllowExplicit, InOverloadResolution, CStyle,
1884 AllowObjCWritebackConversion,
1885 /*AllowObjCConversionOnExplicit=*/false);
1886}
1887
1889 AssignmentAction Action,
1890 bool AllowExplicit) {
1891 if (checkPlaceholderForOverload(*this, From))
1892 return ExprError();
1893
1894 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1895 bool AllowObjCWritebackConversion =
1896 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1897 Action == AssignmentAction::Sending);
1898 if (getLangOpts().ObjC)
1899 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1900 From->getType(), From);
1902 *this, From, ToType,
1903 /*SuppressUserConversions=*/false,
1904 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1905 /*InOverloadResolution=*/false,
1906 /*CStyle=*/false, AllowObjCWritebackConversion,
1907 /*AllowObjCConversionOnExplicit=*/false);
1908 return PerformImplicitConversion(From, ToType, ICS, Action);
1909}
1910
1912 QualType &ResultTy) const {
1913 bool Changed = IsFunctionConversion(FromType, ToType);
1914 if (Changed)
1915 ResultTy = ToType;
1916 return Changed;
1917}
1918
1919bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1920 if (Context.hasSameUnqualifiedType(FromType, ToType))
1921 return false;
1922
1923 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1924 // or F(t noexcept) -> F(t)
1925 // where F adds one of the following at most once:
1926 // - a pointer
1927 // - a member pointer
1928 // - a block pointer
1929 // Changes here need matching changes in FindCompositePointerType.
1930 CanQualType CanTo = Context.getCanonicalType(ToType);
1931 CanQualType CanFrom = Context.getCanonicalType(FromType);
1932 Type::TypeClass TyClass = CanTo->getTypeClass();
1933 if (TyClass != CanFrom->getTypeClass()) return false;
1934 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1935 if (TyClass == Type::Pointer) {
1936 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1937 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1938 } else if (TyClass == Type::BlockPointer) {
1939 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1940 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1941 } else if (TyClass == Type::MemberPointer) {
1942 auto ToMPT = CanTo.castAs<MemberPointerType>();
1943 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1944 // A function pointer conversion cannot change the class of the function.
1945 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1946 FromMPT->getMostRecentCXXRecordDecl()))
1947 return false;
1948 CanTo = ToMPT->getPointeeType();
1949 CanFrom = FromMPT->getPointeeType();
1950 } else {
1951 return false;
1952 }
1953
1954 TyClass = CanTo->getTypeClass();
1955 if (TyClass != CanFrom->getTypeClass()) return false;
1956 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1957 return false;
1958 }
1959
1960 const auto *FromFn = cast<FunctionType>(CanFrom);
1961 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1962
1963 const auto *ToFn = cast<FunctionType>(CanTo);
1964 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1965
1966 bool Changed = false;
1967
1968 // Drop 'noreturn' if not present in target type.
1969 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1970 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1971 Changed = true;
1972 }
1973
1974 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1975 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1976
1977 if (FromFPT && ToFPT) {
1978 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1979 QualType NewTy = Context.getFunctionType(
1980 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1981 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1982 ToFPT->hasCFIUncheckedCallee()));
1983 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1984 FromFn = FromFPT;
1985 Changed = true;
1986 }
1987 }
1988
1989 // Drop 'noexcept' if not present in target type.
1990 if (FromFPT && ToFPT) {
1991 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1992 FromFn = cast<FunctionType>(
1993 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1994 EST_None)
1995 .getTypePtr());
1996 Changed = true;
1997 }
1998
1999 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2000 // only if the ExtParameterInfo lists of the two function prototypes can be
2001 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2003 bool CanUseToFPT, CanUseFromFPT;
2004 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2005 CanUseFromFPT, NewParamInfos) &&
2006 CanUseToFPT && !CanUseFromFPT) {
2007 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2008 ExtInfo.ExtParameterInfos =
2009 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2010 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2011 FromFPT->getParamTypes(), ExtInfo);
2012 FromFn = QT->getAs<FunctionType>();
2013 Changed = true;
2014 }
2015
2016 if (Context.hasAnyFunctionEffects()) {
2017 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2018
2019 // Transparently add/drop effects; here we are concerned with
2020 // language rules/canonicalization. Adding/dropping effects is a warning.
2021 const auto FromFX = FromFPT->getFunctionEffects();
2022 const auto ToFX = ToFPT->getFunctionEffects();
2023 if (FromFX != ToFX) {
2024 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2025 ExtInfo.FunctionEffects = ToFX;
2026 QualType QT = Context.getFunctionType(
2027 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2028 FromFn = QT->getAs<FunctionType>();
2029 Changed = true;
2030 }
2031 }
2032 }
2033
2034 if (!Changed)
2035 return false;
2036
2037 assert(QualType(FromFn, 0).isCanonical());
2038 if (QualType(FromFn, 0) != CanTo) return false;
2039
2040 return true;
2041}
2042
2043/// Determine whether the conversion from FromType to ToType is a valid
2044/// floating point conversion.
2045///
2046static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2047 QualType ToType) {
2048 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2049 return false;
2050 // FIXME: disable conversions between long double, __ibm128 and __float128
2051 // if their representation is different until there is back end support
2052 // We of course allow this conversion if long double is really double.
2053
2054 // Conversions between bfloat16 and float16 are currently not supported.
2055 if ((FromType->isBFloat16Type() &&
2056 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2057 (ToType->isBFloat16Type() &&
2058 (FromType->isFloat16Type() || FromType->isHalfType())))
2059 return false;
2060
2061 // Conversions between IEEE-quad and IBM-extended semantics are not
2062 // permitted.
2063 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2064 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2065 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2066 &ToSem == &llvm::APFloat::IEEEquad()) ||
2067 (&FromSem == &llvm::APFloat::IEEEquad() &&
2068 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2069 return false;
2070 return true;
2071}
2072
2074 QualType ToType,
2076 Expr *From) {
2077 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2078 return true;
2079
2080 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2082 return true;
2083 }
2084
2085 if (IsFloatingPointConversion(S, FromType, ToType)) {
2087 return true;
2088 }
2089
2090 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2092 return true;
2093 }
2094
2095 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2097 ToType->isRealFloatingType())) {
2099 return true;
2100 }
2101
2102 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2104 return true;
2105 }
2106
2107 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2108 ToType->isIntegralType(S.Context)) {
2110 return true;
2111 }
2112
2113 return false;
2114}
2115
2116/// Determine whether the conversion from FromType to ToType is a valid
2117/// matrix conversion.
2118///
2119/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2120/// conversion.
2121static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2123 ImplicitConversionKind &ElConv, Expr *From,
2124 bool InOverloadResolution, bool CStyle) {
2125 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2126 if (!S.getLangOpts().HLSL)
2127 return false;
2128
2129 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2130 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2131
2132 // If both arguments are matrix, handle possible matrix truncation and
2133 // element conversion.
2134 if (ToMatrixType && FromMatrixType) {
2135 unsigned FromCols = FromMatrixType->getNumColumns();
2136 unsigned ToCols = ToMatrixType->getNumColumns();
2137 if (FromCols < ToCols)
2138 return false;
2139
2140 unsigned FromRows = FromMatrixType->getNumRows();
2141 unsigned ToRows = ToMatrixType->getNumRows();
2142 if (FromRows < ToRows)
2143 return false;
2144
2145 if (FromRows == ToRows && FromCols == ToCols)
2146 ElConv = ICK_Identity;
2147 else
2149
2150 QualType FromElTy = FromMatrixType->getElementType();
2151 QualType ToElTy = ToMatrixType->getElementType();
2152 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2153 return true;
2154 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2155 }
2156
2157 // Matrix splat from any arithmetic type to a matrix.
2158 if (ToMatrixType && FromType->isArithmeticType()) {
2159 ElConv = ICK_HLSL_Matrix_Splat;
2160 QualType ToElTy = ToMatrixType->getElementType();
2161 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2162 }
2163 if (FromMatrixType && !ToMatrixType) {
2165 QualType FromElTy = FromMatrixType->getElementType();
2166 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2167 return true;
2168 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2169 }
2170
2171 return false;
2172}
2173
2174/// Determine whether the conversion from FromType to ToType is a valid
2175/// vector conversion.
2176///
2177/// \param ICK Will be set to the vector conversion kind, if this is a vector
2178/// conversion.
2179static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2181 ImplicitConversionKind &ElConv, Expr *From,
2182 bool InOverloadResolution, bool CStyle) {
2183 // We need at least one of these types to be a vector type to have a vector
2184 // conversion.
2185 if (!ToType->isVectorType() && !FromType->isVectorType())
2186 return false;
2187
2188 // Identical types require no conversions.
2189 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2190 return false;
2191
2192 // HLSL allows implicit truncation of vector types.
2193 if (S.getLangOpts().HLSL) {
2194 auto *ToExtType = ToType->getAs<ExtVectorType>();
2195 auto *FromExtType = FromType->getAs<ExtVectorType>();
2196
2197 // If both arguments are vectors, handle possible vector truncation and
2198 // element conversion.
2199 if (ToExtType && FromExtType) {
2200 unsigned FromElts = FromExtType->getNumElements();
2201 unsigned ToElts = ToExtType->getNumElements();
2202 if (FromElts < ToElts)
2203 return false;
2204 if (FromElts == ToElts)
2205 ElConv = ICK_Identity;
2206 else
2208
2209 QualType FromElTy = FromExtType->getElementType();
2210 QualType ToElTy = ToExtType->getElementType();
2211 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2212 return true;
2213 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2214 }
2215 if (FromExtType && !ToExtType) {
2217 QualType FromElTy = FromExtType->getElementType();
2218 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2219 return true;
2220 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2221 }
2222 // Fallthrough for the case where ToType is a vector and FromType is not.
2223 }
2224
2225 // There are no conversions between extended vector types, only identity.
2226 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2227 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2228 // Implicit conversions require the same number of elements.
2229 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2230 return false;
2231
2232 // Permit implicit conversions from integral values to boolean vectors.
2233 if (ToType->isExtVectorBoolType() &&
2234 FromExtType->getElementType()->isIntegerType()) {
2236 return true;
2237 }
2238 // There are no other conversions between extended vector types.
2239 return false;
2240 }
2241
2242 // Vector splat from any arithmetic type to a vector.
2243 if (FromType->isArithmeticType()) {
2244 if (S.getLangOpts().HLSL) {
2245 ElConv = ICK_HLSL_Vector_Splat;
2246 QualType ToElTy = ToExtType->getElementType();
2247 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2248 From);
2249 }
2250 ICK = ICK_Vector_Splat;
2251 return true;
2252 }
2253 }
2254
2255 if (ToType->isSVESizelessBuiltinType() ||
2256 FromType->isSVESizelessBuiltinType())
2257 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2258 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2260 return true;
2261 }
2262
2263 if (ToType->isRVVSizelessBuiltinType() ||
2264 FromType->isRVVSizelessBuiltinType())
2265 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2266 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2268 return true;
2269 }
2270
2271 // We can perform the conversion between vector types in the following cases:
2272 // 1)vector types are equivalent AltiVec and GCC vector types
2273 // 2)lax vector conversions are permitted and the vector types are of the
2274 // same size
2275 // 3)the destination type does not have the ARM MVE strict-polymorphism
2276 // attribute, which inhibits lax vector conversion for overload resolution
2277 // only
2278 if (ToType->isVectorType() && FromType->isVectorType()) {
2279 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2280 (S.isLaxVectorConversion(FromType, ToType) &&
2281 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2282 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2283 S.isLaxVectorConversion(FromType, ToType) &&
2284 S.anyAltivecTypes(FromType, ToType) &&
2285 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2286 !InOverloadResolution && !CStyle) {
2287 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2288 << FromType << ToType;
2289 }
2291 return true;
2292 }
2293 }
2294
2295 return false;
2296}
2297
2298static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2299 bool InOverloadResolution,
2300 StandardConversionSequence &SCS,
2301 bool CStyle);
2302
2303static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2304 QualType ToType,
2305 bool InOverloadResolution,
2306 StandardConversionSequence &SCS,
2307 bool CStyle);
2308
2309/// IsStandardConversion - Determines whether there is a standard
2310/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2311/// expression From to the type ToType. Standard conversion sequences
2312/// only consider non-class types; for conversions that involve class
2313/// types, use TryImplicitConversion. If a conversion exists, SCS will
2314/// contain the standard conversion sequence required to perform this
2315/// conversion and this routine will return true. Otherwise, this
2316/// routine will return false and the value of SCS is unspecified.
2317static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2318 bool InOverloadResolution,
2320 bool CStyle,
2321 bool AllowObjCWritebackConversion) {
2322 QualType FromType = From->getType();
2323
2324 // Standard conversions (C++ [conv])
2326 SCS.IncompatibleObjC = false;
2327 SCS.setFromType(FromType);
2328 SCS.CopyConstructor = nullptr;
2329
2330 // There are no standard conversions for class types in C++, so
2331 // abort early. When overloading in C, however, we do permit them.
2332 if (S.getLangOpts().CPlusPlus &&
2333 (FromType->isRecordType() || ToType->isRecordType()))
2334 return false;
2335
2336 // The first conversion can be an lvalue-to-rvalue conversion,
2337 // array-to-pointer conversion, or function-to-pointer conversion
2338 // (C++ 4p1).
2339
2340 if (FromType == S.Context.OverloadTy) {
2341 DeclAccessPair AccessPair;
2342 if (FunctionDecl *Fn
2343 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2344 AccessPair)) {
2345 // We were able to resolve the address of the overloaded function,
2346 // so we can convert to the type of that function.
2347 FromType = Fn->getType();
2348 SCS.setFromType(FromType);
2349
2350 // we can sometimes resolve &foo<int> regardless of ToType, so check
2351 // if the type matches (identity) or we are converting to bool
2353 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2354 // if the function type matches except for [[noreturn]], it's ok
2355 if (!S.IsFunctionConversion(FromType,
2357 // otherwise, only a boolean conversion is standard
2358 if (!ToType->isBooleanType())
2359 return false;
2360 }
2361
2362 // Check if the "from" expression is taking the address of an overloaded
2363 // function and recompute the FromType accordingly. Take advantage of the
2364 // fact that non-static member functions *must* have such an address-of
2365 // expression.
2366 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2367 if (Method && !Method->isStatic() &&
2368 !Method->isExplicitObjectMemberFunction()) {
2369 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2370 "Non-unary operator on non-static member address");
2371 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2372 == UO_AddrOf &&
2373 "Non-address-of operator on non-static member address");
2374 FromType = S.Context.getMemberPointerType(
2375 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2376 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2377 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2378 UO_AddrOf &&
2379 "Non-address-of operator for overloaded function expression");
2380 FromType = S.Context.getPointerType(FromType);
2381 }
2382 } else {
2383 return false;
2384 }
2385 }
2386
2387 bool argIsLValue = From->isGLValue();
2388 // To handle conversion from ArrayParameterType to ConstantArrayType
2389 // this block must be above the one below because Array parameters
2390 // do not decay and when handling HLSLOutArgExprs and
2391 // the From expression is an LValue.
2392 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2393 ToType->isConstantArrayType()) {
2394 // HLSL constant array parameters do not decay, so if the argument is a
2395 // constant array and the parameter is an ArrayParameterType we have special
2396 // handling here.
2397 if (ToType->isArrayParameterType()) {
2398 FromType = S.Context.getArrayParameterType(FromType);
2399 } else if (FromType->isArrayParameterType()) {
2400 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2401 FromType = APT->getConstantArrayType(S.Context);
2402 }
2403
2405
2406 // Don't consider qualifiers, which include things like address spaces
2407 if (FromType.getCanonicalType().getUnqualifiedType() !=
2409 return false;
2410
2411 SCS.setAllToTypes(ToType);
2412 return true;
2413 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2414 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2415 // Lvalue-to-rvalue conversion (C++11 4.1):
2416 // A glvalue (3.10) of a non-function, non-array type T can
2417 // be converted to a prvalue.
2418
2420
2421 // C11 6.3.2.1p2:
2422 // ... if the lvalue has atomic type, the value has the non-atomic version
2423 // of the type of the lvalue ...
2424 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2425 FromType = Atomic->getValueType();
2426
2427 // If T is a non-class type, the type of the rvalue is the
2428 // cv-unqualified version of T. Otherwise, the type of the rvalue
2429 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2430 // just strip the qualifiers because they don't matter.
2431 FromType = FromType.getUnqualifiedType();
2432 } else if (FromType->isArrayType()) {
2433 // Array-to-pointer conversion (C++ 4.2)
2435
2436 // An lvalue or rvalue of type "array of N T" or "array of unknown
2437 // bound of T" can be converted to an rvalue of type "pointer to
2438 // T" (C++ 4.2p1).
2439 FromType = S.Context.getArrayDecayedType(FromType);
2440
2441 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2442 // This conversion is deprecated in C++03 (D.4)
2444
2445 // For the purpose of ranking in overload resolution
2446 // (13.3.3.1.1), this conversion is considered an
2447 // array-to-pointer conversion followed by a qualification
2448 // conversion (4.4). (C++ 4.2p2)
2449 SCS.Second = ICK_Identity;
2452 SCS.setAllToTypes(FromType);
2453 return true;
2454 }
2455 } else if (FromType->isFunctionType() && argIsLValue) {
2456 // Function-to-pointer conversion (C++ 4.3).
2458
2459 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2460 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2462 return false;
2463
2464 // An lvalue of function type T can be converted to an rvalue of
2465 // type "pointer to T." The result is a pointer to the
2466 // function. (C++ 4.3p1).
2467 FromType = S.Context.getPointerType(FromType);
2468 } else {
2469 // We don't require any conversions for the first step.
2470 SCS.First = ICK_Identity;
2471 }
2472 SCS.setToType(0, FromType);
2473
2474 // The second conversion can be an integral promotion, floating
2475 // point promotion, integral conversion, floating point conversion,
2476 // floating-integral conversion, pointer conversion,
2477 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2478 // For overloading in C, this can also be a "compatible-type"
2479 // conversion.
2480 bool IncompatibleObjC = false;
2482 ImplicitConversionKind DimensionICK = ICK_Identity;
2483 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2484 // The unqualified versions of the types are the same: there's no
2485 // conversion to do.
2486 SCS.Second = ICK_Identity;
2487 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2488 // Integral promotion (C++ 4.5).
2490 FromType = ToType.getUnqualifiedType();
2491 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2492 // Floating point promotion (C++ 4.6).
2494 FromType = ToType.getUnqualifiedType();
2495 } else if (S.IsComplexPromotion(FromType, ToType)) {
2496 // Complex promotion (Clang extension)
2498 FromType = ToType.getUnqualifiedType();
2499 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2500 // OverflowBehaviorType promotions
2502 FromType = ToType.getUnqualifiedType();
2503 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2504 // OverflowBehaviorType conversions
2506 FromType = ToType.getUnqualifiedType();
2507 } else if (ToType->isBooleanType() &&
2508 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2509 FromType->isBlockPointerType() ||
2510 FromType->isMemberPointerType())) {
2511 // Boolean conversions (C++ 4.12).
2513 FromType = S.Context.BoolTy;
2514 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2515 ToType->isIntegralType(S.Context)) {
2516 // Integral conversions (C++ 4.7).
2518 FromType = ToType.getUnqualifiedType();
2519 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2520 // Complex conversions (C99 6.3.1.6)
2522 FromType = ToType.getUnqualifiedType();
2523 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2524 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2525 // Complex-real conversions (C99 6.3.1.7)
2527 FromType = ToType.getUnqualifiedType();
2528 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2529 // Floating point conversions (C++ 4.8).
2531 FromType = ToType.getUnqualifiedType();
2532 } else if ((FromType->isRealFloatingType() &&
2533 ToType->isIntegralType(S.Context)) ||
2535 ToType->isRealFloatingType())) {
2536
2537 // Floating-integral conversions (C++ 4.9).
2539 FromType = ToType.getUnqualifiedType();
2540 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2542 } else if (AllowObjCWritebackConversion &&
2543 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2545 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2546 FromType, IncompatibleObjC)) {
2547 // Pointer conversions (C++ 4.10).
2549 SCS.IncompatibleObjC = IncompatibleObjC;
2550 FromType = FromType.getUnqualifiedType();
2551 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2552 InOverloadResolution, FromType)) {
2553 // Pointer to member conversions (4.11).
2555 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2556 From, InOverloadResolution, CStyle)) {
2557 SCS.Second = SecondICK;
2558 SCS.Dimension = DimensionICK;
2559 FromType = ToType.getUnqualifiedType();
2560 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2561 From, InOverloadResolution, CStyle)) {
2562 SCS.Second = SecondICK;
2563 SCS.Dimension = DimensionICK;
2564 FromType = ToType.getUnqualifiedType();
2565 } else if (!S.getLangOpts().CPlusPlus &&
2566 S.Context.typesAreCompatible(ToType, FromType)) {
2567 // Compatible conversions (Clang extension for C function overloading)
2569 FromType = ToType.getUnqualifiedType();
2571 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2573 FromType = ToType;
2574 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2575 CStyle)) {
2576 // tryAtomicConversion has updated the standard conversion sequence
2577 // appropriately.
2578 return true;
2580 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2581 return true;
2582 } else if (ToType->isEventT() &&
2584 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2586 FromType = ToType;
2587 } else if (ToType->isQueueT() &&
2589 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2591 FromType = ToType;
2592 } else if (ToType->isSamplerT() &&
2595 FromType = ToType;
2596 } else if ((ToType->isFixedPointType() &&
2597 FromType->isConvertibleToFixedPointType()) ||
2598 (FromType->isFixedPointType() &&
2599 ToType->isConvertibleToFixedPointType())) {
2601 FromType = ToType;
2602 } else {
2603 // No second conversion required.
2604 SCS.Second = ICK_Identity;
2605 }
2606 SCS.setToType(1, FromType);
2607
2608 // The third conversion can be a function pointer conversion or a
2609 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2610 bool ObjCLifetimeConversion;
2611 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2612 // Function pointer conversions (removing 'noexcept') including removal of
2613 // 'noreturn' (Clang extension).
2615 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2616 ObjCLifetimeConversion)) {
2618 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2619 FromType = ToType;
2620 } else {
2621 // No conversion required
2622 SCS.Third = ICK_Identity;
2623 }
2624
2625 // C++ [over.best.ics]p6:
2626 // [...] Any difference in top-level cv-qualification is
2627 // subsumed by the initialization itself and does not constitute
2628 // a conversion. [...]
2629 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2630 QualType CanonTo = S.Context.getCanonicalType(ToType);
2631 if (CanonFrom.getLocalUnqualifiedType()
2632 == CanonTo.getLocalUnqualifiedType() &&
2633 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2634 FromType = ToType;
2635 CanonFrom = CanonTo;
2636 }
2637
2638 SCS.setToType(2, FromType);
2639
2640 if (CanonFrom == CanonTo)
2641 return true;
2642
2643 // If we have not converted the argument type to the parameter type,
2644 // this is a bad conversion sequence, unless we're resolving an overload in C.
2645 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2646 return false;
2647
2648 ExprResult ER = ExprResult{From};
2649 AssignConvertType Conv =
2651 /*Diagnose=*/false,
2652 /*DiagnoseCFAudited=*/false,
2653 /*ConvertRHS=*/false);
2654 ImplicitConversionKind SecondConv;
2655 switch (Conv) {
2657 case AssignConvertType::
2658 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2659 SecondConv = ICK_C_Only_Conversion;
2660 break;
2661 // For our purposes, discarding qualifiers is just as bad as using an
2662 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2663 // qualifiers, as well.
2668 break;
2669 default:
2670 return false;
2671 }
2672
2673 // First can only be an lvalue conversion, so we pretend that this was the
2674 // second conversion. First should already be valid from earlier in the
2675 // function.
2676 SCS.Second = SecondConv;
2677 SCS.setToType(1, ToType);
2678
2679 // Third is Identity, because Second should rank us worse than any other
2680 // conversion. This could also be ICK_Qualification, but it's simpler to just
2681 // lump everything in with the second conversion, and we don't gain anything
2682 // from making this ICK_Qualification.
2683 SCS.Third = ICK_Identity;
2684 SCS.setToType(2, ToType);
2685 return true;
2686}
2687
2688static bool
2690 QualType &ToType,
2691 bool InOverloadResolution,
2693 bool CStyle) {
2694
2695 const RecordType *UT = ToType->getAsUnionType();
2696 if (!UT)
2697 return false;
2698 // The field to initialize within the transparent union.
2699 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2700 if (!UD->hasAttr<TransparentUnionAttr>())
2701 return false;
2702 // It's compatible if the expression matches any of the fields.
2703 for (const auto *it : UD->fields()) {
2704 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2705 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2706 ToType = it->getType();
2707 return true;
2708 }
2709 }
2710 return false;
2711}
2712
2713bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2714 const BuiltinType *To = ToType->getAs<BuiltinType>();
2715 // All integers are built-in.
2716 if (!To) {
2717 return false;
2718 }
2719
2720 // An rvalue of type char, signed char, unsigned char, short int, or
2721 // unsigned short int can be converted to an rvalue of type int if
2722 // int can represent all the values of the source type; otherwise,
2723 // the source rvalue can be converted to an rvalue of type unsigned
2724 // int (C++ 4.5p1).
2725 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2726 !FromType->isEnumeralType()) {
2727 if ( // We can promote any signed, promotable integer type to an int
2728 (FromType->isSignedIntegerType() ||
2729 // We can promote any unsigned integer type whose size is
2730 // less than int to an int.
2731 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2732 return To->getKind() == BuiltinType::Int;
2733 }
2734
2735 return To->getKind() == BuiltinType::UInt;
2736 }
2737
2738 // C++11 [conv.prom]p3:
2739 // A prvalue of an unscoped enumeration type whose underlying type is not
2740 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2741 // following types that can represent all the values of the enumeration
2742 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2743 // unsigned int, long int, unsigned long int, long long int, or unsigned
2744 // long long int. If none of the types in that list can represent all the
2745 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2746 // type can be converted to an rvalue a prvalue of the extended integer type
2747 // with lowest integer conversion rank (4.13) greater than the rank of long
2748 // long in which all the values of the enumeration can be represented. If
2749 // there are two such extended types, the signed one is chosen.
2750 // C++11 [conv.prom]p4:
2751 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2752 // can be converted to a prvalue of its underlying type. Moreover, if
2753 // integral promotion can be applied to its underlying type, a prvalue of an
2754 // unscoped enumeration type whose underlying type is fixed can also be
2755 // converted to a prvalue of the promoted underlying type.
2756 if (const auto *FromED = FromType->getAsEnumDecl()) {
2757 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2758 // provided for a scoped enumeration.
2759 if (FromED->isScoped())
2760 return false;
2761
2762 // We can perform an integral promotion to the underlying type of the enum,
2763 // even if that's not the promoted type. Note that the check for promoting
2764 // the underlying type is based on the type alone, and does not consider
2765 // the bitfield-ness of the actual source expression.
2766 if (FromED->isFixed()) {
2767 QualType Underlying = FromED->getIntegerType();
2768 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2769 IsIntegralPromotion(nullptr, Underlying, ToType);
2770 }
2771
2772 // We have already pre-calculated the promotion type, so this is trivial.
2773 if (ToType->isIntegerType() &&
2774 isCompleteType(From->getBeginLoc(), FromType))
2775 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2776
2777 // C++ [conv.prom]p5:
2778 // If the bit-field has an enumerated type, it is treated as any other
2779 // value of that type for promotion purposes.
2780 //
2781 // ... so do not fall through into the bit-field checks below in C++.
2782 if (getLangOpts().CPlusPlus)
2783 return false;
2784 }
2785
2786 // C++0x [conv.prom]p2:
2787 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2788 // to an rvalue a prvalue of the first of the following types that can
2789 // represent all the values of its underlying type: int, unsigned int,
2790 // long int, unsigned long int, long long int, or unsigned long long int.
2791 // If none of the types in that list can represent all the values of its
2792 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2793 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2794 // type.
2795 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2796 ToType->isIntegerType()) {
2797 // Determine whether the type we're converting from is signed or
2798 // unsigned.
2799 bool FromIsSigned = FromType->isSignedIntegerType();
2800 uint64_t FromSize = Context.getTypeSize(FromType);
2801
2802 // The types we'll try to promote to, in the appropriate
2803 // order. Try each of these types.
2804 QualType PromoteTypes[6] = {
2805 Context.IntTy, Context.UnsignedIntTy,
2806 Context.LongTy, Context.UnsignedLongTy ,
2807 Context.LongLongTy, Context.UnsignedLongLongTy
2808 };
2809 for (int Idx = 0; Idx < 6; ++Idx) {
2810 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2811 if (FromSize < ToSize ||
2812 (FromSize == ToSize &&
2813 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2814 // We found the type that we can promote to. If this is the
2815 // type we wanted, we have a promotion. Otherwise, no
2816 // promotion.
2817 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2818 }
2819 }
2820 }
2821
2822 // An rvalue for an integral bit-field (9.6) can be converted to an
2823 // rvalue of type int if int can represent all the values of the
2824 // bit-field; otherwise, it can be converted to unsigned int if
2825 // unsigned int can represent all the values of the bit-field. If
2826 // the bit-field is larger yet, no integral promotion applies to
2827 // it. If the bit-field has an enumerated type, it is treated as any
2828 // other value of that type for promotion purposes (C++ 4.5p3).
2829 // FIXME: We should delay checking of bit-fields until we actually perform the
2830 // conversion.
2831 //
2832 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2833 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2834 // bit-fields and those whose underlying type is larger than int) for GCC
2835 // compatibility.
2836 if (From) {
2837 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2838 std::optional<llvm::APSInt> BitWidth;
2839 if (FromType->isIntegralType(Context) &&
2840 (BitWidth =
2841 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2842 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2843 ToSize = Context.getTypeSize(ToType);
2844
2845 // Are we promoting to an int from a bitfield that fits in an int?
2846 if (*BitWidth < ToSize ||
2847 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2848 return To->getKind() == BuiltinType::Int;
2849 }
2850
2851 // Are we promoting to an unsigned int from an unsigned bitfield
2852 // that fits into an unsigned int?
2853 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2854 return To->getKind() == BuiltinType::UInt;
2855 }
2856
2857 return false;
2858 }
2859 }
2860 }
2861
2862 // An rvalue of type bool can be converted to an rvalue of type int,
2863 // with false becoming zero and true becoming one (C++ 4.5p4).
2864 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2865 return true;
2866 }
2867
2868 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2869 // integral type.
2870 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2871 ToType->isIntegerType())
2872 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2873
2874 return false;
2875}
2876
2878 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2879 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2880 /// An rvalue of type float can be converted to an rvalue of type
2881 /// double. (C++ 4.6p1).
2882 if (FromBuiltin->getKind() == BuiltinType::Float &&
2883 ToBuiltin->getKind() == BuiltinType::Double)
2884 return true;
2885
2886 // C99 6.3.1.5p1:
2887 // When a float is promoted to double or long double, or a
2888 // double is promoted to long double [...].
2889 if (!getLangOpts().CPlusPlus &&
2890 (FromBuiltin->getKind() == BuiltinType::Float ||
2891 FromBuiltin->getKind() == BuiltinType::Double) &&
2892 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2893 ToBuiltin->getKind() == BuiltinType::Float128 ||
2894 ToBuiltin->getKind() == BuiltinType::Ibm128))
2895 return true;
2896
2897 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2898 // or not native half types are enabled.
2899 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2900 (ToBuiltin->getKind() == BuiltinType::Float ||
2901 ToBuiltin->getKind() == BuiltinType::Double))
2902 return true;
2903
2904 // Half can be promoted to float.
2905 if (!getLangOpts().NativeHalfType &&
2906 FromBuiltin->getKind() == BuiltinType::Half &&
2907 ToBuiltin->getKind() == BuiltinType::Float)
2908 return true;
2909 }
2910
2911 return false;
2912}
2913
2915 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2916 if (!FromComplex)
2917 return false;
2918
2919 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2920 if (!ToComplex)
2921 return false;
2922
2923 return IsFloatingPointPromotion(FromComplex->getElementType(),
2924 ToComplex->getElementType()) ||
2925 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2926 ToComplex->getElementType());
2927}
2928
2930 if (!getLangOpts().OverflowBehaviorTypes)
2931 return false;
2932
2933 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2934 return false;
2935
2936 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2937}
2938
2940 QualType ToType) {
2941 if (!getLangOpts().OverflowBehaviorTypes)
2942 return false;
2943
2944 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2945 if (ToType->isBooleanType())
2946 return false;
2947 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2948 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2949 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2950 if (ToED->isScoped())
2951 return false;
2952 }
2953 return true;
2954 }
2955
2956 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2957 return true;
2958
2959 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2960 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2961
2962 return false;
2963}
2964
2965/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2966/// the pointer type FromPtr to a pointer to type ToPointee, with the
2967/// same type qualifiers as FromPtr has on its pointee type. ToType,
2968/// if non-empty, will be a pointer to ToType that may or may not have
2969/// the right set of qualifiers on its pointee.
2970///
2971static QualType
2973 QualType ToPointee, QualType ToType,
2974 ASTContext &Context,
2975 bool StripObjCLifetime = false) {
2976 assert((FromPtr->getTypeClass() == Type::Pointer ||
2977 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2978 "Invalid similarly-qualified pointer type");
2979
2980 /// Conversions to 'id' subsume cv-qualifier conversions.
2981 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2982 return ToType.getUnqualifiedType();
2983
2984 QualType CanonFromPointee
2985 = Context.getCanonicalType(FromPtr->getPointeeType());
2986 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2987 Qualifiers Quals = CanonFromPointee.getQualifiers();
2988
2989 if (StripObjCLifetime)
2990 Quals.removeObjCLifetime();
2991
2992 // Exact qualifier match -> return the pointer type we're converting to.
2993 if (CanonToPointee.getLocalQualifiers() == Quals) {
2994 // ToType is exactly what we need. Return it.
2995 if (!ToType.isNull())
2996 return ToType.getUnqualifiedType();
2997
2998 // Build a pointer to ToPointee. It has the right qualifiers
2999 // already.
3000 if (isa<ObjCObjectPointerType>(ToType))
3001 return Context.getObjCObjectPointerType(ToPointee);
3002 return Context.getPointerType(ToPointee);
3003 }
3004
3005 // Just build a canonical type that has the right qualifiers.
3006 QualType QualifiedCanonToPointee
3007 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3008
3009 if (isa<ObjCObjectPointerType>(ToType))
3010 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3011 return Context.getPointerType(QualifiedCanonToPointee);
3012}
3013
3015 bool InOverloadResolution,
3016 ASTContext &Context) {
3017 // Handle value-dependent integral null pointer constants correctly.
3018 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3019 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3021 return !InOverloadResolution;
3022
3023 return Expr->isNullPointerConstant(Context,
3024 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3026}
3027
3029 bool InOverloadResolution,
3030 QualType& ConvertedType,
3031 bool &IncompatibleObjC) {
3032 IncompatibleObjC = false;
3033 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3034 IncompatibleObjC))
3035 return true;
3036
3037 // Conversion from a null pointer constant to any Objective-C pointer type.
3038 if (ToType->isObjCObjectPointerType() &&
3039 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3040 ConvertedType = ToType;
3041 return true;
3042 }
3043
3044 // Blocks: Block pointers can be converted to void*.
3045 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3046 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3047 ConvertedType = ToType;
3048 return true;
3049 }
3050 // Blocks: A null pointer constant can be converted to a block
3051 // pointer type.
3052 if (ToType->isBlockPointerType() &&
3053 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3054 ConvertedType = ToType;
3055 return true;
3056 }
3057
3058 // If the left-hand-side is nullptr_t, the right side can be a null
3059 // pointer constant.
3060 if (ToType->isNullPtrType() &&
3061 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3062 ConvertedType = ToType;
3063 return true;
3064 }
3065
3066 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3067 if (!ToTypePtr)
3068 return false;
3069
3070 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3071 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3072 ConvertedType = ToType;
3073 return true;
3074 }
3075
3076 // Beyond this point, both types need to be pointers
3077 // , including objective-c pointers.
3078 QualType ToPointeeType = ToTypePtr->getPointeeType();
3079 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3080 !getLangOpts().ObjCAutoRefCount) {
3081 ConvertedType = BuildSimilarlyQualifiedPointerType(
3082 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3083 Context);
3084 return true;
3085 }
3086 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3087 if (!FromTypePtr)
3088 return false;
3089
3090 QualType FromPointeeType = FromTypePtr->getPointeeType();
3091
3092 // If the unqualified pointee types are the same, this can't be a
3093 // pointer conversion, so don't do all of the work below.
3094 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3095 return false;
3096
3097 // An rvalue of type "pointer to cv T," where T is an object type,
3098 // can be converted to an rvalue of type "pointer to cv void" (C++
3099 // 4.10p2).
3100 if (FromPointeeType->isIncompleteOrObjectType() &&
3101 ToPointeeType->isVoidType()) {
3102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3103 ToPointeeType,
3104 ToType, Context,
3105 /*StripObjCLifetime=*/true);
3106 return true;
3107 }
3108
3109 // MSVC allows implicit function to void* type conversion.
3110 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3111 ToPointeeType->isVoidType()) {
3112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3113 ToPointeeType,
3114 ToType, Context);
3115 return true;
3116 }
3117
3118 // When we're overloading in C, we allow a special kind of pointer
3119 // conversion for compatible-but-not-identical pointee types.
3120 if (!getLangOpts().CPlusPlus &&
3121 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3122 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3123 ToPointeeType,
3124 ToType, Context);
3125 return true;
3126 }
3127
3128 // C++ [conv.ptr]p3:
3129 //
3130 // An rvalue of type "pointer to cv D," where D is a class type,
3131 // can be converted to an rvalue of type "pointer to cv B," where
3132 // B is a base class (clause 10) of D. If B is an inaccessible
3133 // (clause 11) or ambiguous (10.2) base class of D, a program that
3134 // necessitates this conversion is ill-formed. The result of the
3135 // conversion is a pointer to the base class sub-object of the
3136 // derived class object. The null pointer value is converted to
3137 // the null pointer value of the destination type.
3138 //
3139 // Note that we do not check for ambiguity or inaccessibility
3140 // here. That is handled by CheckPointerConversion.
3141 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3142 ToPointeeType->isRecordType() &&
3143 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3144 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3146 ToPointeeType,
3147 ToType, Context);
3148 return true;
3149 }
3150
3151 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3152 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3153 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3154 ToPointeeType,
3155 ToType, Context);
3156 return true;
3157 }
3158
3159 return false;
3160}
3161
3162/// Adopt the given qualifiers for the given type.
3164 Qualifiers TQs = T.getQualifiers();
3165
3166 // Check whether qualifiers already match.
3167 if (TQs == Qs)
3168 return T;
3169
3170 if (Qs.compatiblyIncludes(TQs, Context))
3171 return Context.getQualifiedType(T, Qs);
3172
3173 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3174}
3175
3177 QualType& ConvertedType,
3178 bool &IncompatibleObjC) {
3179 if (!getLangOpts().ObjC)
3180 return false;
3181
3182 // The set of qualifiers on the type we're converting from.
3183 Qualifiers FromQualifiers = FromType.getQualifiers();
3184
3185 // First, we handle all conversions on ObjC object pointer types.
3186 const ObjCObjectPointerType* ToObjCPtr =
3187 ToType->getAs<ObjCObjectPointerType>();
3188 const ObjCObjectPointerType *FromObjCPtr =
3189 FromType->getAs<ObjCObjectPointerType>();
3190
3191 if (ToObjCPtr && FromObjCPtr) {
3192 // If the pointee types are the same (ignoring qualifications),
3193 // then this is not a pointer conversion.
3194 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3195 FromObjCPtr->getPointeeType()))
3196 return false;
3197
3198 // Conversion between Objective-C pointers.
3199 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3200 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3201 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3202 if (getLangOpts().CPlusPlus && LHS && RHS &&
3204 FromObjCPtr->getPointeeType(), getASTContext()))
3205 return false;
3206 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3207 ToObjCPtr->getPointeeType(),
3208 ToType, Context);
3209 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3210 return true;
3211 }
3212
3213 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3214 // Okay: this is some kind of implicit downcast of Objective-C
3215 // interfaces, which is permitted. However, we're going to
3216 // complain about it.
3217 IncompatibleObjC = true;
3218 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3219 ToObjCPtr->getPointeeType(),
3220 ToType, Context);
3221 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3222 return true;
3223 }
3224 }
3225 // Beyond this point, both types need to be C pointers or block pointers.
3226 QualType ToPointeeType;
3227 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3228 ToPointeeType = ToCPtr->getPointeeType();
3229 else if (const BlockPointerType *ToBlockPtr =
3230 ToType->getAs<BlockPointerType>()) {
3231 // Objective C++: We're able to convert from a pointer to any object
3232 // to a block pointer type.
3233 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3234 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3235 return true;
3236 }
3237 ToPointeeType = ToBlockPtr->getPointeeType();
3238 }
3239 else if (FromType->getAs<BlockPointerType>() &&
3240 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3241 // Objective C++: We're able to convert from a block pointer type to a
3242 // pointer to any object.
3243 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3244 return true;
3245 }
3246 else
3247 return false;
3248
3249 QualType FromPointeeType;
3250 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3251 FromPointeeType = FromCPtr->getPointeeType();
3252 else if (const BlockPointerType *FromBlockPtr =
3253 FromType->getAs<BlockPointerType>())
3254 FromPointeeType = FromBlockPtr->getPointeeType();
3255 else
3256 return false;
3257
3258 // If we have pointers to pointers, recursively check whether this
3259 // is an Objective-C conversion.
3260 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3261 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3262 IncompatibleObjC)) {
3263 // We always complain about this conversion.
3264 IncompatibleObjC = true;
3265 ConvertedType = Context.getPointerType(ConvertedType);
3266 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3267 return true;
3268 }
3269 // Allow conversion of pointee being objective-c pointer to another one;
3270 // as in I* to id.
3271 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3272 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3273 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3274 IncompatibleObjC)) {
3275
3276 ConvertedType = Context.getPointerType(ConvertedType);
3277 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3278 return true;
3279 }
3280
3281 // If we have pointers to functions or blocks, check whether the only
3282 // differences in the argument and result types are in Objective-C
3283 // pointer conversions. If so, we permit the conversion (but
3284 // complain about it).
3285 const FunctionProtoType *FromFunctionType
3286 = FromPointeeType->getAs<FunctionProtoType>();
3287 const FunctionProtoType *ToFunctionType
3288 = ToPointeeType->getAs<FunctionProtoType>();
3289 if (FromFunctionType && ToFunctionType) {
3290 // If the function types are exactly the same, this isn't an
3291 // Objective-C pointer conversion.
3292 if (Context.getCanonicalType(FromPointeeType)
3293 == Context.getCanonicalType(ToPointeeType))
3294 return false;
3295
3296 // Perform the quick checks that will tell us whether these
3297 // function types are obviously different.
3298 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3299 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3300 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3301 return false;
3302
3303 bool HasObjCConversion = false;
3304 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3305 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3306 // Okay, the types match exactly. Nothing to do.
3307 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3308 ToFunctionType->getReturnType(),
3309 ConvertedType, IncompatibleObjC)) {
3310 // Okay, we have an Objective-C pointer conversion.
3311 HasObjCConversion = true;
3312 } else {
3313 // Function types are too different. Abort.
3314 return false;
3315 }
3316
3317 // Check argument types.
3318 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3319 ArgIdx != NumArgs; ++ArgIdx) {
3320 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3321 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3322 if (Context.getCanonicalType(FromArgType)
3323 == Context.getCanonicalType(ToArgType)) {
3324 // Okay, the types match exactly. Nothing to do.
3325 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3326 ConvertedType, IncompatibleObjC)) {
3327 // Okay, we have an Objective-C pointer conversion.
3328 HasObjCConversion = true;
3329 } else {
3330 // Argument types are too different. Abort.
3331 return false;
3332 }
3333 }
3334
3335 if (HasObjCConversion) {
3336 // We had an Objective-C conversion. Allow this pointer
3337 // conversion, but complain about it.
3338 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3339 IncompatibleObjC = true;
3340 return true;
3341 }
3342 }
3343
3344 return false;
3345}
3346
3348 QualType& ConvertedType) {
3349 QualType ToPointeeType;
3350 if (const BlockPointerType *ToBlockPtr =
3351 ToType->getAs<BlockPointerType>())
3352 ToPointeeType = ToBlockPtr->getPointeeType();
3353 else
3354 return false;
3355
3356 QualType FromPointeeType;
3357 if (const BlockPointerType *FromBlockPtr =
3358 FromType->getAs<BlockPointerType>())
3359 FromPointeeType = FromBlockPtr->getPointeeType();
3360 else
3361 return false;
3362 // We have pointer to blocks, check whether the only
3363 // differences in the argument and result types are in Objective-C
3364 // pointer conversions. If so, we permit the conversion.
3365
3366 const FunctionProtoType *FromFunctionType
3367 = FromPointeeType->getAs<FunctionProtoType>();
3368 const FunctionProtoType *ToFunctionType
3369 = ToPointeeType->getAs<FunctionProtoType>();
3370
3371 if (!FromFunctionType || !ToFunctionType)
3372 return false;
3373
3374 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3375 return true;
3376
3377 // Perform the quick checks that will tell us whether these
3378 // function types are obviously different.
3379 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3380 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3381 return false;
3382
3383 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3384 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3385 if (FromEInfo != ToEInfo)
3386 return false;
3387
3388 bool IncompatibleObjC = false;
3389 if (Context.hasSameType(FromFunctionType->getReturnType(),
3390 ToFunctionType->getReturnType())) {
3391 // Okay, the types match exactly. Nothing to do.
3392 } else {
3393 QualType RHS = FromFunctionType->getReturnType();
3394 QualType LHS = ToFunctionType->getReturnType();
3395 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3396 !RHS.hasQualifiers() && LHS.hasQualifiers())
3397 LHS = LHS.getUnqualifiedType();
3398
3399 if (Context.hasSameType(RHS,LHS)) {
3400 // OK exact match.
3401 } else if (isObjCPointerConversion(RHS, LHS,
3402 ConvertedType, IncompatibleObjC)) {
3403 if (IncompatibleObjC)
3404 return false;
3405 // Okay, we have an Objective-C pointer conversion.
3406 }
3407 else
3408 return false;
3409 }
3410
3411 // Check argument types.
3412 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3413 ArgIdx != NumArgs; ++ArgIdx) {
3414 IncompatibleObjC = false;
3415 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3416 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3417 if (Context.hasSameType(FromArgType, ToArgType)) {
3418 // Okay, the types match exactly. Nothing to do.
3419 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3420 ConvertedType, IncompatibleObjC)) {
3421 if (IncompatibleObjC)
3422 return false;
3423 // Okay, we have an Objective-C pointer conversion.
3424 } else
3425 // Argument types are too different. Abort.
3426 return false;
3427 }
3428
3430 bool CanUseToFPT, CanUseFromFPT;
3431 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3432 CanUseToFPT, CanUseFromFPT,
3433 NewParamInfos))
3434 return false;
3435
3436 ConvertedType = ToType;
3437 return true;
3438}
3439
3440enum {
3448};
3449
3450/// Attempts to get the FunctionProtoType from a Type. Handles
3451/// MemberFunctionPointers properly.
3453 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3454 return FPT;
3455
3456 if (auto *MPT = FromType->getAs<MemberPointerType>())
3457 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3458
3459 return nullptr;
3460}
3461
3463 QualType FromType, QualType ToType) {
3464 // If either type is not valid, include no extra info.
3465 if (FromType.isNull() || ToType.isNull()) {
3466 PDiag << ft_default;
3467 return;
3468 }
3469
3470 // Get the function type from the pointers.
3471 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3472 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3473 *ToMember = ToType->castAs<MemberPointerType>();
3474 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3475 ToMember->getMostRecentCXXRecordDecl())) {
3477 if (ToMember->isSugared())
3478 PDiag << Context.getCanonicalTagType(
3479 ToMember->getMostRecentCXXRecordDecl());
3480 else
3481 PDiag << ToMember->getQualifier();
3482 if (FromMember->isSugared())
3483 PDiag << Context.getCanonicalTagType(
3484 FromMember->getMostRecentCXXRecordDecl());
3485 else
3486 PDiag << FromMember->getQualifier();
3487 return;
3488 }
3489 FromType = FromMember->getPointeeType();
3490 ToType = ToMember->getPointeeType();
3491 }
3492
3493 if (FromType->isPointerType())
3494 FromType = FromType->getPointeeType();
3495 if (ToType->isPointerType())
3496 ToType = ToType->getPointeeType();
3497
3498 // Remove references.
3499 FromType = FromType.getNonReferenceType();
3500 ToType = ToType.getNonReferenceType();
3501
3502 // Don't print extra info for non-specialized template functions.
3503 if (FromType->isInstantiationDependentType() &&
3504 !FromType->getAs<TemplateSpecializationType>()) {
3505 PDiag << ft_default;
3506 return;
3507 }
3508
3509 // No extra info for same types.
3510 if (Context.hasSameType(FromType, ToType)) {
3511 PDiag << ft_default;
3512 return;
3513 }
3514
3515 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3516 *ToFunction = tryGetFunctionProtoType(ToType);
3517
3518 // Both types need to be function types.
3519 if (!FromFunction || !ToFunction) {
3520 PDiag << ft_default;
3521 return;
3522 }
3523
3524 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3525 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3526 << FromFunction->getNumParams();
3527 return;
3528 }
3529
3530 // Handle different parameter types.
3531 unsigned ArgPos;
3532 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3533 PDiag << ft_parameter_mismatch << ArgPos + 1
3534 << ToFunction->getParamType(ArgPos)
3535 << FromFunction->getParamType(ArgPos);
3536 return;
3537 }
3538
3539 // Handle different return type.
3540 if (!Context.hasSameType(FromFunction->getReturnType(),
3541 ToFunction->getReturnType())) {
3542 PDiag << ft_return_type << ToFunction->getReturnType()
3543 << FromFunction->getReturnType();
3544 return;
3545 }
3546
3547 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3548 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3549 << FromFunction->getMethodQuals();
3550 return;
3551 }
3552
3553 // Handle exception specification differences on canonical type (in C++17
3554 // onwards).
3556 ->isNothrow() !=
3557 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3558 ->isNothrow()) {
3559 PDiag << ft_noexcept;
3560 return;
3561 }
3562
3563 // Unable to find a difference, so add no extra info.
3564 PDiag << ft_default;
3565}
3566
3568 ArrayRef<QualType> New, unsigned *ArgPos,
3569 bool Reversed) {
3570 assert(llvm::size(Old) == llvm::size(New) &&
3571 "Can't compare parameters of functions with different number of "
3572 "parameters!");
3573
3574 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3575 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3576 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3577
3578 // Ignore address spaces in pointee type. This is to disallow overloading
3579 // on __ptr32/__ptr64 address spaces.
3580 QualType OldType =
3581 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3582 QualType NewType =
3583 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3584
3585 if (!Context.hasSameType(OldType, NewType)) {
3586 if (ArgPos)
3587 *ArgPos = Idx;
3588 return false;
3589 }
3590 }
3591 return true;
3592}
3593
3595 const FunctionProtoType *NewType,
3596 unsigned *ArgPos, bool Reversed) {
3597 return FunctionParamTypesAreEqual(OldType->param_types(),
3598 NewType->param_types(), ArgPos, Reversed);
3599}
3600
3602 const FunctionDecl *NewFunction,
3603 unsigned *ArgPos,
3604 bool Reversed) {
3605
3606 if (OldFunction->getNumNonObjectParams() !=
3607 NewFunction->getNumNonObjectParams())
3608 return false;
3609
3610 unsigned OldIgnore =
3612 unsigned NewIgnore =
3614
3615 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3616 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3617
3618 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3619 NewPT->param_types().slice(NewIgnore),
3620 ArgPos, Reversed);
3621}
3622
3624 CastKind &Kind,
3625 CXXCastPath& BasePath,
3626 bool IgnoreBaseAccess,
3627 bool Diagnose) {
3628 QualType FromType = From->getType();
3629 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3630
3631 Kind = CK_BitCast;
3632
3633 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3636 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3637 DiagRuntimeBehavior(From->getExprLoc(), From,
3638 PDiag(diag::warn_impcast_bool_to_null_pointer)
3639 << ToType << From->getSourceRange());
3640 else if (!isUnevaluatedContext())
3641 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3642 << ToType << From->getSourceRange();
3643 }
3644 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3645 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3646 QualType FromPointeeType = FromPtrType->getPointeeType(),
3647 ToPointeeType = ToPtrType->getPointeeType();
3648
3649 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3650 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3651 // We must have a derived-to-base conversion. Check an
3652 // ambiguous or inaccessible conversion.
3653 unsigned InaccessibleID = 0;
3654 unsigned AmbiguousID = 0;
3655 if (Diagnose) {
3656 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3657 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3658 }
3660 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3661 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3662 &BasePath, IgnoreBaseAccess))
3663 return true;
3664
3665 // The conversion was successful.
3666 Kind = CK_DerivedToBase;
3667 }
3668
3669 if (Diagnose && !IsCStyleOrFunctionalCast &&
3670 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3671 assert(getLangOpts().MSVCCompat &&
3672 "this should only be possible with MSVCCompat!");
3673 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3674 << From->getSourceRange();
3675 }
3676 }
3677 } else if (const ObjCObjectPointerType *ToPtrType =
3678 ToType->getAs<ObjCObjectPointerType>()) {
3679 if (const ObjCObjectPointerType *FromPtrType =
3680 FromType->getAs<ObjCObjectPointerType>()) {
3681 // Objective-C++ conversions are always okay.
3682 // FIXME: We should have a different class of conversions for the
3683 // Objective-C++ implicit conversions.
3684 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3685 return false;
3686 } else if (FromType->isBlockPointerType()) {
3687 Kind = CK_BlockPointerToObjCPointerCast;
3688 } else {
3689 Kind = CK_CPointerToObjCPointerCast;
3690 }
3691 } else if (ToType->isBlockPointerType()) {
3692 if (!FromType->isBlockPointerType())
3693 Kind = CK_AnyPointerToBlockPointerCast;
3694 }
3695
3696 // We shouldn't fall into this case unless it's valid for other
3697 // reasons.
3699 Kind = CK_NullToPointer;
3700
3701 return false;
3702}
3703
3705 QualType ToType,
3706 bool InOverloadResolution,
3707 QualType &ConvertedType) {
3708 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3709 if (!ToTypePtr)
3710 return false;
3711
3712 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3714 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3716 ConvertedType = ToType;
3717 return true;
3718 }
3719
3720 // Otherwise, both types have to be member pointers.
3721 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3722 if (!FromTypePtr)
3723 return false;
3724
3725 // A pointer to member of B can be converted to a pointer to member of D,
3726 // where D is derived from B (C++ 4.11p2).
3727 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3728 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3729
3730 if (!declaresSameEntity(FromClass, ToClass) &&
3731 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3732 ConvertedType = Context.getMemberPointerType(
3733 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3734 return true;
3735 }
3736
3737 return false;
3738}
3739
3741 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3742 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3743 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3744 // Lock down the inheritance model right now in MS ABI, whether or not the
3745 // pointee types are the same.
3746 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3747 (void)isCompleteType(CheckLoc, FromType);
3748 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3749 }
3750
3751 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3752 if (!FromPtrType) {
3753 // This must be a null pointer to member pointer conversion
3754 Kind = CK_NullToMemberPointer;
3756 }
3757
3758 // T == T, modulo cv
3760 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3761 ToPtrType->getPointeeType()))
3763
3764 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3765 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3766
3767 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3768 const CXXRecordDecl *Cls) {
3769 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3770 PD << Qual;
3771 else
3772 PD << Context.getCanonicalTagType(Cls);
3773 };
3774 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3775 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3776 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3777 return PD;
3778 };
3779
3780 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3782 std::swap(Base, Derived);
3783
3784 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3785 /*DetectVirtual=*/true);
3786 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3788
3789 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3790 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3791 PD << int(Direction);
3792 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3793 Diag(CheckLoc, PD);
3795 }
3796
3797 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3798 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3799 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3800 Diag(CheckLoc, PD);
3802 }
3803
3804 // Must be a base to derived member conversion.
3805 BuildBasePathArray(Paths, BasePath);
3807 ? CK_DerivedToBaseMemberPointer
3808 : CK_BaseToDerivedMemberPointer;
3809
3810 if (!IgnoreBaseAccess)
3811 switch (CheckBaseClassAccess(
3812 CheckLoc, Base, Derived, Paths.front(),
3814 ? diag::err_upcast_to_inaccessible_base
3815 : diag::err_downcast_from_inaccessible_base,
3816 [&](PartialDiagnostic &PD) {
3817 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3818 DerivedQual = ToPtrType->getQualifier();
3819 if (Direction == MemberPointerConversionDirection::Upcast)
3820 std::swap(BaseQual, DerivedQual);
3821 DiagCls(PD, DerivedQual, Derived);
3822 DiagCls(PD, BaseQual, Base);
3823 })) {
3825 case Sema::AR_delayed:
3826 case Sema::AR_dependent:
3827 // Optimistically assume that the delayed and dependent cases
3828 // will work out.
3829 break;
3830
3833 }
3834
3836}
3837
3838/// Determine whether the lifetime conversion between the two given
3839/// qualifiers sets is nontrivial.
3841 Qualifiers ToQuals) {
3842 // Converting anything to const __unsafe_unretained is trivial.
3843 if (ToQuals.hasConst() &&
3845 return false;
3846
3847 return true;
3848}
3849
3850/// Perform a single iteration of the loop for checking if a qualification
3851/// conversion is valid.
3852///
3853/// Specifically, check whether any change between the qualifiers of \p
3854/// FromType and \p ToType is permissible, given knowledge about whether every
3855/// outer layer is const-qualified.
3857 bool CStyle, bool IsTopLevel,
3858 bool &PreviousToQualsIncludeConst,
3859 bool &ObjCLifetimeConversion,
3860 const ASTContext &Ctx) {
3861 Qualifiers FromQuals = FromType.getQualifiers();
3862 Qualifiers ToQuals = ToType.getQualifiers();
3863
3864 // Ignore __unaligned qualifier.
3865 FromQuals.removeUnaligned();
3866
3867 // Objective-C ARC:
3868 // Check Objective-C lifetime conversions.
3869 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3870 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3871 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3872 ObjCLifetimeConversion = true;
3873 FromQuals.removeObjCLifetime();
3874 ToQuals.removeObjCLifetime();
3875 } else {
3876 // Qualification conversions cannot cast between different
3877 // Objective-C lifetime qualifiers.
3878 return false;
3879 }
3880 }
3881
3882 // Allow addition/removal of GC attributes but not changing GC attributes.
3883 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3884 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3885 FromQuals.removeObjCGCAttr();
3886 ToQuals.removeObjCGCAttr();
3887 }
3888
3889 // __ptrauth qualifiers must match exactly.
3890 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3891 return false;
3892
3893 // -- for every j > 0, if const is in cv 1,j then const is in cv
3894 // 2,j, and similarly for volatile.
3895 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3896 return false;
3897
3898 // If address spaces mismatch:
3899 // - in top level it is only valid to convert to addr space that is a
3900 // superset in all cases apart from C-style casts where we allow
3901 // conversions between overlapping address spaces.
3902 // - in non-top levels it is not a valid conversion.
3903 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3904 (!IsTopLevel ||
3905 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3906 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3907 return false;
3908
3909 // -- if the cv 1,j and cv 2,j are different, then const is in
3910 // every cv for 0 < k < j.
3911 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3912 !PreviousToQualsIncludeConst)
3913 return false;
3914
3915 // The following wording is from C++20, where the result of the conversion
3916 // is T3, not T2.
3917 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3918 // "array of unknown bound of"
3919 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3920 return false;
3921
3922 // -- if the resulting P3,i is different from P1,i [...], then const is
3923 // added to every cv 3_k for 0 < k < i.
3924 if (!CStyle && FromType->isConstantArrayType() &&
3925 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3926 return false;
3927
3928 // Keep track of whether all prior cv-qualifiers in the "to" type
3929 // include const.
3930 PreviousToQualsIncludeConst =
3931 PreviousToQualsIncludeConst && ToQuals.hasConst();
3932 return true;
3933}
3934
3935bool
3937 bool CStyle, bool &ObjCLifetimeConversion) {
3938 FromType = Context.getCanonicalType(FromType);
3939 ToType = Context.getCanonicalType(ToType);
3940 ObjCLifetimeConversion = false;
3941
3942 // If FromType and ToType are the same type, this is not a
3943 // qualification conversion.
3944 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3945 return false;
3946
3947 // (C++ 4.4p4):
3948 // A conversion can add cv-qualifiers at levels other than the first
3949 // in multi-level pointers, subject to the following rules: [...]
3950 bool PreviousToQualsIncludeConst = true;
3951 bool UnwrappedAnyPointer = false;
3952 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3953 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3954 !UnwrappedAnyPointer,
3955 PreviousToQualsIncludeConst,
3956 ObjCLifetimeConversion, getASTContext()))
3957 return false;
3958 UnwrappedAnyPointer = true;
3959 }
3960
3961 // We are left with FromType and ToType being the pointee types
3962 // after unwrapping the original FromType and ToType the same number
3963 // of times. If we unwrapped any pointers, and if FromType and
3964 // ToType have the same unqualified type (since we checked
3965 // qualifiers above), then this is a qualification conversion.
3966 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3967}
3968
3969/// - Determine whether this is a conversion from a scalar type to an
3970/// atomic type.
3971///
3972/// If successful, updates \c SCS's second and third steps in the conversion
3973/// sequence to finish the conversion.
3974static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3975 bool InOverloadResolution,
3977 bool CStyle) {
3978 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3979 if (!ToAtomic)
3980 return false;
3981
3983 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3984 InOverloadResolution, InnerSCS,
3985 CStyle, /*AllowObjCWritebackConversion=*/false))
3986 return false;
3987
3988 SCS.Second = InnerSCS.Second;
3989 SCS.setToType(1, InnerSCS.getToType(1));
3990 SCS.Third = InnerSCS.Third;
3993 SCS.setToType(2, InnerSCS.getToType(2));
3994 return true;
3995}
3996
3998 QualType ToType,
3999 bool InOverloadResolution,
4001 bool CStyle) {
4002 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4003 if (!ToOBT)
4004 return false;
4005
4006 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4007 QualType FromType = From->getType();
4008 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4009 return false;
4010
4012 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4013 InOverloadResolution, InnerSCS, CStyle,
4014 /*AllowObjCWritebackConversion=*/false))
4015 return false;
4016
4017 SCS.Second = InnerSCS.Second;
4018 SCS.setToType(1, InnerSCS.getToType(1));
4019 SCS.Third = InnerSCS.Third;
4022 SCS.setToType(2, InnerSCS.getToType(2));
4023 return true;
4024}
4025
4028 QualType Type) {
4029 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4030 if (CtorType->getNumParams() > 0) {
4031 QualType FirstArg = CtorType->getParamType(0);
4032 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4033 return true;
4034 }
4035 return false;
4036}
4037
4038static OverloadingResult
4040 CXXRecordDecl *To,
4042 OverloadCandidateSet &CandidateSet,
4043 bool AllowExplicit) {
4045 for (auto *D : S.LookupConstructors(To)) {
4046 auto Info = getConstructorInfo(D);
4047 if (!Info)
4048 continue;
4049
4050 bool Usable = !Info.Constructor->isInvalidDecl() &&
4051 S.isInitListConstructor(Info.Constructor);
4052 if (Usable) {
4053 bool SuppressUserConversions = false;
4054 if (Info.ConstructorTmpl)
4055 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4056 /*ExplicitArgs*/ nullptr, From,
4057 CandidateSet, SuppressUserConversions,
4058 /*PartialOverloading*/ false,
4059 AllowExplicit);
4060 else
4061 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4062 CandidateSet, SuppressUserConversions,
4063 /*PartialOverloading*/ false, AllowExplicit);
4064 }
4065 }
4066
4067 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4068
4070 switch (auto Result =
4071 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4072 case OR_Deleted:
4073 case OR_Success: {
4074 // Record the standard conversion we used and the conversion function.
4076 QualType ThisType = Constructor->getFunctionObjectParameterType();
4077 // Initializer lists don't have conversions as such.
4079 User.HadMultipleCandidates = HadMultipleCandidates;
4081 User.FoundConversionFunction = Best->FoundDecl;
4083 User.After.setFromType(ThisType);
4084 User.After.setAllToTypes(ToType);
4085 return Result;
4086 }
4087
4089 return OR_No_Viable_Function;
4090 case OR_Ambiguous:
4091 return OR_Ambiguous;
4092 }
4093
4094 llvm_unreachable("Invalid OverloadResult!");
4095}
4096
4097/// Determines whether there is a user-defined conversion sequence
4098/// (C++ [over.ics.user]) that converts expression From to the type
4099/// ToType. If such a conversion exists, User will contain the
4100/// user-defined conversion sequence that performs such a conversion
4101/// and this routine will return true. Otherwise, this routine returns
4102/// false and User is unspecified.
4103///
4104/// \param AllowExplicit true if the conversion should consider C++0x
4105/// "explicit" conversion functions as well as non-explicit conversion
4106/// functions (C++0x [class.conv.fct]p2).
4107///
4108/// \param AllowObjCConversionOnExplicit true if the conversion should
4109/// allow an extra Objective-C pointer conversion on uses of explicit
4110/// constructors. Requires \c AllowExplicit to also be set.
4111static OverloadingResult
4114 OverloadCandidateSet &CandidateSet,
4115 AllowedExplicit AllowExplicit,
4116 bool AllowObjCConversionOnExplicit) {
4117 assert(AllowExplicit != AllowedExplicit::None ||
4118 !AllowObjCConversionOnExplicit);
4120
4121 // Whether we will only visit constructors.
4122 bool ConstructorsOnly = false;
4123
4124 // If the type we are conversion to is a class type, enumerate its
4125 // constructors.
4126 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4127 // C++ [over.match.ctor]p1:
4128 // When objects of class type are direct-initialized (8.5), or
4129 // copy-initialized from an expression of the same or a
4130 // derived class type (8.5), overload resolution selects the
4131 // constructor. [...] For copy-initialization, the candidate
4132 // functions are all the converting constructors (12.3.1) of
4133 // that class. The argument list is the expression-list within
4134 // the parentheses of the initializer.
4135 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4136 (From->getType()->isRecordType() &&
4137 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4138 ConstructorsOnly = true;
4139
4140 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4141 // We're not going to find any constructors.
4142 } else if (auto *ToRecordDecl =
4143 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4144 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4145
4146 Expr **Args = &From;
4147 unsigned NumArgs = 1;
4148 bool ListInitializing = false;
4149 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4150 // But first, see if there is an init-list-constructor that will work.
4152 S, From, ToType, ToRecordDecl, User, CandidateSet,
4153 AllowExplicit == AllowedExplicit::All);
4154 if (Result != OR_No_Viable_Function)
4155 return Result;
4156 // Never mind.
4157 CandidateSet.clear(
4159
4160 // If we're list-initializing, we pass the individual elements as
4161 // arguments, not the entire list.
4162 Args = InitList->getInits();
4163 NumArgs = InitList->getNumInits();
4164 ListInitializing = true;
4165 }
4166
4167 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4168 auto Info = getConstructorInfo(D);
4169 if (!Info)
4170 continue;
4171
4172 bool Usable = !Info.Constructor->isInvalidDecl();
4173 if (!ListInitializing)
4174 Usable = Usable && Info.Constructor->isConvertingConstructor(
4175 /*AllowExplicit*/ true);
4176 if (Usable) {
4177 bool SuppressUserConversions = !ConstructorsOnly;
4178 // C++20 [over.best.ics.general]/4.5:
4179 // if the target is the first parameter of a constructor [of class
4180 // X] and the constructor [...] is a candidate by [...] the second
4181 // phase of [over.match.list] when the initializer list has exactly
4182 // one element that is itself an initializer list, [...] and the
4183 // conversion is to X or reference to cv X, user-defined conversion
4184 // sequences are not considered.
4185 if (SuppressUserConversions && ListInitializing) {
4186 SuppressUserConversions =
4187 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4188 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4189 ToType);
4190 }
4191 if (Info.ConstructorTmpl)
4193 Info.ConstructorTmpl, Info.FoundDecl,
4194 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4195 CandidateSet, SuppressUserConversions,
4196 /*PartialOverloading*/ false,
4197 AllowExplicit == AllowedExplicit::All);
4198 else
4199 // Allow one user-defined conversion when user specifies a
4200 // From->ToType conversion via an static cast (c-style, etc).
4201 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4202 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4203 SuppressUserConversions,
4204 /*PartialOverloading*/ false,
4205 AllowExplicit == AllowedExplicit::All);
4206 }
4207 }
4208 }
4209 }
4210
4211 // Enumerate conversion functions, if we're allowed to.
4212 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4213 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4214 // No conversion functions from incomplete types.
4215 } else if (const RecordType *FromRecordType =
4216 From->getType()->getAsCanonical<RecordType>()) {
4217 if (auto *FromRecordDecl =
4218 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4219 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4220 // Add all of the conversion functions as candidates.
4221 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4222 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4223 DeclAccessPair FoundDecl = I.getPair();
4224 NamedDecl *D = FoundDecl.getDecl();
4225 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4226 if (isa<UsingShadowDecl>(D))
4227 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4228
4229 CXXConversionDecl *Conv;
4230 FunctionTemplateDecl *ConvTemplate;
4231 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4232 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4233 else
4234 Conv = cast<CXXConversionDecl>(D);
4235
4236 if (ConvTemplate)
4238 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4239 CandidateSet, AllowObjCConversionOnExplicit,
4240 AllowExplicit != AllowedExplicit::None);
4241 else
4242 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4243 CandidateSet, AllowObjCConversionOnExplicit,
4244 AllowExplicit != AllowedExplicit::None);
4245 }
4246 }
4247 }
4248
4249 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4250
4252 switch (auto Result =
4253 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4254 case OR_Success:
4255 case OR_Deleted:
4256 // Record the standard conversion we used and the conversion function.
4258 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4259 // C++ [over.ics.user]p1:
4260 // If the user-defined conversion is specified by a
4261 // constructor (12.3.1), the initial standard conversion
4262 // sequence converts the source type to the type required by
4263 // the argument of the constructor.
4264 //
4265 if (isa<InitListExpr>(From)) {
4266 // Initializer lists don't have conversions as such.
4268 User.Before.FromBracedInitList = true;
4269 } else {
4270 if (Best->Conversions[0].isEllipsis())
4271 User.EllipsisConversion = true;
4272 else {
4273 User.Before = Best->Conversions[0].Standard;
4274 User.EllipsisConversion = false;
4275 }
4276 }
4277 User.HadMultipleCandidates = HadMultipleCandidates;
4279 User.FoundConversionFunction = Best->FoundDecl;
4281 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4282 User.After.setAllToTypes(ToType);
4283 return Result;
4284 }
4285 if (CXXConversionDecl *Conversion
4286 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4287
4288 assert(Best->HasFinalConversion);
4289
4290 // C++ [over.ics.user]p1:
4291 //
4292 // [...] If the user-defined conversion is specified by a
4293 // conversion function (12.3.2), the initial standard
4294 // conversion sequence converts the source type to the
4295 // implicit object parameter of the conversion function.
4296 User.Before = Best->Conversions[0].Standard;
4297 User.HadMultipleCandidates = HadMultipleCandidates;
4298 User.ConversionFunction = Conversion;
4299 User.FoundConversionFunction = Best->FoundDecl;
4300 User.EllipsisConversion = false;
4301
4302 // C++ [over.ics.user]p2:
4303 // The second standard conversion sequence converts the
4304 // result of the user-defined conversion to the target type
4305 // for the sequence. Since an implicit conversion sequence
4306 // is an initialization, the special rules for
4307 // initialization by user-defined conversion apply when
4308 // selecting the best user-defined conversion for a
4309 // user-defined conversion sequence (see 13.3.3 and
4310 // 13.3.3.1).
4311 User.After = Best->FinalConversion;
4312 return Result;
4313 }
4314 llvm_unreachable("Not a constructor or conversion function?");
4315
4317 return OR_No_Viable_Function;
4318
4319 case OR_Ambiguous:
4320 return OR_Ambiguous;
4321 }
4322
4323 llvm_unreachable("Invalid OverloadResult!");
4324}
4325
4326bool
4329 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4331 OverloadingResult OvResult =
4332 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4333 CandidateSet, AllowedExplicit::None, false);
4334
4335 if (!(OvResult == OR_Ambiguous ||
4336 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4337 return false;
4338
4339 auto Cands = CandidateSet.CompleteCandidates(
4340 *this,
4342 From);
4343 if (OvResult == OR_Ambiguous)
4344 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4345 << From->getType() << ToType << From->getSourceRange();
4346 else { // OR_No_Viable_Function && !CandidateSet.empty()
4347 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4348 diag::err_typecheck_nonviable_condition_incomplete,
4349 From->getType(), From->getSourceRange()))
4350 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4351 << false << From->getType() << From->getSourceRange() << ToType;
4352 }
4353
4354 CandidateSet.NoteCandidates(
4355 *this, From, Cands);
4356 return true;
4357}
4358
4359// Helper for compareConversionFunctions that gets the FunctionType that the
4360// conversion-operator return value 'points' to, or nullptr.
4361static const FunctionType *
4363 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4364 const PointerType *RetPtrTy =
4365 ConvFuncTy->getReturnType()->getAs<PointerType>();
4366
4367 if (!RetPtrTy)
4368 return nullptr;
4369
4370 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4371}
4372
4373/// Compare the user-defined conversion functions or constructors
4374/// of two user-defined conversion sequences to determine whether any ordering
4375/// is possible.
4378 FunctionDecl *Function2) {
4379 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4380 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4381 if (!Conv1 || !Conv2)
4383
4384 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4386
4387 // Objective-C++:
4388 // If both conversion functions are implicitly-declared conversions from
4389 // a lambda closure type to a function pointer and a block pointer,
4390 // respectively, always prefer the conversion to a function pointer,
4391 // because the function pointer is more lightweight and is more likely
4392 // to keep code working.
4393 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4394 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4395 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4396 if (Block1 != Block2)
4397 return Block1 ? ImplicitConversionSequence::Worse
4399 }
4400
4401 // In order to support multiple calling conventions for the lambda conversion
4402 // operator (such as when the free and member function calling convention is
4403 // different), prefer the 'free' mechanism, followed by the calling-convention
4404 // of operator(). The latter is in place to support the MSVC-like solution of
4405 // defining ALL of the possible conversions in regards to calling-convention.
4406 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4407 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4408
4409 if (Conv1FuncRet && Conv2FuncRet &&
4410 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4411 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4412 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4413
4414 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4415 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4416
4417 CallingConv CallOpCC =
4418 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4420 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4422 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4423
4424 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4425 for (CallingConv CC : PrefOrder) {
4426 if (Conv1CC == CC)
4428 if (Conv2CC == CC)
4430 }
4431 }
4432
4434}
4435
4442
4443/// CompareImplicitConversionSequences - Compare two implicit
4444/// conversion sequences to determine whether one is better than the
4445/// other or if they are indistinguishable (C++ 13.3.3.2).
4448 const ImplicitConversionSequence& ICS1,
4449 const ImplicitConversionSequence& ICS2)
4450{
4451 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4452 // conversion sequences (as defined in 13.3.3.1)
4453 // -- a standard conversion sequence (13.3.3.1.1) is a better
4454 // conversion sequence than a user-defined conversion sequence or
4455 // an ellipsis conversion sequence, and
4456 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4457 // conversion sequence than an ellipsis conversion sequence
4458 // (13.3.3.1.3).
4459 //
4460 // C++0x [over.best.ics]p10:
4461 // For the purpose of ranking implicit conversion sequences as
4462 // described in 13.3.3.2, the ambiguous conversion sequence is
4463 // treated as a user-defined sequence that is indistinguishable
4464 // from any other user-defined conversion sequence.
4465
4466 // String literal to 'char *' conversion has been deprecated in C++03. It has
4467 // been removed from C++11. We still accept this conversion, if it happens at
4468 // the best viable function. Otherwise, this conversion is considered worse
4469 // than ellipsis conversion. Consider this as an extension; this is not in the
4470 // standard. For example:
4471 //
4472 // int &f(...); // #1
4473 // void f(char*); // #2
4474 // void g() { int &r = f("foo"); }
4475 //
4476 // In C++03, we pick #2 as the best viable function.
4477 // In C++11, we pick #1 as the best viable function, because ellipsis
4478 // conversion is better than string-literal to char* conversion (since there
4479 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4480 // convert arguments, #2 would be the best viable function in C++11.
4481 // If the best viable function has this conversion, a warning will be issued
4482 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4483
4484 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4487 // Ill-formedness must not differ
4488 ICS1.isBad() == ICS2.isBad())
4492
4493 if (ICS1.getKindRank() < ICS2.getKindRank())
4495 if (ICS2.getKindRank() < ICS1.getKindRank())
4497
4498 // The following checks require both conversion sequences to be of
4499 // the same kind.
4500 if (ICS1.getKind() != ICS2.getKind())
4502
4505
4506 // Two implicit conversion sequences of the same form are
4507 // indistinguishable conversion sequences unless one of the
4508 // following rules apply: (C++ 13.3.3.2p3):
4509
4510 // List-initialization sequence L1 is a better conversion sequence than
4511 // list-initialization sequence L2 if:
4512 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4513 // if not that,
4514 // — L1 and L2 convert to arrays of the same element type, and either the
4515 // number of elements n_1 initialized by L1 is less than the number of
4516 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4517 // an array of unknown bound and L1 does not,
4518 // even if one of the other rules in this paragraph would otherwise apply.
4519 if (!ICS1.isBad()) {
4520 bool StdInit1 = false, StdInit2 = false;
4523 nullptr);
4526 nullptr);
4527 if (StdInit1 != StdInit2)
4528 return StdInit1 ? ImplicitConversionSequence::Better
4530
4533 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4535 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4537 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4538 CAT2->getElementType())) {
4539 // Both to arrays of the same element type
4540 if (CAT1->getSize() != CAT2->getSize())
4541 // Different sized, the smaller wins
4542 return CAT1->getSize().ult(CAT2->getSize())
4547 // One is incomplete, it loses
4551 }
4552 }
4553 }
4554
4555 if (ICS1.isStandard())
4556 // Standard conversion sequence S1 is a better conversion sequence than
4557 // standard conversion sequence S2 if [...]
4558 Result = CompareStandardConversionSequences(S, Loc,
4559 ICS1.Standard, ICS2.Standard);
4560 else if (ICS1.isUserDefined()) {
4561 // With lazy template loading, it is possible to find non-canonical
4562 // FunctionDecls, depending on when redecl chains are completed. Make sure
4563 // to compare the canonical decls of conversion functions. This avoids
4564 // ambiguity problems for templated conversion operators.
4565 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4566 if (ConvFunc1)
4567 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4568 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4569 if (ConvFunc2)
4570 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4571 // User-defined conversion sequence U1 is a better conversion
4572 // sequence than another user-defined conversion sequence U2 if
4573 // they contain the same user-defined conversion function or
4574 // constructor and if the second standard conversion sequence of
4575 // U1 is better than the second standard conversion sequence of
4576 // U2 (C++ 13.3.3.2p3).
4577 if (ConvFunc1 == ConvFunc2)
4578 Result = CompareStandardConversionSequences(S, Loc,
4579 ICS1.UserDefined.After,
4580 ICS2.UserDefined.After);
4581 else
4582 Result = compareConversionFunctions(S,
4585 }
4586
4587 return Result;
4588}
4589
4590// Per 13.3.3.2p3, compare the given standard conversion sequences to
4591// determine if one is a proper subset of the other.
4594 const StandardConversionSequence& SCS1,
4595 const StandardConversionSequence& SCS2) {
4598
4599 // the identity conversion sequence is considered to be a subsequence of
4600 // any non-identity conversion sequence
4601 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4603 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4605
4606 if (SCS1.Second != SCS2.Second) {
4607 if (SCS1.Second == ICK_Identity)
4609 else if (SCS2.Second == ICK_Identity)
4611 else
4613 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4615
4616 if (SCS1.Third == SCS2.Third) {
4617 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4619 }
4620
4621 if (SCS1.Third == ICK_Identity)
4622 return Result == ImplicitConversionSequence::Worse
4625
4626 if (SCS2.Third == ICK_Identity)
4627 return Result == ImplicitConversionSequence::Better
4630
4632}
4633
4634/// Determine whether one of the given reference bindings is better
4635/// than the other based on what kind of bindings they are.
4636static bool
4638 const StandardConversionSequence &SCS2) {
4639 // C++0x [over.ics.rank]p3b4:
4640 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4641 // implicit object parameter of a non-static member function declared
4642 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4643 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4644 // lvalue reference to a function lvalue and S2 binds an rvalue
4645 // reference*.
4646 //
4647 // FIXME: Rvalue references. We're going rogue with the above edits,
4648 // because the semantics in the current C++0x working paper (N3225 at the
4649 // time of this writing) break the standard definition of std::forward
4650 // and std::reference_wrapper when dealing with references to functions.
4651 // Proposed wording changes submitted to CWG for consideration.
4654 return false;
4655
4656 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4657 SCS2.IsLvalueReference) ||
4660}
4661
4667
4668/// Returns kind of fixed enum promotion the \a SCS uses.
4669static FixedEnumPromotion
4671
4672 if (SCS.Second != ICK_Integral_Promotion)
4674
4675 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4676 if (!Enum)
4678
4679 if (!Enum->isFixed())
4681
4682 QualType UnderlyingType = Enum->getIntegerType();
4683 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4685
4687}
4688
4689/// CompareStandardConversionSequences - Compare two standard
4690/// conversion sequences to determine whether one is better than the
4691/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4694 const StandardConversionSequence& SCS1,
4695 const StandardConversionSequence& SCS2)
4696{
4697 // Standard conversion sequence S1 is a better conversion sequence
4698 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4699
4700 // -- S1 is a proper subsequence of S2 (comparing the conversion
4701 // sequences in the canonical form defined by 13.3.3.1.1,
4702 // excluding any Lvalue Transformation; the identity conversion
4703 // sequence is considered to be a subsequence of any
4704 // non-identity conversion sequence) or, if not that,
4707 return CK;
4708
4709 // -- the rank of S1 is better than the rank of S2 (by the rules
4710 // defined below), or, if not that,
4711 ImplicitConversionRank Rank1 = SCS1.getRank();
4712 ImplicitConversionRank Rank2 = SCS2.getRank();
4713 if (Rank1 < Rank2)
4715 else if (Rank2 < Rank1)
4717
4718 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4719 // are indistinguishable unless one of the following rules
4720 // applies:
4721
4722 // A conversion that is not a conversion of a pointer, or
4723 // pointer to member, to bool is better than another conversion
4724 // that is such a conversion.
4726 return SCS2.isPointerConversionToBool()
4729
4730 // C++14 [over.ics.rank]p4b2:
4731 // This is retroactively applied to C++11 by CWG 1601.
4732 //
4733 // A conversion that promotes an enumeration whose underlying type is fixed
4734 // to its underlying type is better than one that promotes to the promoted
4735 // underlying type, if the two are different.
4738 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4739 FEP1 != FEP2)
4743
4744 // C++ [over.ics.rank]p4b2:
4745 //
4746 // If class B is derived directly or indirectly from class A,
4747 // conversion of B* to A* is better than conversion of B* to
4748 // void*, and conversion of A* to void* is better than conversion
4749 // of B* to void*.
4750 bool SCS1ConvertsToVoid
4752 bool SCS2ConvertsToVoid
4754 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4755 // Exactly one of the conversion sequences is a conversion to
4756 // a void pointer; it's the worse conversion.
4757 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4759 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4760 // Neither conversion sequence converts to a void pointer; compare
4761 // their derived-to-base conversions.
4763 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4764 return DerivedCK;
4765 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4766 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4767 // Both conversion sequences are conversions to void
4768 // pointers. Compare the source types to determine if there's an
4769 // inheritance relationship in their sources.
4770 QualType FromType1 = SCS1.getFromType();
4771 QualType FromType2 = SCS2.getFromType();
4772
4773 // Adjust the types we're converting from via the array-to-pointer
4774 // conversion, if we need to.
4775 if (SCS1.First == ICK_Array_To_Pointer)
4776 FromType1 = S.Context.getArrayDecayedType(FromType1);
4777 if (SCS2.First == ICK_Array_To_Pointer)
4778 FromType2 = S.Context.getArrayDecayedType(FromType2);
4779
4780 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4781 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4782
4783 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4785 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4787
4788 // Objective-C++: If one interface is more specific than the
4789 // other, it is the better one.
4790 const ObjCObjectPointerType* FromObjCPtr1
4791 = FromType1->getAs<ObjCObjectPointerType>();
4792 const ObjCObjectPointerType* FromObjCPtr2
4793 = FromType2->getAs<ObjCObjectPointerType>();
4794 if (FromObjCPtr1 && FromObjCPtr2) {
4795 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4796 FromObjCPtr2);
4797 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4798 FromObjCPtr1);
4799 if (AssignLeft != AssignRight) {
4800 return AssignLeft? ImplicitConversionSequence::Better
4802 }
4803 }
4804 }
4805
4806 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4807 // Check for a better reference binding based on the kind of bindings.
4808 if (isBetterReferenceBindingKind(SCS1, SCS2))
4810 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4812 }
4813
4814 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4815 // bullet 3).
4817 = CompareQualificationConversions(S, SCS1, SCS2))
4818 return QualCK;
4819
4822 return ObtCK;
4823
4824 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4825 // C++ [over.ics.rank]p3b4:
4826 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4827 // which the references refer are the same type except for
4828 // top-level cv-qualifiers, and the type to which the reference
4829 // initialized by S2 refers is more cv-qualified than the type
4830 // to which the reference initialized by S1 refers.
4831 QualType T1 = SCS1.getToType(2);
4832 QualType T2 = SCS2.getToType(2);
4833 T1 = S.Context.getCanonicalType(T1);
4834 T2 = S.Context.getCanonicalType(T2);
4835 Qualifiers T1Quals, T2Quals;
4836 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4837 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4838 if (UnqualT1 == UnqualT2) {
4839 // Objective-C++ ARC: If the references refer to objects with different
4840 // lifetimes, prefer bindings that don't change lifetime.
4846 }
4847
4848 // If the type is an array type, promote the element qualifiers to the
4849 // type for comparison.
4850 if (isa<ArrayType>(T1) && T1Quals)
4851 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4852 if (isa<ArrayType>(T2) && T2Quals)
4853 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4854 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4856 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4858 }
4859 }
4860
4861 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4862 // floating-to-integral conversion if the integral conversion
4863 // is between types of the same size.
4864 // For example:
4865 // void f(float);
4866 // void f(int);
4867 // int main {
4868 // long a;
4869 // f(a);
4870 // }
4871 // Here, MSVC will call f(int) instead of generating a compile error
4872 // as clang will do in standard mode.
4873 if (S.getLangOpts().MSVCCompat &&
4876 SCS2.Second == ICK_Floating_Integral &&
4877 S.Context.getTypeSize(SCS1.getFromType()) ==
4878 S.Context.getTypeSize(SCS1.getToType(2)))
4880
4881 // Prefer a compatible vector conversion over a lax vector conversion
4882 // For example:
4883 //
4884 // typedef float __v4sf __attribute__((__vector_size__(16)));
4885 // void f(vector float);
4886 // void f(vector signed int);
4887 // int main() {
4888 // __v4sf a;
4889 // f(a);
4890 // }
4891 // Here, we'd like to choose f(vector float) and not
4892 // report an ambiguous call error
4893 if (SCS1.Second == ICK_Vector_Conversion &&
4894 SCS2.Second == ICK_Vector_Conversion) {
4895 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4896 SCS1.getFromType(), SCS1.getToType(2));
4897 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4898 SCS2.getFromType(), SCS2.getToType(2));
4899
4900 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4901 return SCS1IsCompatibleVectorConversion
4904 }
4905
4906 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4908 bool SCS1IsCompatibleSVEVectorConversion =
4909 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4910 bool SCS2IsCompatibleSVEVectorConversion =
4911 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4912
4913 if (SCS1IsCompatibleSVEVectorConversion !=
4914 SCS2IsCompatibleSVEVectorConversion)
4915 return SCS1IsCompatibleSVEVectorConversion
4918 }
4919
4920 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4922 bool SCS1IsCompatibleRVVVectorConversion =
4924 bool SCS2IsCompatibleRVVVectorConversion =
4926
4927 if (SCS1IsCompatibleRVVVectorConversion !=
4928 SCS2IsCompatibleRVVVectorConversion)
4929 return SCS1IsCompatibleRVVVectorConversion
4932 }
4934}
4935
4936/// CompareOverflowBehaviorConversions - Compares two standard conversion
4937/// sequences to determine whether they can be ranked based on their
4938/// OverflowBehaviorType's underlying type.
4954
4955/// CompareQualificationConversions - Compares two standard conversion
4956/// sequences to determine whether they can be ranked based on their
4957/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4960 const StandardConversionSequence& SCS1,
4961 const StandardConversionSequence& SCS2) {
4962 // C++ [over.ics.rank]p3:
4963 // -- S1 and S2 differ only in their qualification conversion and
4964 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4965 // [C++98]
4966 // [...] and the cv-qualification signature of type T1 is a proper subset
4967 // of the cv-qualification signature of type T2, and S1 is not the
4968 // deprecated string literal array-to-pointer conversion (4.2).
4969 // [C++2a]
4970 // [...] where T1 can be converted to T2 by a qualification conversion.
4971 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4972 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4974
4975 // FIXME: the example in the standard doesn't use a qualification
4976 // conversion (!)
4977 QualType T1 = SCS1.getToType(2);
4978 QualType T2 = SCS2.getToType(2);
4979 T1 = S.Context.getCanonicalType(T1);
4980 T2 = S.Context.getCanonicalType(T2);
4981 assert(!T1->isReferenceType() && !T2->isReferenceType());
4982 Qualifiers T1Quals, T2Quals;
4983 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4984 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4985
4986 // If the types are the same, we won't learn anything by unwrapping
4987 // them.
4988 if (UnqualT1 == UnqualT2)
4990
4991 // Don't ever prefer a standard conversion sequence that uses the deprecated
4992 // string literal array to pointer conversion.
4993 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4994 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4995
4996 // Objective-C++ ARC:
4997 // Prefer qualification conversions not involving a change in lifetime
4998 // to qualification conversions that do change lifetime.
5001 CanPick1 = false;
5004 CanPick2 = false;
5005
5006 bool ObjCLifetimeConversion;
5007 if (CanPick1 &&
5008 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5009 CanPick1 = false;
5010 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5011 // directions, so we can't short-cut this second check in general.
5012 if (CanPick2 &&
5013 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5014 CanPick2 = false;
5015
5016 if (CanPick1 != CanPick2)
5017 return CanPick1 ? ImplicitConversionSequence::Better
5020}
5021
5022/// CompareDerivedToBaseConversions - Compares two standard conversion
5023/// sequences to determine whether they can be ranked based on their
5024/// various kinds of derived-to-base conversions (C++
5025/// [over.ics.rank]p4b3). As part of these checks, we also look at
5026/// conversions between Objective-C interface types.
5029 const StandardConversionSequence& SCS1,
5030 const StandardConversionSequence& SCS2) {
5031 QualType FromType1 = SCS1.getFromType();
5032 QualType ToType1 = SCS1.getToType(1);
5033 QualType FromType2 = SCS2.getFromType();
5034 QualType ToType2 = SCS2.getToType(1);
5035
5036 // Adjust the types we're converting from via the array-to-pointer
5037 // conversion, if we need to.
5038 if (SCS1.First == ICK_Array_To_Pointer)
5039 FromType1 = S.Context.getArrayDecayedType(FromType1);
5040 if (SCS2.First == ICK_Array_To_Pointer)
5041 FromType2 = S.Context.getArrayDecayedType(FromType2);
5042
5043 // Canonicalize all of the types.
5044 FromType1 = S.Context.getCanonicalType(FromType1);
5045 ToType1 = S.Context.getCanonicalType(ToType1);
5046 FromType2 = S.Context.getCanonicalType(FromType2);
5047 ToType2 = S.Context.getCanonicalType(ToType2);
5048
5049 // C++ [over.ics.rank]p4b3:
5050 //
5051 // If class B is derived directly or indirectly from class A and
5052 // class C is derived directly or indirectly from B,
5053 //
5054 // Compare based on pointer conversions.
5055 if (SCS1.Second == ICK_Pointer_Conversion &&
5057 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5058 FromType1->isPointerType() && FromType2->isPointerType() &&
5059 ToType1->isPointerType() && ToType2->isPointerType()) {
5060 QualType FromPointee1 =
5062 QualType ToPointee1 =
5064 QualType FromPointee2 =
5066 QualType ToPointee2 =
5068
5069 // -- conversion of C* to B* is better than conversion of C* to A*,
5070 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5071 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5073 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5075 }
5076
5077 // -- conversion of B* to A* is better than conversion of C* to A*,
5078 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5079 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5081 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5083 }
5084 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5086 const ObjCObjectPointerType *FromPtr1
5087 = FromType1->getAs<ObjCObjectPointerType>();
5088 const ObjCObjectPointerType *FromPtr2
5089 = FromType2->getAs<ObjCObjectPointerType>();
5090 const ObjCObjectPointerType *ToPtr1
5091 = ToType1->getAs<ObjCObjectPointerType>();
5092 const ObjCObjectPointerType *ToPtr2
5093 = ToType2->getAs<ObjCObjectPointerType>();
5094
5095 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5096 // Apply the same conversion ranking rules for Objective-C pointer types
5097 // that we do for C++ pointers to class types. However, we employ the
5098 // Objective-C pseudo-subtyping relationship used for assignment of
5099 // Objective-C pointer types.
5100 bool FromAssignLeft
5101 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5102 bool FromAssignRight
5103 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5104 bool ToAssignLeft
5105 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5106 bool ToAssignRight
5107 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5108
5109 // A conversion to an a non-id object pointer type or qualified 'id'
5110 // type is better than a conversion to 'id'.
5111 if (ToPtr1->isObjCIdType() &&
5112 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5114 if (ToPtr2->isObjCIdType() &&
5115 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5117
5118 // A conversion to a non-id object pointer type is better than a
5119 // conversion to a qualified 'id' type
5120 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5122 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5124
5125 // A conversion to an a non-Class object pointer type or qualified 'Class'
5126 // type is better than a conversion to 'Class'.
5127 if (ToPtr1->isObjCClassType() &&
5128 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5130 if (ToPtr2->isObjCClassType() &&
5131 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5133
5134 // A conversion to a non-Class object pointer type is better than a
5135 // conversion to a qualified 'Class' type.
5136 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5138 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5140
5141 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5142 if (S.Context.hasSameType(FromType1, FromType2) &&
5143 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5144 (ToAssignLeft != ToAssignRight)) {
5145 if (FromPtr1->isSpecialized()) {
5146 // "conversion of B<A> * to B * is better than conversion of B * to
5147 // C *.
5148 bool IsFirstSame =
5149 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5150 bool IsSecondSame =
5151 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5152 if (IsFirstSame) {
5153 if (!IsSecondSame)
5155 } else if (IsSecondSame)
5157 }
5158 return ToAssignLeft? ImplicitConversionSequence::Worse
5160 }
5161
5162 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5163 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5164 (FromAssignLeft != FromAssignRight))
5165 return FromAssignLeft? ImplicitConversionSequence::Better
5167 }
5168 }
5169
5170 // Ranking of member-pointer types.
5171 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5172 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5173 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5174 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5175 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5176 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5177 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5178 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5179 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5180 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5181 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5182 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5183 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5184 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5186 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5188 }
5189 // conversion of B::* to C::* is better than conversion of A::* to C::*
5190 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5191 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5193 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5195 }
5196 }
5197
5198 if (SCS1.Second == ICK_Derived_To_Base) {
5199 // -- conversion of C to B is better than conversion of C to A,
5200 // -- binding of an expression of type C to a reference of type
5201 // B& is better than binding an expression of type C to a
5202 // reference of type A&,
5203 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5204 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5205 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5207 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5209 }
5210
5211 // -- conversion of B to A is better than conversion of C to A.
5212 // -- binding of an expression of type B to a reference of type
5213 // A& is better than binding an expression of type C to a
5214 // reference of type A&,
5215 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5216 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5217 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5219 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5221 }
5222 }
5223
5225}
5226
5228 if (!T.getQualifiers().hasUnaligned())
5229 return T;
5230
5231 Qualifiers Q;
5232 T = Ctx.getUnqualifiedArrayType(T, Q);
5233 Q.removeUnaligned();
5234 return Ctx.getQualifiedType(T, Q);
5235}
5236
5239 QualType OrigT1, QualType OrigT2,
5240 ReferenceConversions *ConvOut) {
5241 assert(!OrigT1->isReferenceType() &&
5242 "T1 must be the pointee type of the reference type");
5243 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5244
5245 QualType T1 = Context.getCanonicalType(OrigT1);
5246 QualType T2 = Context.getCanonicalType(OrigT2);
5247 Qualifiers T1Quals, T2Quals;
5248 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5249 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5250
5251 ReferenceConversions ConvTmp;
5252 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5253 Conv = ReferenceConversions();
5254
5255 // C++2a [dcl.init.ref]p4:
5256 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5257 // reference-related to "cv2 T2" if T1 is similar to T2, or
5258 // T1 is a base class of T2.
5259 // "cv1 T1" is reference-compatible with "cv2 T2" if
5260 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5261 // "pointer to cv1 T1" via a standard conversion sequence.
5262
5263 // Check for standard conversions we can apply to pointers: derived-to-base
5264 // conversions, ObjC pointer conversions, and function pointer conversions.
5265 // (Qualification conversions are checked last.)
5266 if (UnqualT1 == UnqualT2) {
5267 // Nothing to do.
5268 } else if (isCompleteType(Loc, OrigT2) &&
5269 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5270 Conv |= ReferenceConversions::DerivedToBase;
5271 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5272 UnqualT2->isObjCObjectOrInterfaceType() &&
5273 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5274 Conv |= ReferenceConversions::ObjC;
5275 else if (UnqualT2->isFunctionType() &&
5276 IsFunctionConversion(UnqualT2, UnqualT1)) {
5277 Conv |= ReferenceConversions::Function;
5278 // No need to check qualifiers; function types don't have them.
5279 return Ref_Compatible;
5280 }
5281 bool ConvertedReferent = Conv != 0;
5282
5283 // We can have a qualification conversion. Compute whether the types are
5284 // similar at the same time.
5285 bool PreviousToQualsIncludeConst = true;
5286 bool TopLevel = true;
5287 do {
5288 if (T1 == T2)
5289 break;
5290
5291 // We will need a qualification conversion.
5292 Conv |= ReferenceConversions::Qualification;
5293
5294 // Track whether we performed a qualification conversion anywhere other
5295 // than the top level. This matters for ranking reference bindings in
5296 // overload resolution.
5297 if (!TopLevel)
5298 Conv |= ReferenceConversions::NestedQualification;
5299
5300 // MS compiler ignores __unaligned qualifier for references; do the same.
5301 T1 = withoutUnaligned(Context, T1);
5302 T2 = withoutUnaligned(Context, T2);
5303
5304 // If we find a qualifier mismatch, the types are not reference-compatible,
5305 // but are still be reference-related if they're similar.
5306 bool ObjCLifetimeConversion = false;
5307 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5308 PreviousToQualsIncludeConst,
5309 ObjCLifetimeConversion, getASTContext()))
5310 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5311 ? Ref_Related
5313
5314 // FIXME: Should we track this for any level other than the first?
5315 if (ObjCLifetimeConversion)
5316 Conv |= ReferenceConversions::ObjCLifetime;
5317
5318 TopLevel = false;
5319 } while (Context.UnwrapSimilarTypes(T1, T2));
5320
5321 // At this point, if the types are reference-related, we must either have the
5322 // same inner type (ignoring qualifiers), or must have already worked out how
5323 // to convert the referent.
5324 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5327}
5328
5329/// Look for a user-defined conversion to a value reference-compatible
5330/// with DeclType. Return true if something definite is found.
5331static bool
5333 QualType DeclType, SourceLocation DeclLoc,
5334 Expr *Init, QualType T2, bool AllowRvalues,
5335 bool AllowExplicit) {
5336 assert(T2->isRecordType() && "Can only find conversions of record types.");
5337 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5338 OverloadCandidateSet CandidateSet(
5340 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5341 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5342 NamedDecl *D = *I;
5344 if (isa<UsingShadowDecl>(D))
5345 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5346
5347 FunctionTemplateDecl *ConvTemplate
5348 = dyn_cast<FunctionTemplateDecl>(D);
5349 CXXConversionDecl *Conv;
5350 if (ConvTemplate)
5351 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5352 else
5353 Conv = cast<CXXConversionDecl>(D);
5354
5355 if (AllowRvalues) {
5356 // If we are initializing an rvalue reference, don't permit conversion
5357 // functions that return lvalues.
5358 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5359 const ReferenceType *RefType
5361 if (RefType && !RefType->getPointeeType()->isFunctionType())
5362 continue;
5363 }
5364
5365 if (!ConvTemplate &&
5367 DeclLoc,
5368 Conv->getConversionType()
5373 continue;
5374 } else {
5375 // If the conversion function doesn't return a reference type,
5376 // it can't be considered for this conversion. An rvalue reference
5377 // is only acceptable if its referencee is a function type.
5378
5379 const ReferenceType *RefType =
5381 if (!RefType ||
5382 (!RefType->isLValueReferenceType() &&
5383 !RefType->getPointeeType()->isFunctionType()))
5384 continue;
5385 }
5386
5387 if (ConvTemplate)
5389 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5390 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5391 else
5393 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5394 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5395 }
5396
5397 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5398
5400 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5401 case OR_Success:
5402
5403 assert(Best->HasFinalConversion);
5404
5405 // C++ [over.ics.ref]p1:
5406 //
5407 // [...] If the parameter binds directly to the result of
5408 // applying a conversion function to the argument
5409 // expression, the implicit conversion sequence is a
5410 // user-defined conversion sequence (13.3.3.1.2), with the
5411 // second standard conversion sequence either an identity
5412 // conversion or, if the conversion function returns an
5413 // entity of a type that is a derived class of the parameter
5414 // type, a derived-to-base Conversion.
5415 if (!Best->FinalConversion.DirectBinding)
5416 return false;
5417
5418 ICS.setUserDefined();
5419 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5420 ICS.UserDefined.After = Best->FinalConversion;
5421 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5422 ICS.UserDefined.ConversionFunction = Best->Function;
5423 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5424 ICS.UserDefined.EllipsisConversion = false;
5425 assert(ICS.UserDefined.After.ReferenceBinding &&
5427 "Expected a direct reference binding!");
5428 return true;
5429
5430 case OR_Ambiguous:
5431 ICS.setAmbiguous();
5432 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5433 Cand != CandidateSet.end(); ++Cand)
5434 if (Cand->Best)
5435 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5436 return true;
5437
5439 case OR_Deleted:
5440 // There was no suitable conversion, or we found a deleted
5441 // conversion; continue with other checks.
5442 return false;
5443 }
5444
5445 llvm_unreachable("Invalid OverloadResult!");
5446}
5447
5448/// Compute an implicit conversion sequence for reference
5449/// initialization.
5450static ImplicitConversionSequence
5452 SourceLocation DeclLoc,
5453 bool SuppressUserConversions,
5454 bool AllowExplicit) {
5455 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5456
5457 // Most paths end in a failed conversion.
5460
5461 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5462 QualType T2 = Init->getType();
5463
5464 // If the initializer is the address of an overloaded function, try
5465 // to resolve the overloaded function. If all goes well, T2 is the
5466 // type of the resulting function.
5467 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5470 false, Found))
5471 T2 = Fn->getType();
5472 }
5473
5474 // Compute some basic properties of the types and the initializer.
5475 bool isRValRef = DeclType->isRValueReferenceType();
5476 Expr::Classification InitCategory = Init->Classify(S.Context);
5477
5479 Sema::ReferenceCompareResult RefRelationship =
5480 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5481
5482 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5483 ICS.setStandard();
5485 // FIXME: A reference binding can be a function conversion too. We should
5486 // consider that when ordering reference-to-function bindings.
5487 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5489 : (RefConv & Sema::ReferenceConversions::ObjC)
5491 : ICK_Identity;
5493 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5494 // a reference binding that performs a non-top-level qualification
5495 // conversion as a qualification conversion, not as an identity conversion.
5496 ICS.Standard.Third = (RefConv &
5497 Sema::ReferenceConversions::NestedQualification)
5499 : ICK_Identity;
5500 ICS.Standard.setFromType(T2);
5501 ICS.Standard.setToType(0, T2);
5502 ICS.Standard.setToType(1, T1);
5503 ICS.Standard.setToType(2, T1);
5504 ICS.Standard.ReferenceBinding = true;
5505 ICS.Standard.DirectBinding = BindsDirectly;
5506 ICS.Standard.IsLvalueReference = !isRValRef;
5508 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5511 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5512 ICS.Standard.FromBracedInitList = false;
5513 ICS.Standard.CopyConstructor = nullptr;
5515 };
5516
5517 // C++0x [dcl.init.ref]p5:
5518 // A reference to type "cv1 T1" is initialized by an expression
5519 // of type "cv2 T2" as follows:
5520
5521 // -- If reference is an lvalue reference and the initializer expression
5522 if (!isRValRef) {
5523 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5524 // reference-compatible with "cv2 T2," or
5525 //
5526 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5527 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5528 // C++ [over.ics.ref]p1:
5529 // When a parameter of reference type binds directly (8.5.3)
5530 // to an argument expression, the implicit conversion sequence
5531 // is the identity conversion, unless the argument expression
5532 // has a type that is a derived class of the parameter type,
5533 // in which case the implicit conversion sequence is a
5534 // derived-to-base Conversion (13.3.3.1).
5535 SetAsReferenceBinding(/*BindsDirectly=*/true);
5536
5537 // Nothing more to do: the inaccessibility/ambiguity check for
5538 // derived-to-base conversions is suppressed when we're
5539 // computing the implicit conversion sequence (C++
5540 // [over.best.ics]p2).
5541 return ICS;
5542 }
5543
5544 // -- has a class type (i.e., T2 is a class type), where T1 is
5545 // not reference-related to T2, and can be implicitly
5546 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5547 // is reference-compatible with "cv3 T3" 92) (this
5548 // conversion is selected by enumerating the applicable
5549 // conversion functions (13.3.1.6) and choosing the best
5550 // one through overload resolution (13.3)),
5551 if (!SuppressUserConversions && T2->isRecordType() &&
5552 S.isCompleteType(DeclLoc, T2) &&
5553 RefRelationship == Sema::Ref_Incompatible) {
5554 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5555 Init, T2, /*AllowRvalues=*/false,
5556 AllowExplicit))
5557 return ICS;
5558 }
5559 }
5560
5561 // -- Otherwise, the reference shall be an lvalue reference to a
5562 // non-volatile const type (i.e., cv1 shall be const), or the reference
5563 // shall be an rvalue reference.
5564 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5565 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5567 return ICS;
5568 }
5569
5570 // -- If the initializer expression
5571 //
5572 // -- is an xvalue, class prvalue, array prvalue or function
5573 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5574 if (RefRelationship == Sema::Ref_Compatible &&
5575 (InitCategory.isXValue() ||
5576 (InitCategory.isPRValue() &&
5577 (T2->isRecordType() || T2->isArrayType())) ||
5578 (InitCategory.isLValue() && T2->isFunctionType()))) {
5579 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5580 // binding unless we're binding to a class prvalue.
5581 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5582 // allow the use of rvalue references in C++98/03 for the benefit of
5583 // standard library implementors; therefore, we need the xvalue check here.
5584 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5585 !(InitCategory.isPRValue() || T2->isRecordType()));
5586 return ICS;
5587 }
5588
5589 // -- has a class type (i.e., T2 is a class type), where T1 is not
5590 // reference-related to T2, and can be implicitly converted to
5591 // an xvalue, class prvalue, or function lvalue of type
5592 // "cv3 T3", where "cv1 T1" is reference-compatible with
5593 // "cv3 T3",
5594 //
5595 // then the reference is bound to the value of the initializer
5596 // expression in the first case and to the result of the conversion
5597 // in the second case (or, in either case, to an appropriate base
5598 // class subobject).
5599 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5600 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5601 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5602 Init, T2, /*AllowRvalues=*/true,
5603 AllowExplicit)) {
5604 // In the second case, if the reference is an rvalue reference
5605 // and the second standard conversion sequence of the
5606 // user-defined conversion sequence includes an lvalue-to-rvalue
5607 // conversion, the program is ill-formed.
5608 if (ICS.isUserDefined() && isRValRef &&
5611
5612 return ICS;
5613 }
5614
5615 // A temporary of function type cannot be created; don't even try.
5616 if (T1->isFunctionType())
5617 return ICS;
5618
5619 // -- Otherwise, a temporary of type "cv1 T1" is created and
5620 // initialized from the initializer expression using the
5621 // rules for a non-reference copy initialization (8.5). The
5622 // reference is then bound to the temporary. If T1 is
5623 // reference-related to T2, cv1 must be the same
5624 // cv-qualification as, or greater cv-qualification than,
5625 // cv2; otherwise, the program is ill-formed.
5626 if (RefRelationship == Sema::Ref_Related) {
5627 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5628 // we would be reference-compatible or reference-compatible with
5629 // added qualification. But that wasn't the case, so the reference
5630 // initialization fails.
5631 //
5632 // Note that we only want to check address spaces and cvr-qualifiers here.
5633 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5634 Qualifiers T1Quals = T1.getQualifiers();
5635 Qualifiers T2Quals = T2.getQualifiers();
5636 T1Quals.removeObjCGCAttr();
5637 T1Quals.removeObjCLifetime();
5638 T2Quals.removeObjCGCAttr();
5639 T2Quals.removeObjCLifetime();
5640 // MS compiler ignores __unaligned qualifier for references; do the same.
5641 T1Quals.removeUnaligned();
5642 T2Quals.removeUnaligned();
5643 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5644 return ICS;
5645 }
5646
5647 // If at least one of the types is a class type, the types are not
5648 // related, and we aren't allowed any user conversions, the
5649 // reference binding fails. This case is important for breaking
5650 // recursion, since TryImplicitConversion below will attempt to
5651 // create a temporary through the use of a copy constructor.
5652 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5653 (T1->isRecordType() || T2->isRecordType()))
5654 return ICS;
5655
5656 // If T1 is reference-related to T2 and the reference is an rvalue
5657 // reference, the initializer expression shall not be an lvalue.
5658 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5659 Init->Classify(S.Context).isLValue()) {
5661 return ICS;
5662 }
5663
5664 // C++ [over.ics.ref]p2:
5665 // When a parameter of reference type is not bound directly to
5666 // an argument expression, the conversion sequence is the one
5667 // required to convert the argument expression to the
5668 // underlying type of the reference according to
5669 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5670 // to copy-initializing a temporary of the underlying type with
5671 // the argument expression. Any difference in top-level
5672 // cv-qualification is subsumed by the initialization itself
5673 // and does not constitute a conversion.
5674 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5675 AllowedExplicit::None,
5676 /*InOverloadResolution=*/false,
5677 /*CStyle=*/false,
5678 /*AllowObjCWritebackConversion=*/false,
5679 /*AllowObjCConversionOnExplicit=*/false);
5680
5681 // Of course, that's still a reference binding.
5682 if (ICS.isStandard()) {
5683 ICS.Standard.ReferenceBinding = true;
5684 ICS.Standard.IsLvalueReference = !isRValRef;
5685 ICS.Standard.BindsToFunctionLvalue = false;
5686 ICS.Standard.BindsToRvalue = true;
5689 } else if (ICS.isUserDefined()) {
5690 const ReferenceType *LValRefType =
5693
5694 // C++ [over.ics.ref]p3:
5695 // Except for an implicit object parameter, for which see 13.3.1, a
5696 // standard conversion sequence cannot be formed if it requires [...]
5697 // binding an rvalue reference to an lvalue other than a function
5698 // lvalue.
5699 // Note that the function case is not possible here.
5700 if (isRValRef && LValRefType) {
5702 return ICS;
5703 }
5704
5706 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5708 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5712 }
5713
5714 return ICS;
5715}
5716
5717static ImplicitConversionSequence
5718TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5719 bool SuppressUserConversions,
5720 bool InOverloadResolution,
5721 bool AllowObjCWritebackConversion,
5722 bool AllowExplicit = false);
5723
5724/// TryListConversion - Try to copy-initialize a value of type ToType from the
5725/// initializer list From.
5726static ImplicitConversionSequence
5728 bool SuppressUserConversions,
5729 bool InOverloadResolution,
5730 bool AllowObjCWritebackConversion) {
5731 // C++11 [over.ics.list]p1:
5732 // When an argument is an initializer list, it is not an expression and
5733 // special rules apply for converting it to a parameter type.
5734
5736 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5737
5738 // We need a complete type for what follows. With one C++20 exception,
5739 // incomplete types can never be initialized from init lists.
5740 QualType InitTy = ToType;
5741 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5742 if (AT && S.getLangOpts().CPlusPlus20)
5743 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5744 // C++20 allows list initialization of an incomplete array type.
5745 InitTy = IAT->getElementType();
5746 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5747 return Result;
5748
5749 // C++20 [over.ics.list]/2:
5750 // If the initializer list is a designated-initializer-list, a conversion
5751 // is only possible if the parameter has an aggregate type
5752 //
5753 // FIXME: The exception for reference initialization here is not part of the
5754 // language rules, but follow other compilers in adding it as a tentative DR
5755 // resolution.
5756 bool IsDesignatedInit = From->hasDesignatedInit();
5757 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5758 IsDesignatedInit)
5759 return Result;
5760
5761 // Per DR1467 and DR2137:
5762 // If the parameter type is an aggregate class X and the initializer list
5763 // has a single element of type cv U, where U is X or a class derived from
5764 // X, the implicit conversion sequence is the one required to convert the
5765 // element to the parameter type.
5766 //
5767 // Otherwise, if the parameter type is a character array [... ]
5768 // and the initializer list has a single element that is an
5769 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5770 // implicit conversion sequence is the identity conversion.
5771 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5772 if (ToType->isRecordType() && ToType->isAggregateType()) {
5773 QualType InitType = From->getInit(0)->getType();
5774 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5775 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5776 return TryCopyInitialization(S, From->getInit(0), ToType,
5777 SuppressUserConversions,
5778 InOverloadResolution,
5779 AllowObjCWritebackConversion);
5780 }
5781
5782 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5783 InitializedEntity Entity =
5785 /*Consumed=*/false);
5786 if (S.CanPerformCopyInitialization(Entity, From)) {
5787 Result.setStandard();
5788 Result.Standard.setAsIdentityConversion();
5789 Result.Standard.setFromType(ToType);
5790 Result.Standard.setAllToTypes(ToType);
5791 return Result;
5792 }
5793 }
5794 }
5795
5796 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5797 // C++11 [over.ics.list]p2:
5798 // If the parameter type is std::initializer_list<X> or "array of X" and
5799 // all the elements can be implicitly converted to X, the implicit
5800 // conversion sequence is the worst conversion necessary to convert an
5801 // element of the list to X.
5802 //
5803 // C++14 [over.ics.list]p3:
5804 // Otherwise, if the parameter type is "array of N X", if the initializer
5805 // list has exactly N elements or if it has fewer than N elements and X is
5806 // default-constructible, and if all the elements of the initializer list
5807 // can be implicitly converted to X, the implicit conversion sequence is
5808 // the worst conversion necessary to convert an element of the list to X.
5809 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5810 unsigned e = From->getNumInits();
5813 QualType());
5814 QualType ContTy = ToType;
5815 bool IsUnbounded = false;
5816 if (AT) {
5817 InitTy = AT->getElementType();
5818 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5819 if (CT->getSize().ult(e)) {
5820 // Too many inits, fatally bad
5822 ToType);
5823 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5824 return Result;
5825 }
5826 if (CT->getSize().ugt(e)) {
5827 // Need an init from empty {}, is there one?
5828 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5829 From->getEndLoc());
5830 EmptyList.setType(S.Context.VoidTy);
5831 DfltElt = TryListConversion(
5832 S, &EmptyList, InitTy, SuppressUserConversions,
5833 InOverloadResolution, AllowObjCWritebackConversion);
5834 if (DfltElt.isBad()) {
5835 // No {} init, fatally bad
5837 ToType);
5838 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5839 return Result;
5840 }
5841 }
5842 } else {
5843 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5844 IsUnbounded = true;
5845 if (!e) {
5846 // Cannot convert to zero-sized.
5848 ToType);
5849 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5850 return Result;
5851 }
5852 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5853 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5855 }
5856 }
5857
5858 Result.setStandard();
5859 Result.Standard.setAsIdentityConversion();
5860 Result.Standard.setFromType(InitTy);
5861 Result.Standard.setAllToTypes(InitTy);
5862 for (unsigned i = 0; i < e; ++i) {
5863 Expr *Init = From->getInit(i);
5865 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5866 AllowObjCWritebackConversion);
5867
5868 // Keep the worse conversion seen so far.
5869 // FIXME: Sequences are not totally ordered, so 'worse' can be
5870 // ambiguous. CWG has been informed.
5872 Result) ==
5874 Result = ICS;
5875 // Bail as soon as we find something unconvertible.
5876 if (Result.isBad()) {
5877 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5878 return Result;
5879 }
5880 }
5881 }
5882
5883 // If we needed any implicit {} initialization, compare that now.
5884 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5885 // has been informed that this might not be the best thing.
5886 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5887 S, From->getEndLoc(), DfltElt, Result) ==
5889 Result = DfltElt;
5890 // Record the type being initialized so that we may compare sequences
5891 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5892 return Result;
5893 }
5894
5895 // C++14 [over.ics.list]p4:
5896 // C++11 [over.ics.list]p3:
5897 // Otherwise, if the parameter is a non-aggregate class X and overload
5898 // resolution chooses a single best constructor [...] the implicit
5899 // conversion sequence is a user-defined conversion sequence. If multiple
5900 // constructors are viable but none is better than the others, the
5901 // implicit conversion sequence is a user-defined conversion sequence.
5902 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5903 // This function can deal with initializer lists.
5904 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5905 AllowedExplicit::None,
5906 InOverloadResolution, /*CStyle=*/false,
5907 AllowObjCWritebackConversion,
5908 /*AllowObjCConversionOnExplicit=*/false);
5909 }
5910
5911 // C++14 [over.ics.list]p5:
5912 // C++11 [over.ics.list]p4:
5913 // Otherwise, if the parameter has an aggregate type which can be
5914 // initialized from the initializer list [...] the implicit conversion
5915 // sequence is a user-defined conversion sequence.
5916 if (ToType->isAggregateType()) {
5917 // Type is an aggregate, argument is an init list. At this point it comes
5918 // down to checking whether the initialization works.
5919 // FIXME: Find out whether this parameter is consumed or not.
5920 InitializedEntity Entity =
5922 /*Consumed=*/false);
5924 From)) {
5925 Result.setUserDefined();
5926 Result.UserDefined.Before.setAsIdentityConversion();
5927 // Initializer lists don't have a type.
5928 Result.UserDefined.Before.setFromType(QualType());
5929 Result.UserDefined.Before.setAllToTypes(QualType());
5930
5931 Result.UserDefined.After.setAsIdentityConversion();
5932 Result.UserDefined.After.setFromType(ToType);
5933 Result.UserDefined.After.setAllToTypes(ToType);
5934 Result.UserDefined.ConversionFunction = nullptr;
5935 }
5936 return Result;
5937 }
5938
5939 // C++14 [over.ics.list]p6:
5940 // C++11 [over.ics.list]p5:
5941 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5942 if (ToType->isReferenceType()) {
5943 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5944 // mention initializer lists in any way. So we go by what list-
5945 // initialization would do and try to extrapolate from that.
5946
5947 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5948
5949 // If the initializer list has a single element that is reference-related
5950 // to the parameter type, we initialize the reference from that.
5951 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5952 Expr *Init = From->getInit(0);
5953
5954 QualType T2 = Init->getType();
5955
5956 // If the initializer is the address of an overloaded function, try
5957 // to resolve the overloaded function. If all goes well, T2 is the
5958 // type of the resulting function.
5959 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5962 Init, ToType, false, Found))
5963 T2 = Fn->getType();
5964 }
5965
5966 // Compute some basic properties of the types and the initializer.
5967 Sema::ReferenceCompareResult RefRelationship =
5968 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5969
5970 if (RefRelationship >= Sema::Ref_Related) {
5971 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5972 SuppressUserConversions,
5973 /*AllowExplicit=*/false);
5974 }
5975 }
5976
5977 // Otherwise, we bind the reference to a temporary created from the
5978 // initializer list.
5979 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5980 InOverloadResolution,
5981 AllowObjCWritebackConversion);
5982 if (Result.isFailure())
5983 return Result;
5984 assert(!Result.isEllipsis() &&
5985 "Sub-initialization cannot result in ellipsis conversion.");
5986
5987 // Can we even bind to a temporary?
5988 if (ToType->isRValueReferenceType() ||
5989 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5990 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5991 Result.UserDefined.After;
5992 SCS.ReferenceBinding = true;
5994 SCS.BindsToRvalue = true;
5995 SCS.BindsToFunctionLvalue = false;
5998 SCS.FromBracedInitList = false;
5999
6000 } else
6002 From, ToType);
6003 return Result;
6004 }
6005
6006 // C++14 [over.ics.list]p7:
6007 // C++11 [over.ics.list]p6:
6008 // Otherwise, if the parameter type is not a class:
6009 if (!ToType->isRecordType()) {
6010 // - if the initializer list has one element that is not itself an
6011 // initializer list, the implicit conversion sequence is the one
6012 // required to convert the element to the parameter type.
6013 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6014 // single integer.
6015 unsigned NumInits = From->getNumInits();
6016 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6017 !isa<EmbedExpr>(From->getInit(0))) {
6018 Result = TryCopyInitialization(
6019 S, From->getInit(0), ToType, SuppressUserConversions,
6020 InOverloadResolution, AllowObjCWritebackConversion);
6021 if (Result.isStandard())
6022 Result.Standard.FromBracedInitList = true;
6023 }
6024 // - if the initializer list has no elements, the implicit conversion
6025 // sequence is the identity conversion.
6026 else if (NumInits == 0) {
6027 Result.setStandard();
6028 Result.Standard.setAsIdentityConversion();
6029 Result.Standard.setFromType(ToType);
6030 Result.Standard.setAllToTypes(ToType);
6031 }
6032 return Result;
6033 }
6034
6035 // C++14 [over.ics.list]p8:
6036 // C++11 [over.ics.list]p7:
6037 // In all cases other than those enumerated above, no conversion is possible
6038 return Result;
6039}
6040
6041/// TryCopyInitialization - Try to copy-initialize a value of type
6042/// ToType from the expression From. Return the implicit conversion
6043/// sequence required to pass this argument, which may be a bad
6044/// conversion sequence (meaning that the argument cannot be passed to
6045/// a parameter of this type). If @p SuppressUserConversions, then we
6046/// do not permit any user-defined conversion sequences.
6047static ImplicitConversionSequence
6049 bool SuppressUserConversions,
6050 bool InOverloadResolution,
6051 bool AllowObjCWritebackConversion,
6052 bool AllowExplicit) {
6053 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6054 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6055 InOverloadResolution,AllowObjCWritebackConversion);
6056
6057 if (ToType->isReferenceType())
6058 return TryReferenceInit(S, From, ToType,
6059 /*FIXME:*/ From->getBeginLoc(),
6060 SuppressUserConversions, AllowExplicit);
6061
6062 return TryImplicitConversion(S, From, ToType,
6063 SuppressUserConversions,
6064 AllowedExplicit::None,
6065 InOverloadResolution,
6066 /*CStyle=*/false,
6067 AllowObjCWritebackConversion,
6068 /*AllowObjCConversionOnExplicit=*/false);
6069}
6070
6071static bool TryCopyInitialization(const CanQualType FromQTy,
6072 const CanQualType ToQTy,
6073 Sema &S,
6074 SourceLocation Loc,
6075 ExprValueKind FromVK) {
6076 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6078 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6079
6080 return !ICS.isBad();
6081}
6082
6083/// TryObjectArgumentInitialization - Try to initialize the object
6084/// parameter of the given member function (@c Method) from the
6085/// expression @p From.
6087 Sema &S, SourceLocation Loc, QualType FromType,
6088 Expr::Classification FromClassification, CXXMethodDecl *Method,
6089 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6090 QualType ExplicitParameterType = QualType(),
6091 bool SuppressUserConversion = false) {
6092
6093 // We need to have an object of class type.
6094 if (const auto *PT = FromType->getAs<PointerType>()) {
6095 FromType = PT->getPointeeType();
6096
6097 // When we had a pointer, it's implicitly dereferenced, so we
6098 // better have an lvalue.
6099 assert(FromClassification.isLValue());
6100 }
6101
6102 auto ValueKindFromClassification = [](Expr::Classification C) {
6103 if (C.isPRValue())
6104 return clang::VK_PRValue;
6105 if (C.isXValue())
6106 return VK_XValue;
6107 return clang::VK_LValue;
6108 };
6109
6110 if (Method->isExplicitObjectMemberFunction()) {
6111 if (ExplicitParameterType.isNull())
6112 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6113 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6114 ValueKindFromClassification(FromClassification));
6116 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6117 /*InOverloadResolution=*/true, false);
6118 if (ICS.isBad())
6119 ICS.Bad.FromExpr = nullptr;
6120 return ICS;
6121 }
6122
6123 assert(FromType->isRecordType());
6124
6125 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6126 // C++98 [class.dtor]p2:
6127 // A destructor can be invoked for a const, volatile or const volatile
6128 // object.
6129 // C++98 [over.match.funcs]p4:
6130 // For static member functions, the implicit object parameter is considered
6131 // to match any object (since if the function is selected, the object is
6132 // discarded).
6133 Qualifiers Quals = Method->getMethodQualifiers();
6134 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6135 Quals.addConst();
6136 Quals.addVolatile();
6137 }
6138
6139 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6140
6141 // Set up the conversion sequence as a "bad" conversion, to allow us
6142 // to exit early.
6144
6145 // C++0x [over.match.funcs]p4:
6146 // For non-static member functions, the type of the implicit object
6147 // parameter is
6148 //
6149 // - "lvalue reference to cv X" for functions declared without a
6150 // ref-qualifier or with the & ref-qualifier
6151 // - "rvalue reference to cv X" for functions declared with the &&
6152 // ref-qualifier
6153 //
6154 // where X is the class of which the function is a member and cv is the
6155 // cv-qualification on the member function declaration.
6156 //
6157 // However, when finding an implicit conversion sequence for the argument, we
6158 // are not allowed to perform user-defined conversions
6159 // (C++ [over.match.funcs]p5). We perform a simplified version of
6160 // reference binding here, that allows class rvalues to bind to
6161 // non-constant references.
6162
6163 // First check the qualifiers.
6164 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6165 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6166 if (ImplicitParamType.getCVRQualifiers() !=
6167 FromTypeCanon.getLocalCVRQualifiers() &&
6168 !ImplicitParamType.isAtLeastAsQualifiedAs(
6169 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6171 FromType, ImplicitParamType);
6172 return ICS;
6173 }
6174
6175 if (FromTypeCanon.hasAddressSpace()) {
6176 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6177 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6178 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6179 S.getASTContext())) {
6181 FromType, ImplicitParamType);
6182 return ICS;
6183 }
6184 }
6185
6186 // Check that we have either the same type or a derived type. It
6187 // affects the conversion rank.
6188 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6189 ImplicitConversionKind SecondKind;
6190 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6191 SecondKind = ICK_Identity;
6192 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6193 SecondKind = ICK_Derived_To_Base;
6194 } else if (!Method->isExplicitObjectMemberFunction()) {
6196 FromType, ImplicitParamType);
6197 return ICS;
6198 }
6199
6200 // Check the ref-qualifier.
6201 switch (Method->getRefQualifier()) {
6202 case RQ_None:
6203 // Do nothing; we don't care about lvalueness or rvalueness.
6204 break;
6205
6206 case RQ_LValue:
6207 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6208 // non-const lvalue reference cannot bind to an rvalue
6210 ImplicitParamType);
6211 return ICS;
6212 }
6213 break;
6214
6215 case RQ_RValue:
6216 if (!FromClassification.isRValue()) {
6217 // rvalue reference cannot bind to an lvalue
6219 ImplicitParamType);
6220 return ICS;
6221 }
6222 break;
6223 }
6224
6225 // Success. Mark this as a reference binding.
6226 ICS.setStandard();
6228 ICS.Standard.Second = SecondKind;
6229 ICS.Standard.setFromType(FromType);
6230 ICS.Standard.setAllToTypes(ImplicitParamType);
6231 ICS.Standard.ReferenceBinding = true;
6232 ICS.Standard.DirectBinding = true;
6233 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6234 ICS.Standard.BindsToFunctionLvalue = false;
6235 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6236 ICS.Standard.FromBracedInitList = false;
6238 = (Method->getRefQualifier() == RQ_None);
6239 return ICS;
6240}
6241
6242/// PerformObjectArgumentInitialization - Perform initialization of
6243/// the implicit object parameter for the given Method with the given
6244/// expression.
6246 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6248 QualType FromRecordType, DestType;
6249 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6250
6251 Expr::Classification FromClassification;
6252 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6253 FromRecordType = PT->getPointeeType();
6254 DestType = Method->getThisType();
6255 FromClassification = Expr::Classification::makeSimpleLValue();
6256 } else {
6257 FromRecordType = From->getType();
6258 DestType = ImplicitParamRecordType;
6259 FromClassification = From->Classify(Context);
6260
6261 // CWG2813 [expr.call]p6:
6262 // If the function is an implicit object member function, the object
6263 // expression of the class member access shall be a glvalue [...]
6264 if (From->isPRValue()) {
6265 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6266 Method->getRefQualifier() !=
6268 }
6269 }
6270
6271 // Note that we always use the true parent context when performing
6272 // the actual argument initialization.
6274 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6275 Method->getParent());
6276 if (ICS.isBad()) {
6277 switch (ICS.Bad.Kind) {
6279 Qualifiers FromQs = FromRecordType.getQualifiers();
6280 Qualifiers ToQs = DestType.getQualifiers();
6281 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6282 if (CVR) {
6283 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6284 << Method->getDeclName() << FromRecordType << (CVR - 1)
6285 << From->getSourceRange();
6286 Diag(Method->getLocation(), diag::note_previous_decl)
6287 << Method->getDeclName();
6288 return ExprError();
6289 }
6290 break;
6291 }
6292
6295 bool IsRValueQualified =
6296 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6297 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6298 << Method->getDeclName() << FromClassification.isRValue()
6299 << IsRValueQualified;
6300 Diag(Method->getLocation(), diag::note_previous_decl)
6301 << Method->getDeclName();
6302 return ExprError();
6303 }
6304
6307 break;
6308
6311 llvm_unreachable("Lists are not objects");
6312 }
6313
6314 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6315 << ImplicitParamRecordType << FromRecordType
6316 << From->getSourceRange();
6317 }
6318
6319 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6320 ExprResult FromRes =
6321 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6322 if (FromRes.isInvalid())
6323 return ExprError();
6324 From = FromRes.get();
6325 }
6326
6327 if (!Context.hasSameType(From->getType(), DestType)) {
6328 CastKind CK;
6329 QualType PteeTy = DestType->getPointeeType();
6330 LangAS DestAS =
6331 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6332 if (FromRecordType.getAddressSpace() != DestAS)
6333 CK = CK_AddressSpaceConversion;
6334 else
6335 CK = CK_NoOp;
6336 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6337 }
6338 return From;
6339}
6340
6341/// TryContextuallyConvertToBool - Attempt to contextually convert the
6342/// expression From to bool (C++0x [conv]p3).
6345 // C++ [dcl.init]/17.8:
6346 // - Otherwise, if the initialization is direct-initialization, the source
6347 // type is std::nullptr_t, and the destination type is bool, the initial
6348 // value of the object being initialized is false.
6349 if (From->getType()->isNullPtrType())
6351 S.Context.BoolTy,
6352 From->isGLValue());
6353
6354 // All other direct-initialization of bool is equivalent to an implicit
6355 // conversion to bool in which explicit conversions are permitted.
6356 return TryImplicitConversion(S, From, S.Context.BoolTy,
6357 /*SuppressUserConversions=*/false,
6358 AllowedExplicit::Conversions,
6359 /*InOverloadResolution=*/false,
6360 /*CStyle=*/false,
6361 /*AllowObjCWritebackConversion=*/false,
6362 /*AllowObjCConversionOnExplicit=*/false);
6363}
6364
6366 if (checkPlaceholderForOverload(*this, From))
6367 return ExprError();
6368
6370 if (!ICS.isBad())
6371 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6373
6375 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6376 << From->getType() << From->getSourceRange();
6377 return ExprError();
6378}
6379
6380/// Check that the specified conversion is permitted in a converted constant
6381/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6382/// is acceptable.
6385 // Since we know that the target type is an integral or unscoped enumeration
6386 // type, most conversion kinds are impossible. All possible First and Third
6387 // conversions are fine.
6388 switch (SCS.Second) {
6389 case ICK_Identity:
6391 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6393 return true;
6394
6396 // Conversion from an integral or unscoped enumeration type to bool is
6397 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6398 // conversion, so we allow it in a converted constant expression.
6399 //
6400 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6401 // a lot of popular code. We should at least add a warning for this
6402 // (non-conforming) extension.
6404 SCS.getToType(2)->isBooleanType();
6405
6407 case ICK_Pointer_Member:
6408 // C++1z: null pointer conversions and null member pointer conversions are
6409 // only permitted if the source type is std::nullptr_t.
6410 return SCS.getFromType()->isNullPtrType();
6411
6424 case ICK_Vector_Splat:
6425 case ICK_Complex_Real:
6435 return false;
6436
6441 llvm_unreachable("found a first conversion kind in Second");
6442
6444 case ICK_Qualification:
6445 llvm_unreachable("found a third conversion kind in Second");
6446
6448 break;
6449 }
6450
6451 llvm_unreachable("unknown conversion kind");
6452}
6453
6454/// BuildConvertedConstantExpression - Check that the expression From is a
6455/// converted constant expression of type T, perform the conversion but
6456/// does not evaluate the expression
6458 QualType T, CCEKind CCE,
6459 NamedDecl *Dest,
6460 APValue &PreNarrowingValue) {
6461 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6463 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6464 "converted constant expression outside C++11 or TTP matching");
6465
6466 if (checkPlaceholderForOverload(S, From))
6467 return ExprError();
6468
6469 // C++1z [expr.const]p3:
6470 // A converted constant expression of type T is an expression,
6471 // implicitly converted to type T, where the converted
6472 // expression is a constant expression and the implicit conversion
6473 // sequence contains only [... list of conversions ...].
6475 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6477 : TryCopyInitialization(S, From, T,
6478 /*SuppressUserConversions=*/false,
6479 /*InOverloadResolution=*/false,
6480 /*AllowObjCWritebackConversion=*/false,
6481 /*AllowExplicit=*/false);
6482 StandardConversionSequence *SCS = nullptr;
6483 switch (ICS.getKind()) {
6485 SCS = &ICS.Standard;
6486 break;
6488 if (T->isRecordType())
6489 SCS = &ICS.UserDefined.Before;
6490 else
6491 SCS = &ICS.UserDefined.After;
6492 break;
6496 return S.Diag(From->getBeginLoc(),
6497 diag::err_typecheck_converted_constant_expression)
6498 << From->getType() << From->getSourceRange() << T;
6499 return ExprError();
6500
6503 llvm_unreachable("bad conversion in converted constant expression");
6504 }
6505
6506 // Check that we would only use permitted conversions.
6507 if (!CheckConvertedConstantConversions(S, *SCS)) {
6508 return S.Diag(From->getBeginLoc(),
6509 diag::err_typecheck_converted_constant_expression_disallowed)
6510 << From->getType() << From->getSourceRange() << T;
6511 }
6512 // [...] and where the reference binding (if any) binds directly.
6513 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6514 return S.Diag(From->getBeginLoc(),
6515 diag::err_typecheck_converted_constant_expression_indirect)
6516 << From->getType() << From->getSourceRange() << T;
6517 }
6518 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6519 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6520 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6521 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6522 // case explicitly.
6523 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6524 return S.Diag(From->getBeginLoc(),
6525 diag::err_reference_bind_to_bitfield_in_cce)
6526 << From->getSourceRange();
6527 }
6528
6529 // Usually we can simply apply the ImplicitConversionSequence we formed
6530 // earlier, but that's not guaranteed to work when initializing an object of
6531 // class type.
6532 ExprResult Result;
6533 bool IsTemplateArgument =
6535 if (T->isRecordType()) {
6536 assert(IsTemplateArgument &&
6537 "unexpected class type converted constant expr");
6538 Result = S.PerformCopyInitialization(
6541 SourceLocation(), From);
6542 } else {
6543 Result =
6545 }
6546 if (Result.isInvalid())
6547 return Result;
6548
6549 // C++2a [intro.execution]p5:
6550 // A full-expression is [...] a constant-expression [...]
6551 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6552 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6553 IsTemplateArgument);
6554 if (Result.isInvalid())
6555 return Result;
6556
6557 // Check for a narrowing implicit conversion.
6558 bool ReturnPreNarrowingValue = false;
6559 QualType PreNarrowingType;
6560 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6561 PreNarrowingType)) {
6563 // Implicit conversion to a narrower type, and the value is not a constant
6564 // expression. We'll diagnose this in a moment.
6565 case NK_Not_Narrowing:
6566 break;
6567
6569 if (CCE == CCEKind::ArrayBound &&
6570 PreNarrowingType->isIntegralOrEnumerationType() &&
6571 PreNarrowingValue.isInt()) {
6572 // Don't diagnose array bound narrowing here; we produce more precise
6573 // errors by allowing the un-narrowed value through.
6574 ReturnPreNarrowingValue = true;
6575 break;
6576 }
6577 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6578 << CCE << /*Constant*/ 1
6579 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6580 // If this is an SFINAE Context, treat the result as invalid so it stops
6581 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6582 // FIXME: Should do this whenever the above diagnostic is an error, but
6583 // without further changes this would degrade some other diagnostics.
6584 if (S.isSFINAEContext())
6585 return ExprError();
6586 break;
6587
6589 // Implicit conversion to a narrower type, but the expression is
6590 // value-dependent so we can't tell whether it's actually narrowing.
6591 // For matching the parameters of a TTP, the conversion is ill-formed
6592 // if it may narrow.
6593 if (CCE != CCEKind::TempArgStrict)
6594 break;
6595 [[fallthrough]];
6596 case NK_Type_Narrowing:
6597 // FIXME: It would be better to diagnose that the expression is not a
6598 // constant expression.
6599 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6600 << CCE << /*Constant*/ 0 << From->getType() << T;
6601 if (S.isSFINAEContext())
6602 return ExprError();
6603 break;
6604 }
6605 if (!ReturnPreNarrowingValue)
6606 PreNarrowingValue = {};
6607
6608 return Result;
6609}
6610
6611/// CheckConvertedConstantExpression - Check that the expression From is a
6612/// converted constant expression of type T, perform the conversion and produce
6613/// the converted expression, per C++11 [expr.const]p3.
6616 CCEKind CCE, bool RequireInt,
6617 NamedDecl *Dest) {
6618
6619 APValue PreNarrowingValue;
6620 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6621 PreNarrowingValue);
6622 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6623 Value = APValue();
6624 return Result;
6625 }
6626 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6627 RequireInt, PreNarrowingValue);
6628}
6629
6631 CCEKind CCE,
6632 NamedDecl *Dest) {
6633 APValue PreNarrowingValue;
6634 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6635 PreNarrowingValue);
6636}
6637
6639 APValue &Value, CCEKind CCE,
6640 NamedDecl *Dest) {
6641 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6642 Dest);
6643}
6644
6646 llvm::APSInt &Value,
6647 CCEKind CCE) {
6648 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6649
6650 APValue V;
6651 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6652 /*Dest=*/nullptr);
6653 if (!R.isInvalid() && !R.get()->isValueDependent())
6654 Value = V.getInt();
6655 return R;
6656}
6657
6660 CCEKind CCE, bool RequireInt,
6661 const APValue &PreNarrowingValue) {
6662
6663 ExprResult Result = E;
6664 // Check the expression is a constant expression.
6666 Expr::EvalResult Eval;
6667 Eval.Diag = &Notes;
6668
6669 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6670
6671 ConstantExprKind Kind;
6672 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6673 Kind = ConstantExprKind::ClassTemplateArgument;
6674 else if (CCE == CCEKind::TemplateArg)
6675 Kind = ConstantExprKind::NonClassTemplateArgument;
6676 else
6677 Kind = ConstantExprKind::Normal;
6678
6679 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6680 (RequireInt && !Eval.Val.isInt())) {
6681 // The expression can't be folded, so we can't keep it at this position in
6682 // the AST.
6683 Result = ExprError();
6684 } else {
6685 Value = Eval.Val;
6686
6687 if (Notes.empty()) {
6688 // It's a constant expression.
6689 Expr *E = Result.get();
6690 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6691 // We expect a ConstantExpr to have a value associated with it
6692 // by this point.
6693 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6694 "ConstantExpr has no value associated with it");
6695 (void)CE;
6696 } else {
6698 }
6699 if (!PreNarrowingValue.isAbsent())
6700 Value = std::move(PreNarrowingValue);
6701 return E;
6702 }
6703 }
6704
6705 // It's not a constant expression. Produce an appropriate diagnostic.
6706 if (Notes.size() == 1 &&
6707 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6708 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6709 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6710 diag::note_constexpr_invalid_template_arg) {
6711 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6712 for (unsigned I = 0; I < Notes.size(); ++I)
6713 Diag(Notes[I].first, Notes[I].second);
6714 } else {
6715 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6716 << CCE << E->getSourceRange();
6717 for (unsigned I = 0; I < Notes.size(); ++I)
6718 Diag(Notes[I].first, Notes[I].second);
6719 }
6720 return ExprError();
6721}
6722
6723/// dropPointerConversions - If the given standard conversion sequence
6724/// involves any pointer conversions, remove them. This may change
6725/// the result type of the conversion sequence.
6727 if (SCS.Second == ICK_Pointer_Conversion) {
6728 SCS.Second = ICK_Identity;
6729 SCS.Dimension = ICK_Identity;
6730 SCS.Third = ICK_Identity;
6731 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6732 }
6733}
6734
6735/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6736/// convert the expression From to an Objective-C pointer type.
6737static ImplicitConversionSequence
6739 // Do an implicit conversion to 'id'.
6742 = TryImplicitConversion(S, From, Ty,
6743 // FIXME: Are these flags correct?
6744 /*SuppressUserConversions=*/false,
6745 AllowedExplicit::Conversions,
6746 /*InOverloadResolution=*/false,
6747 /*CStyle=*/false,
6748 /*AllowObjCWritebackConversion=*/false,
6749 /*AllowObjCConversionOnExplicit=*/true);
6750
6751 // Strip off any final conversions to 'id'.
6752 switch (ICS.getKind()) {
6757 break;
6758
6761 break;
6762
6765 break;
6766 }
6767
6768 return ICS;
6769}
6770
6772 if (checkPlaceholderForOverload(*this, From))
6773 return ExprError();
6774
6775 QualType Ty = Context.getObjCIdType();
6778 if (!ICS.isBad())
6779 return PerformImplicitConversion(From, Ty, ICS,
6781 return ExprResult();
6782}
6783
6784static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6785 const Expr *Base = nullptr;
6786 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6787 "expected a member expression");
6788
6789 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6790 M && !M->isImplicitAccess())
6791 Base = M->getBase();
6792 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6793 M && !M->isImplicitAccess())
6794 Base = M->getBase();
6795
6796 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6797
6798 if (T->isPointerType())
6799 T = T->getPointeeType();
6800
6801 return T;
6802}
6803
6805 const FunctionDecl *Fun) {
6806 QualType ObjType = Obj->getType();
6807 if (ObjType->isPointerType()) {
6808 ObjType = ObjType->getPointeeType();
6809 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6811 /*CanOverflow=*/false, FPOptionsOverride());
6812 }
6813 return Obj;
6814}
6815
6823
6825 Expr *Object, MultiExprArg &Args,
6826 SmallVectorImpl<Expr *> &NewArgs) {
6827 assert(Method->isExplicitObjectMemberFunction() &&
6828 "Method is not an explicit member function");
6829 assert(NewArgs.empty() && "NewArgs should be empty");
6830
6831 NewArgs.reserve(Args.size() + 1);
6832 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6833 NewArgs.push_back(This);
6834 NewArgs.append(Args.begin(), Args.end());
6835 Args = NewArgs;
6837 Method, Object->getBeginLoc());
6838}
6839
6840/// Determine whether the provided type is an integral type, or an enumeration
6841/// type of a permitted flavor.
6843 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6844 : T->isIntegralOrUnscopedEnumerationType();
6845}
6846
6847static ExprResult
6850 QualType T, UnresolvedSetImpl &ViableConversions) {
6851
6852 if (Converter.Suppress)
6853 return ExprError();
6854
6855 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6856 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6857 CXXConversionDecl *Conv =
6858 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6860 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6861 }
6862 return From;
6863}
6864
6865static bool
6868 QualType T, bool HadMultipleCandidates,
6869 UnresolvedSetImpl &ExplicitConversions) {
6870 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6871 DeclAccessPair Found = ExplicitConversions[0];
6872 CXXConversionDecl *Conversion =
6873 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6874
6875 // The user probably meant to invoke the given explicit
6876 // conversion; use it.
6877 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6878 std::string TypeStr;
6879 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6880
6881 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6883 "static_cast<" + TypeStr + ">(")
6885 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6886 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6887
6888 // If we aren't in a SFINAE context, build a call to the
6889 // explicit conversion function.
6890 if (SemaRef.isSFINAEContext())
6891 return true;
6892
6893 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6894 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6895 HadMultipleCandidates);
6896 if (Result.isInvalid())
6897 return true;
6898
6899 // Replace the conversion with a RecoveryExpr, so we don't try to
6900 // instantiate it later, but can further diagnose here.
6901 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6902 From, Result.get()->getType());
6903 if (Result.isInvalid())
6904 return true;
6905 From = Result.get();
6906 }
6907 return false;
6908}
6909
6910static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6912 QualType T, bool HadMultipleCandidates,
6914 CXXConversionDecl *Conversion =
6915 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6916 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6917
6918 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6919 if (!Converter.SuppressConversion) {
6920 if (SemaRef.isSFINAEContext())
6921 return true;
6922
6923 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6924 << From->getSourceRange();
6925 }
6926
6927 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6928 HadMultipleCandidates);
6929 if (Result.isInvalid())
6930 return true;
6931 // Record usage of conversion in an implicit cast.
6932 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6933 CK_UserDefinedConversion, Result.get(),
6934 nullptr, Result.get()->getValueKind(),
6935 SemaRef.CurFPFeatureOverrides());
6936 return false;
6937}
6938
6940 Sema &SemaRef, SourceLocation Loc, Expr *From,
6942 if (!Converter.match(From->getType()) && !Converter.Suppress)
6943 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6944 << From->getSourceRange();
6945
6946 return SemaRef.DefaultLvalueConversion(From);
6947}
6948
6949static void
6951 UnresolvedSetImpl &ViableConversions,
6952 OverloadCandidateSet &CandidateSet) {
6953 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6954 NamedDecl *D = FoundDecl.getDecl();
6955 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6956 if (isa<UsingShadowDecl>(D))
6957 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6958
6959 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6961 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6962 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6963 continue;
6964 }
6966 SemaRef.AddConversionCandidate(
6967 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6968 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6969 }
6970}
6971
6972/// Attempt to convert the given expression to a type which is accepted
6973/// by the given converter.
6974///
6975/// This routine will attempt to convert an expression of class type to a
6976/// type accepted by the specified converter. In C++11 and before, the class
6977/// must have a single non-explicit conversion function converting to a matching
6978/// type. In C++1y, there can be multiple such conversion functions, but only
6979/// one target type.
6980///
6981/// \param Loc The source location of the construct that requires the
6982/// conversion.
6983///
6984/// \param From The expression we're converting from.
6985///
6986/// \param Converter Used to control and diagnose the conversion process.
6987///
6988/// \returns The expression, converted to an integral or enumeration type if
6989/// successful.
6991 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6992 // We can't perform any more checking for type-dependent expressions.
6993 if (From->isTypeDependent())
6994 return From;
6995
6996 // Process placeholders immediately.
6997 if (From->hasPlaceholderType()) {
6998 ExprResult result = CheckPlaceholderExpr(From);
6999 if (result.isInvalid())
7000 return result;
7001 From = result.get();
7002 }
7003
7004 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7005 ExprResult Converted = DefaultLvalueConversion(From);
7006 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7007 // If the expression already has a matching type, we're golden.
7008 if (Converter.match(T))
7009 return Converted;
7010
7011 // FIXME: Check for missing '()' if T is a function type?
7012
7013 // We can only perform contextual implicit conversions on objects of class
7014 // type.
7015 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7016 if (!RecordTy || !getLangOpts().CPlusPlus) {
7017 if (!Converter.Suppress)
7018 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7019 return From;
7020 }
7021
7022 // We must have a complete class type.
7023 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7024 ContextualImplicitConverter &Converter;
7025 Expr *From;
7026
7027 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7028 : Converter(Converter), From(From) {}
7029
7030 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7031 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7032 }
7033 } IncompleteDiagnoser(Converter, From);
7034
7035 if (Converter.Suppress ? !isCompleteType(Loc, T)
7036 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7037 return From;
7038
7039 // Look for a conversion to an integral or enumeration type.
7041 ViableConversions; // These are *potentially* viable in C++1y.
7042 UnresolvedSet<4> ExplicitConversions;
7043 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7044 ->getDefinitionOrSelf()
7045 ->getVisibleConversionFunctions();
7046
7047 bool HadMultipleCandidates =
7048 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7049
7050 // To check that there is only one target type, in C++1y:
7051 QualType ToType;
7052 bool HasUniqueTargetType = true;
7053
7054 // Collect explicit or viable (potentially in C++1y) conversions.
7055 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7056 NamedDecl *D = (*I)->getUnderlyingDecl();
7057 CXXConversionDecl *Conversion;
7058 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7059 if (ConvTemplate) {
7061 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7062 else
7063 continue; // C++11 does not consider conversion operator templates(?).
7064 } else
7065 Conversion = cast<CXXConversionDecl>(D);
7066
7067 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7068 "Conversion operator templates are considered potentially "
7069 "viable in C++1y");
7070
7071 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7072 if (Converter.match(CurToType) || ConvTemplate) {
7073
7074 if (Conversion->isExplicit()) {
7075 // FIXME: For C++1y, do we need this restriction?
7076 // cf. diagnoseNoViableConversion()
7077 if (!ConvTemplate)
7078 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7079 } else {
7080 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7081 if (ToType.isNull())
7082 ToType = CurToType.getUnqualifiedType();
7083 else if (HasUniqueTargetType &&
7084 (CurToType.getUnqualifiedType() != ToType))
7085 HasUniqueTargetType = false;
7086 }
7087 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7088 }
7089 }
7090 }
7091
7092 if (getLangOpts().CPlusPlus14) {
7093 // C++1y [conv]p6:
7094 // ... An expression e of class type E appearing in such a context
7095 // is said to be contextually implicitly converted to a specified
7096 // type T and is well-formed if and only if e can be implicitly
7097 // converted to a type T that is determined as follows: E is searched
7098 // for conversion functions whose return type is cv T or reference to
7099 // cv T such that T is allowed by the context. There shall be
7100 // exactly one such T.
7101
7102 // If no unique T is found:
7103 if (ToType.isNull()) {
7104 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7105 HadMultipleCandidates,
7106 ExplicitConversions))
7107 return ExprError();
7108 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7109 }
7110
7111 // If more than one unique Ts are found:
7112 if (!HasUniqueTargetType)
7113 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7114 ViableConversions);
7115
7116 // If one unique T is found:
7117 // First, build a candidate set from the previously recorded
7118 // potentially viable conversions.
7120 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7121 CandidateSet);
7122
7123 // Then, perform overload resolution over the candidate set.
7125 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7126 case OR_Success: {
7127 // Apply this conversion.
7129 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7130 if (recordConversion(*this, Loc, From, Converter, T,
7131 HadMultipleCandidates, Found))
7132 return ExprError();
7133 break;
7134 }
7135 case OR_Ambiguous:
7136 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7137 ViableConversions);
7139 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7140 HadMultipleCandidates,
7141 ExplicitConversions))
7142 return ExprError();
7143 [[fallthrough]];
7144 case OR_Deleted:
7145 // We'll complain below about a non-integral condition type.
7146 break;
7147 }
7148 } else {
7149 switch (ViableConversions.size()) {
7150 case 0: {
7151 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7152 HadMultipleCandidates,
7153 ExplicitConversions))
7154 return ExprError();
7155
7156 // We'll complain below about a non-integral condition type.
7157 break;
7158 }
7159 case 1: {
7160 // Apply this conversion.
7161 DeclAccessPair Found = ViableConversions[0];
7162 if (recordConversion(*this, Loc, From, Converter, T,
7163 HadMultipleCandidates, Found))
7164 return ExprError();
7165 break;
7166 }
7167 default:
7168 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7169 ViableConversions);
7170 }
7171 }
7172
7173 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7174}
7175
7176/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7177/// an acceptable non-member overloaded operator for a call whose
7178/// arguments have types T1 (and, if non-empty, T2). This routine
7179/// implements the check in C++ [over.match.oper]p3b2 concerning
7180/// enumeration types.
7182 FunctionDecl *Fn,
7183 ArrayRef<Expr *> Args) {
7184 QualType T1 = Args[0]->getType();
7185 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7186
7187 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7188 return true;
7189
7190 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7191 return true;
7192
7193 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7194 if (Proto->getNumParams() < 1)
7195 return false;
7196
7197 if (T1->isEnumeralType()) {
7198 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7199 if (Context.hasSameUnqualifiedType(T1, ArgType))
7200 return true;
7201 }
7202
7203 if (Proto->getNumParams() < 2)
7204 return false;
7205
7206 if (!T2.isNull() && T2->isEnumeralType()) {
7207 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7208 if (Context.hasSameUnqualifiedType(T2, ArgType))
7209 return true;
7210 }
7211
7212 return false;
7213}
7214
7217 return false;
7218
7219 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7220 return FD->isTargetMultiVersion();
7221
7222 if (!FD->isMultiVersion())
7223 return false;
7224
7225 // Among multiple target versions consider either the default,
7226 // or the first non-default in the absence of default version.
7227 unsigned SeenAt = 0;
7228 unsigned I = 0;
7229 bool HasDefault = false;
7231 FD, [&](const FunctionDecl *CurFD) {
7232 if (FD == CurFD)
7233 SeenAt = I;
7234 else if (CurFD->isTargetMultiVersionDefault())
7235 HasDefault = true;
7236 ++I;
7237 });
7238 return HasDefault || SeenAt != 0;
7239}
7240
7243 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7244 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7245 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7246 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7247 bool StrictPackMatch) {
7248 const FunctionProtoType *Proto
7249 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7250 assert(Proto && "Functions without a prototype cannot be overloaded");
7251 assert(!Function->getDescribedFunctionTemplate() &&
7252 "Use AddTemplateOverloadCandidate for function templates");
7253
7254 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7256 // If we get here, it's because we're calling a member function
7257 // that is named without a member access expression (e.g.,
7258 // "this->f") that was either written explicitly or created
7259 // implicitly. This can happen with a qualified call to a member
7260 // function, e.g., X::f(). We use an empty type for the implied
7261 // object argument (C++ [over.call.func]p3), and the acting context
7262 // is irrelevant.
7263 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7265 CandidateSet, SuppressUserConversions,
7266 PartialOverloading, EarlyConversions, PO,
7267 StrictPackMatch);
7268 return;
7269 }
7270 // We treat a constructor like a non-member function, since its object
7271 // argument doesn't participate in overload resolution.
7272 }
7273
7274 if (!CandidateSet.isNewCandidate(Function, PO))
7275 return;
7276
7277 // C++11 [class.copy]p11: [DR1402]
7278 // A defaulted move constructor that is defined as deleted is ignored by
7279 // overload resolution.
7280 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7281 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7282 Constructor->isMoveConstructor())
7283 return;
7284
7285 // Overload resolution is always an unevaluated context.
7288
7289 // C++ [over.match.oper]p3:
7290 // if no operand has a class type, only those non-member functions in the
7291 // lookup set that have a first parameter of type T1 or "reference to
7292 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7293 // is a right operand) a second parameter of type T2 or "reference to
7294 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7295 // candidate functions.
7296 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7298 return;
7299
7300 // Add this candidate
7301 OverloadCandidate &Candidate =
7302 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7303 Candidate.FoundDecl = FoundDecl;
7304 Candidate.Function = Function;
7305 Candidate.Viable = true;
7306 Candidate.RewriteKind =
7307 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7308 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7309 Candidate.ExplicitCallArguments = Args.size();
7310 Candidate.StrictPackMatch = StrictPackMatch;
7311
7312 // Explicit functions are not actually candidates at all if we're not
7313 // allowing them in this context, but keep them around so we can point
7314 // to them in diagnostics.
7315 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7316 Candidate.Viable = false;
7317 Candidate.FailureKind = ovl_fail_explicit;
7318 return;
7319 }
7320
7321 // Functions with internal linkage are only viable in the same module unit.
7322 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7323 /// FIXME: Currently, the semantics of linkage in clang is slightly
7324 /// different from the semantics in C++ spec. In C++ spec, only names
7325 /// have linkage. So that all entities of the same should share one
7326 /// linkage. But in clang, different entities of the same could have
7327 /// different linkage.
7328 const NamedDecl *ND = Function;
7329 bool IsImplicitlyInstantiated = false;
7330 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7331 ND = SpecInfo->getTemplate();
7332 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7334 }
7335
7336 /// Don't remove inline functions with internal linkage from the overload
7337 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7338 /// However:
7339 /// - Inline functions with internal linkage are a common pattern in
7340 /// headers to avoid ODR issues.
7341 /// - The global module is meant to be a transition mechanism for C and C++
7342 /// headers, and the current rules as written work against that goal.
7343 const bool IsInlineFunctionInGMF =
7344 Function->isFromGlobalModule() &&
7345 (IsImplicitlyInstantiated || Function->isInlined());
7346
7347 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7348 Candidate.Viable = false;
7350 return;
7351 }
7352 }
7353
7355 Candidate.Viable = false;
7357 return;
7358 }
7359
7360 if (Constructor) {
7361 // C++ [class.copy]p3:
7362 // A member function template is never instantiated to perform the copy
7363 // of a class object to an object of its class type.
7364 CanQualType ClassType =
7365 Context.getCanonicalTagType(Constructor->getParent());
7366 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7367 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7368 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7369 ClassType))) {
7370 Candidate.Viable = false;
7372 return;
7373 }
7374
7375 // C++ [over.match.funcs]p8: (proposed DR resolution)
7376 // A constructor inherited from class type C that has a first parameter
7377 // of type "reference to P" (including such a constructor instantiated
7378 // from a template) is excluded from the set of candidate functions when
7379 // constructing an object of type cv D if the argument list has exactly
7380 // one argument and D is reference-related to P and P is reference-related
7381 // to C.
7382 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7383 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7384 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7385 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7386 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7387 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7388 SourceLocation Loc = Args.front()->getExprLoc();
7389 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7390 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7391 Candidate.Viable = false;
7393 return;
7394 }
7395 }
7396
7397 // Check that the constructor is capable of constructing an object in the
7398 // destination address space.
7400 Constructor->getMethodQualifiers().getAddressSpace(),
7401 CandidateSet.getDestAS(), getASTContext())) {
7402 Candidate.Viable = false;
7404 }
7405 }
7406
7407 unsigned NumParams = Proto->getNumParams();
7408
7409 // (C++ 13.3.2p2): A candidate function having fewer than m
7410 // parameters is viable only if it has an ellipsis in its parameter
7411 // list (8.3.5).
7412 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7413 !Proto->isVariadic() &&
7414 shouldEnforceArgLimit(PartialOverloading, Function)) {
7415 Candidate.Viable = false;
7417 return;
7418 }
7419
7420 // (C++ 13.3.2p2): A candidate function having more than m parameters
7421 // is viable only if the (m+1)st parameter has a default argument
7422 // (8.3.6). For the purposes of overload resolution, the
7423 // parameter list is truncated on the right, so that there are
7424 // exactly m parameters.
7425 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7426 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7427 !PartialOverloading) {
7428 // Not enough arguments.
7429 Candidate.Viable = false;
7431 return;
7432 }
7433
7434 // (CUDA B.1): Check for invalid calls between targets.
7435 if (getLangOpts().CUDA) {
7436 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7437 // Skip the check for callers that are implicit members, because in this
7438 // case we may not yet know what the member's target is; the target is
7439 // inferred for the member automatically, based on the bases and fields of
7440 // the class.
7441 if (!(Caller && Caller->isImplicit()) &&
7442 !CUDA().IsAllowedCall(Caller, Function)) {
7443 Candidate.Viable = false;
7444 Candidate.FailureKind = ovl_fail_bad_target;
7445 return;
7446 }
7447 }
7448
7449 if (Function->getTrailingRequiresClause()) {
7450 ConstraintSatisfaction Satisfaction;
7451 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7452 /*ForOverloadResolution*/ true) ||
7453 !Satisfaction.IsSatisfied) {
7454 Candidate.Viable = false;
7456 return;
7457 }
7458 }
7459
7460 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7461 // Determine the implicit conversion sequences for each of the
7462 // arguments.
7463 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7464 unsigned ConvIdx =
7465 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7466 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7467 // We already formed a conversion sequence for this parameter during
7468 // template argument deduction.
7469 } else if (ArgIdx < NumParams) {
7470 // (C++ 13.3.2p3): for F to be a viable function, there shall
7471 // exist for each argument an implicit conversion sequence
7472 // (13.3.3.1) that converts that argument to the corresponding
7473 // parameter of F.
7474 QualType ParamType = Proto->getParamType(ArgIdx);
7475 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7476 if (ParamABI == ParameterABI::HLSLOut ||
7477 ParamABI == ParameterABI::HLSLInOut)
7478 ParamType = ParamType.getNonReferenceType();
7479 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7480 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7481 /*InOverloadResolution=*/true,
7482 /*AllowObjCWritebackConversion=*/
7483 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7484 if (Candidate.Conversions[ConvIdx].isBad()) {
7485 Candidate.Viable = false;
7487 return;
7488 }
7489 } else {
7490 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7491 // argument for which there is no corresponding parameter is
7492 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7493 Candidate.Conversions[ConvIdx].setEllipsis();
7494 }
7495 }
7496
7497 if (EnableIfAttr *FailedAttr =
7498 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7499 Candidate.Viable = false;
7500 Candidate.FailureKind = ovl_fail_enable_if;
7501 Candidate.DeductionFailure.Data = FailedAttr;
7502 return;
7503 }
7504}
7505
7509 if (Methods.size() <= 1)
7510 return nullptr;
7511
7512 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7513 bool Match = true;
7514 ObjCMethodDecl *Method = Methods[b];
7515 unsigned NumNamedArgs = Sel.getNumArgs();
7516 // Method might have more arguments than selector indicates. This is due
7517 // to addition of c-style arguments in method.
7518 if (Method->param_size() > NumNamedArgs)
7519 NumNamedArgs = Method->param_size();
7520 if (Args.size() < NumNamedArgs)
7521 continue;
7522
7523 for (unsigned i = 0; i < NumNamedArgs; i++) {
7524 // We can't do any type-checking on a type-dependent argument.
7525 if (Args[i]->isTypeDependent()) {
7526 Match = false;
7527 break;
7528 }
7529
7530 ParmVarDecl *param = Method->parameters()[i];
7531 Expr *argExpr = Args[i];
7532 assert(argExpr && "SelectBestMethod(): missing expression");
7533
7534 // Strip the unbridged-cast placeholder expression off unless it's
7535 // a consumed argument.
7536 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7537 !param->hasAttr<CFConsumedAttr>())
7538 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7539
7540 // If the parameter is __unknown_anytype, move on to the next method.
7541 if (param->getType() == Context.UnknownAnyTy) {
7542 Match = false;
7543 break;
7544 }
7545
7546 ImplicitConversionSequence ConversionState
7547 = TryCopyInitialization(*this, argExpr, param->getType(),
7548 /*SuppressUserConversions*/false,
7549 /*InOverloadResolution=*/true,
7550 /*AllowObjCWritebackConversion=*/
7551 getLangOpts().ObjCAutoRefCount,
7552 /*AllowExplicit*/false);
7553 // This function looks for a reasonably-exact match, so we consider
7554 // incompatible pointer conversions to be a failure here.
7555 if (ConversionState.isBad() ||
7556 (ConversionState.isStandard() &&
7557 ConversionState.Standard.Second ==
7559 Match = false;
7560 break;
7561 }
7562 }
7563 // Promote additional arguments to variadic methods.
7564 if (Match && Method->isVariadic()) {
7565 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7566 if (Args[i]->isTypeDependent()) {
7567 Match = false;
7568 break;
7569 }
7571 Args[i], VariadicCallType::Method, nullptr);
7572 if (Arg.isInvalid()) {
7573 Match = false;
7574 break;
7575 }
7576 }
7577 } else {
7578 // Check for extra arguments to non-variadic methods.
7579 if (Args.size() != NumNamedArgs)
7580 Match = false;
7581 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7582 // Special case when selectors have no argument. In this case, select
7583 // one with the most general result type of 'id'.
7584 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7585 QualType ReturnT = Methods[b]->getReturnType();
7586 if (ReturnT->isObjCIdType())
7587 return Methods[b];
7588 }
7589 }
7590 }
7591
7592 if (Match)
7593 return Method;
7594 }
7595 return nullptr;
7596}
7597
7599 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7600 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7601 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7602 if (ThisArg) {
7603 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7604 assert(!isa<CXXConstructorDecl>(Method) &&
7605 "Shouldn't have `this` for ctors!");
7606 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7608 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7609 if (R.isInvalid())
7610 return false;
7611 ConvertedThis = R.get();
7612 } else {
7613 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7614 (void)MD;
7615 assert((MissingImplicitThis || MD->isStatic() ||
7617 "Expected `this` for non-ctor instance methods");
7618 }
7619 ConvertedThis = nullptr;
7620 }
7621
7622 // Ignore any variadic arguments. Converting them is pointless, since the
7623 // user can't refer to them in the function condition.
7624 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7625
7626 // Convert the arguments.
7627 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7628 ExprResult R;
7630 S.Context, Function->getParamDecl(I)),
7631 SourceLocation(), Args[I]);
7632
7633 if (R.isInvalid())
7634 return false;
7635
7636 ConvertedArgs.push_back(R.get());
7637 }
7638
7639 if (Trap.hasErrorOccurred())
7640 return false;
7641
7642 // Push default arguments if needed.
7643 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7644 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7645 ParmVarDecl *P = Function->getParamDecl(i);
7646 if (!P->hasDefaultArg())
7647 return false;
7648 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7649 if (R.isInvalid())
7650 return false;
7651 ConvertedArgs.push_back(R.get());
7652 }
7653
7654 if (Trap.hasErrorOccurred())
7655 return false;
7656 }
7657 return true;
7658}
7659
7661 SourceLocation CallLoc,
7662 ArrayRef<Expr *> Args,
7663 bool MissingImplicitThis) {
7664 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7665 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7666 return nullptr;
7667
7668 SFINAETrap Trap(*this);
7669 // Perform the access checking immediately so any access diagnostics are
7670 // caught by the SFINAE trap.
7671 llvm::scope_exit UndelayDiags(
7672 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7673 DelayedDiagnostics.popUndelayed(CurrentState);
7674 });
7675 SmallVector<Expr *, 16> ConvertedArgs;
7676 // FIXME: We should look into making enable_if late-parsed.
7677 Expr *DiscardedThis;
7679 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7680 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7681 return *EnableIfAttrs.begin();
7682
7683 for (auto *EIA : EnableIfAttrs) {
7685 // FIXME: This doesn't consider value-dependent cases, because doing so is
7686 // very difficult. Ideally, we should handle them more gracefully.
7687 if (EIA->getCond()->isValueDependent() ||
7688 !EIA->getCond()->EvaluateWithSubstitution(
7689 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7690 return EIA;
7691
7692 if (!Result.isInt() || !Result.getInt().getBoolValue())
7693 return EIA;
7694 }
7695 return nullptr;
7696}
7697
7698template <typename CheckFn>
7700 bool ArgDependent, SourceLocation Loc,
7701 CheckFn &&IsSuccessful) {
7703 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7704 if (ArgDependent == DIA->getArgDependent())
7705 Attrs.push_back(DIA);
7706 }
7707
7708 // Common case: No diagnose_if attributes, so we can quit early.
7709 if (Attrs.empty())
7710 return false;
7711
7712 auto WarningBegin = std::stable_partition(
7713 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7714 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7715 DIA->getWarningGroup().empty();
7716 });
7717
7718 // Note that diagnose_if attributes are late-parsed, so they appear in the
7719 // correct order (unlike enable_if attributes).
7720 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7721 IsSuccessful);
7722 if (ErrAttr != WarningBegin) {
7723 const DiagnoseIfAttr *DIA = *ErrAttr;
7724 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7725 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7726 << DIA->getParent() << DIA->getCond()->getSourceRange();
7727 return true;
7728 }
7729
7730 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7731 switch (Sev) {
7732 case DiagnoseIfAttr::DS_warning:
7734 case DiagnoseIfAttr::DS_error:
7735 return diag::Severity::Error;
7736 }
7737 llvm_unreachable("Fully covered switch above!");
7738 };
7739
7740 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7741 if (IsSuccessful(DIA)) {
7742 if (DIA->getWarningGroup().empty() &&
7743 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7744 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7745 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7746 << DIA->getParent() << DIA->getCond()->getSourceRange();
7747 } else {
7748 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7749 DIA->getWarningGroup());
7750 assert(DiagGroup);
7751 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7752 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7753 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7754 S.Diag(Loc, DiagID) << DIA->getMessage();
7755 }
7756 }
7757
7758 return false;
7759}
7760
7762 const Expr *ThisArg,
7764 SourceLocation Loc) {
7766 *this, Function, /*ArgDependent=*/true, Loc,
7767 [&](const DiagnoseIfAttr *DIA) {
7769 // It's sane to use the same Args for any redecl of this function, since
7770 // EvaluateWithSubstitution only cares about the position of each
7771 // argument in the arg list, not the ParmVarDecl* it maps to.
7772 if (!DIA->getCond()->EvaluateWithSubstitution(
7773 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7774 return false;
7775 return Result.isInt() && Result.getInt().getBoolValue();
7776 });
7777}
7778
7780 SourceLocation Loc) {
7782 *this, ND, /*ArgDependent=*/false, Loc,
7783 [&](const DiagnoseIfAttr *DIA) {
7784 bool Result;
7785 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7786 Result;
7787 });
7788}
7789
7791 ArrayRef<Expr *> Args,
7792 OverloadCandidateSet &CandidateSet,
7793 TemplateArgumentListInfo *ExplicitTemplateArgs,
7794 bool SuppressUserConversions,
7795 bool PartialOverloading,
7796 bool FirstArgumentIsBase) {
7797 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7798 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7799 ArrayRef<Expr *> FunctionArgs = Args;
7800
7801 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7802 FunctionDecl *FD =
7803 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7804
7805 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7806 QualType ObjectType;
7807 Expr::Classification ObjectClassification;
7808 if (Args.size() > 0) {
7809 if (Expr *E = Args[0]) {
7810 // Use the explicit base to restrict the lookup:
7811 ObjectType = E->getType();
7812 // Pointers in the object arguments are implicitly dereferenced, so we
7813 // always classify them as l-values.
7814 if (!ObjectType.isNull() && ObjectType->isPointerType())
7815 ObjectClassification = Expr::Classification::makeSimpleLValue();
7816 else
7817 ObjectClassification = E->Classify(Context);
7818 } // .. else there is an implicit base.
7819 FunctionArgs = Args.slice(1);
7820 }
7821 if (FunTmpl) {
7823 FunTmpl, F.getPair(),
7825 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7826 FunctionArgs, CandidateSet, SuppressUserConversions,
7827 PartialOverloading);
7828 } else {
7829 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7830 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7831 ObjectClassification, FunctionArgs, CandidateSet,
7832 SuppressUserConversions, PartialOverloading);
7833 }
7834 } else {
7835 // This branch handles both standalone functions and static methods.
7836
7837 // Slice the first argument (which is the base) when we access
7838 // static method as non-static.
7839 if (Args.size() > 0 &&
7840 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7841 !isa<CXXConstructorDecl>(FD)))) {
7842 assert(cast<CXXMethodDecl>(FD)->isStatic());
7843 FunctionArgs = Args.slice(1);
7844 }
7845 if (FunTmpl) {
7846 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7847 ExplicitTemplateArgs, FunctionArgs,
7848 CandidateSet, SuppressUserConversions,
7849 PartialOverloading);
7850 } else {
7851 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7852 SuppressUserConversions, PartialOverloading);
7853 }
7854 }
7855 }
7856}
7857
7859 Expr::Classification ObjectClassification,
7860 ArrayRef<Expr *> Args,
7861 OverloadCandidateSet &CandidateSet,
7862 bool SuppressUserConversions,
7864 NamedDecl *Decl = FoundDecl.getDecl();
7866
7868 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7869
7870 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7871 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7872 "Expected a member function template");
7873 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7874 /*ExplicitArgs*/ nullptr, ObjectType,
7875 ObjectClassification, Args, CandidateSet,
7876 SuppressUserConversions, false, PO);
7877 } else {
7878 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7879 ObjectType, ObjectClassification, Args, CandidateSet,
7880 SuppressUserConversions, false, {}, PO);
7881 }
7882}
7883
7886 CXXRecordDecl *ActingContext, QualType ObjectType,
7887 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7888 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7889 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7890 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7891 const FunctionProtoType *Proto
7892 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7893 assert(Proto && "Methods without a prototype cannot be overloaded");
7895 "Use AddOverloadCandidate for constructors");
7896
7897 if (!CandidateSet.isNewCandidate(Method, PO))
7898 return;
7899
7900 // C++11 [class.copy]p23: [DR1402]
7901 // A defaulted move assignment operator that is defined as deleted is
7902 // ignored by overload resolution.
7903 if (Method->isDefaulted() && Method->isDeleted() &&
7904 Method->isMoveAssignmentOperator())
7905 return;
7906
7907 // Overload resolution is always an unevaluated context.
7910
7911 bool IgnoreExplicitObject =
7912 (Method->isExplicitObjectMemberFunction() &&
7913 CandidateSet.getKind() ==
7915 bool ImplicitObjectMethodTreatedAsStatic =
7916 CandidateSet.getKind() ==
7918 Method->isImplicitObjectMemberFunction();
7919
7920 unsigned ExplicitOffset =
7921 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7922
7923 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7924 int(ImplicitObjectMethodTreatedAsStatic);
7925
7926 unsigned ExtraArgs =
7928 ? 0
7929 : 1;
7930
7931 // Add this candidate
7932 OverloadCandidate &Candidate =
7933 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7934 Candidate.FoundDecl = FoundDecl;
7935 Candidate.Function = Method;
7936 Candidate.RewriteKind =
7937 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7938 Candidate.TookAddressOfOverload =
7940 Candidate.ExplicitCallArguments = Args.size();
7941 Candidate.StrictPackMatch = StrictPackMatch;
7942
7943 // (C++ 13.3.2p2): A candidate function having fewer than m
7944 // parameters is viable only if it has an ellipsis in its parameter
7945 // list (8.3.5).
7946 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7947 !Proto->isVariadic() &&
7948 shouldEnforceArgLimit(PartialOverloading, Method)) {
7949 Candidate.Viable = false;
7951 return;
7952 }
7953
7954 // (C++ 13.3.2p2): A candidate function having more than m parameters
7955 // is viable only if the (m+1)st parameter has a default argument
7956 // (8.3.6). For the purposes of overload resolution, the
7957 // parameter list is truncated on the right, so that there are
7958 // exactly m parameters.
7959 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7960 ExplicitOffset +
7961 int(ImplicitObjectMethodTreatedAsStatic);
7962
7963 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7964 // Not enough arguments.
7965 Candidate.Viable = false;
7967 return;
7968 }
7969
7970 Candidate.Viable = true;
7971
7972 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7973 if (!IgnoreExplicitObject) {
7974 if (ObjectType.isNull())
7975 Candidate.IgnoreObjectArgument = true;
7976 else if (Method->isStatic()) {
7977 // [over.best.ics.general]p8
7978 // When the parameter is the implicit object parameter of a static member
7979 // function, the implicit conversion sequence is a standard conversion
7980 // sequence that is neither better nor worse than any other standard
7981 // conversion sequence.
7982 //
7983 // This is a rule that was introduced in C++23 to support static lambdas.
7984 // We apply it retroactively because we want to support static lambdas as
7985 // an extension and it doesn't hurt previous code.
7986 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7987 } else {
7988 // Determine the implicit conversion sequence for the object
7989 // parameter.
7990 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7991 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7992 Method, ActingContext, /*InOverloadResolution=*/true);
7993 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7994 Candidate.Viable = false;
7996 return;
7997 }
7998 }
7999 }
8000
8001 // (CUDA B.1): Check for invalid calls between targets.
8002 if (getLangOpts().CUDA)
8003 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8004 Method)) {
8005 Candidate.Viable = false;
8006 Candidate.FailureKind = ovl_fail_bad_target;
8007 return;
8008 }
8009
8010 if (Method->getTrailingRequiresClause()) {
8011 ConstraintSatisfaction Satisfaction;
8012 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8013 /*ForOverloadResolution*/ true) ||
8014 !Satisfaction.IsSatisfied) {
8015 Candidate.Viable = false;
8017 return;
8018 }
8019 }
8020
8021 // Determine the implicit conversion sequences for each of the
8022 // arguments.
8023 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8024 unsigned ConvIdx =
8025 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8026 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8027 // We already formed a conversion sequence for this parameter during
8028 // template argument deduction.
8029 } else if (ArgIdx < NumParams) {
8030 // (C++ 13.3.2p3): for F to be a viable function, there shall
8031 // exist for each argument an implicit conversion sequence
8032 // (13.3.3.1) that converts that argument to the corresponding
8033 // parameter of F.
8034 QualType ParamType;
8035 if (ImplicitObjectMethodTreatedAsStatic) {
8036 ParamType = ArgIdx == 0
8037 ? Method->getFunctionObjectParameterReferenceType()
8038 : Proto->getParamType(ArgIdx - 1);
8039 } else {
8040 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8041 }
8042 Candidate.Conversions[ConvIdx]
8043 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8044 SuppressUserConversions,
8045 /*InOverloadResolution=*/true,
8046 /*AllowObjCWritebackConversion=*/
8047 getLangOpts().ObjCAutoRefCount);
8048 if (Candidate.Conversions[ConvIdx].isBad()) {
8049 Candidate.Viable = false;
8051 return;
8052 }
8053 } else {
8054 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8055 // argument for which there is no corresponding parameter is
8056 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8057 Candidate.Conversions[ConvIdx].setEllipsis();
8058 }
8059 }
8060
8061 if (EnableIfAttr *FailedAttr =
8062 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8063 Candidate.Viable = false;
8064 Candidate.FailureKind = ovl_fail_enable_if;
8065 Candidate.DeductionFailure.Data = FailedAttr;
8066 return;
8067 }
8068
8070 Candidate.Viable = false;
8072 }
8073}
8074
8076 Sema &S, OverloadCandidateSet &CandidateSet,
8077 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8078 CXXRecordDecl *ActingContext,
8079 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8080 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8081 bool SuppressUserConversions, bool PartialOverloading,
8083
8084 // C++ [over.match.funcs]p7:
8085 // In each case where a candidate is a function template, candidate
8086 // function template specializations are generated using template argument
8087 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8088 // candidate functions in the usual way.113) A given name can refer to one
8089 // or more function templates and also to a set of overloaded non-template
8090 // functions. In such a case, the candidate functions generated from each
8091 // function template are combined with the set of non-template candidate
8092 // functions.
8093 TemplateDeductionInfo Info(CandidateSet.getLocation());
8094 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8095 FunctionDecl *Specialization = nullptr;
8096 ConversionSequenceList Conversions;
8098 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8099 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8100 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8101 CandidateSet.getKind() ==
8103 [&](ArrayRef<QualType> ParamTypes,
8104 bool OnlyInitializeNonUserDefinedConversions) {
8105 return S.CheckNonDependentConversions(
8106 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8107 Sema::CheckNonDependentConversionsFlag(
8108 SuppressUserConversions,
8109 OnlyInitializeNonUserDefinedConversions),
8110 ActingContext, ObjectType, ObjectClassification, PO);
8111 });
8113 OverloadCandidate &Candidate =
8114 CandidateSet.addCandidate(Conversions.size(), Conversions);
8115 Candidate.FoundDecl = FoundDecl;
8116 Candidate.Function = Method;
8117 Candidate.Viable = false;
8118 Candidate.RewriteKind =
8119 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8120 Candidate.IsSurrogate = false;
8121 Candidate.TookAddressOfOverload =
8122 CandidateSet.getKind() ==
8124
8125 Candidate.IgnoreObjectArgument =
8126 Method->isStatic() ||
8127 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8128 Candidate.ExplicitCallArguments = Args.size();
8131 else {
8133 Candidate.DeductionFailure =
8134 MakeDeductionFailureInfo(S.Context, Result, Info);
8135 }
8136 return;
8137 }
8138
8139 // Add the function template specialization produced by template argument
8140 // deduction as a candidate.
8141 assert(Specialization && "Missing member function template specialization?");
8143 "Specialization is not a member function?");
8145 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8146 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8147 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8148}
8149
8151 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8152 CXXRecordDecl *ActingContext,
8153 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8154 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8155 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8156 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8157 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8158 return;
8159
8160 if (ExplicitTemplateArgs ||
8163 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8164 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8165 SuppressUserConversions, PartialOverloading, PO);
8166 return;
8167 }
8168
8170 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8171 Args, SuppressUserConversions, PartialOverloading, PO);
8172}
8173
8174/// Determine whether a given function template has a simple explicit specifier
8175/// or a non-value-dependent explicit-specification that evaluates to true.
8179
8184
8186 Sema &S, OverloadCandidateSet &CandidateSet,
8188 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8189 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8191 bool AggregateCandidateDeduction) {
8192
8193 // If the function template has a non-dependent explicit specification,
8194 // exclude it now if appropriate; we are not permitted to perform deduction
8195 // and substitution in this case.
8196 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8197 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8198 Candidate.FoundDecl = FoundDecl;
8199 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8200 Candidate.Viable = false;
8201 Candidate.FailureKind = ovl_fail_explicit;
8202 return;
8203 }
8204
8205 // C++ [over.match.funcs]p7:
8206 // In each case where a candidate is a function template, candidate
8207 // function template specializations are generated using template argument
8208 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8209 // candidate functions in the usual way.113) A given name can refer to one
8210 // or more function templates and also to a set of overloaded non-template
8211 // functions. In such a case, the candidate functions generated from each
8212 // function template are combined with the set of non-template candidate
8213 // functions.
8214 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8215 FunctionTemplate->getTemplateDepth());
8216 FunctionDecl *Specialization = nullptr;
8217 ConversionSequenceList Conversions;
8219 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8220 PartialOverloading, AggregateCandidateDeduction,
8221 /*PartialOrdering=*/false,
8222 /*ObjectType=*/QualType(),
8223 /*ObjectClassification=*/Expr::Classification(),
8224 CandidateSet.getKind() ==
8226 [&](ArrayRef<QualType> ParamTypes,
8227 bool OnlyInitializeNonUserDefinedConversions) {
8228 return S.CheckNonDependentConversions(
8229 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8230 Sema::CheckNonDependentConversionsFlag(
8231 SuppressUserConversions,
8232 OnlyInitializeNonUserDefinedConversions),
8233 nullptr, QualType(), {}, PO);
8234 });
8236 OverloadCandidate &Candidate =
8237 CandidateSet.addCandidate(Conversions.size(), Conversions);
8238 Candidate.FoundDecl = FoundDecl;
8239 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8240 Candidate.Viable = false;
8241 Candidate.RewriteKind =
8242 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8243 Candidate.IsSurrogate = false;
8244 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8245 // Ignore the object argument if there is one, since we don't have an object
8246 // type.
8247 Candidate.TookAddressOfOverload =
8248 CandidateSet.getKind() ==
8250
8251 Candidate.IgnoreObjectArgument =
8252 isa<CXXMethodDecl>(Candidate.Function) &&
8253 !cast<CXXMethodDecl>(Candidate.Function)
8254 ->isExplicitObjectMemberFunction() &&
8256
8257 Candidate.ExplicitCallArguments = Args.size();
8260 else {
8262 Candidate.DeductionFailure =
8264 }
8265 return;
8266 }
8267
8268 // Add the function template specialization produced by template argument
8269 // deduction as a candidate.
8270 assert(Specialization && "Missing function template specialization?");
8272 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8273 PartialOverloading, AllowExplicit,
8274 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8275 Info.AggregateDeductionCandidateHasMismatchedArity,
8276 Info.hasStrictPackMatch());
8277}
8278
8281 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8282 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8283 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8284 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8285 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8286 return;
8287
8288 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8289
8290 if (ExplicitTemplateArgs ||
8292 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8293 DependentExplicitSpecifier)) {
8294
8296 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8297 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8298 IsADLCandidate, PO, AggregateCandidateDeduction);
8299
8300 if (DependentExplicitSpecifier)
8302 return;
8303 }
8304
8305 CandidateSet.AddDeferredTemplateCandidate(
8306 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8307 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8308 AggregateCandidateDeduction);
8309}
8310
8313 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8315 CheckNonDependentConversionsFlag UserConversionFlag,
8316 CXXRecordDecl *ActingContext, QualType ObjectType,
8317 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8318 // FIXME: The cases in which we allow explicit conversions for constructor
8319 // arguments never consider calling a constructor template. It's not clear
8320 // that is correct.
8321 const bool AllowExplicit = false;
8322
8323 bool ForOverloadSetAddressResolution =
8325 auto *FD = FunctionTemplate->getTemplatedDecl();
8326 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8327 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8329 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8330
8331 if (Conversions.empty())
8332 Conversions =
8333 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8334
8335 // Overload resolution is always an unevaluated context.
8338
8339 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8340 // require that, but this check should never result in a hard error, and
8341 // overload resolution is permitted to sidestep instantiations.
8342 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8343 !ObjectType.isNull()) {
8344 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8345 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8346 !ParamTypes[0]->isDependentType()) {
8348 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8349 Method, ActingContext, /*InOverloadResolution=*/true,
8350 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8351 : QualType());
8352 if (Conversions[ConvIdx].isBad())
8353 return true;
8354 }
8355 }
8356
8357 // A speculative workaround for self-dependent constraint bugs that manifest
8358 // after CWG2369.
8359 // FIXME: Add references to the standard once P3606 is adopted.
8360 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8361 QualType ArgType) {
8362 ParamType = ParamType.getNonReferenceType();
8363 ArgType = ArgType.getNonReferenceType();
8364 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8365 if (PointerConv) {
8366 ParamType = ParamType->getPointeeType();
8367 ArgType = ArgType->getPointeeType();
8368 }
8369
8370 if (auto *RD = ParamType->getAsCXXRecordDecl();
8371 RD && RD->hasDefinition() &&
8372 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8373 auto Info = getConstructorInfo(ND);
8374 if (!Info)
8375 return false;
8376 CXXConstructorDecl *Ctor = Info.Constructor;
8377 /// isConvertingConstructor takes copy/move constructors into
8378 /// account!
8379 return !Ctor->isCopyOrMoveConstructor() &&
8381 /*AllowExplicit=*/true);
8382 }))
8383 return true;
8384 if (auto *RD = ArgType->getAsCXXRecordDecl();
8385 RD && RD->hasDefinition() &&
8386 !RD->getVisibleConversionFunctions().empty())
8387 return true;
8388
8389 return false;
8390 };
8391
8392 unsigned Offset =
8393 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8394 : 0;
8395
8396 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8397 I != N; ++I) {
8398 QualType ParamType = ParamTypes[I + Offset];
8399 if (!ParamType->isDependentType()) {
8400 unsigned ConvIdx;
8402 ConvIdx = Args.size() - 1 - I;
8403 assert(Args.size() + ThisConversions == 2 &&
8404 "number of args (including 'this') must be exactly 2 for "
8405 "reversed order");
8406 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8407 // would also be 0. 'this' got ConvIdx = 1 previously.
8408 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8409 } else {
8410 // For members, 'this' got ConvIdx = 0 previously.
8411 ConvIdx = ThisConversions + I;
8412 }
8413 if (Conversions[ConvIdx].isInitialized())
8414 continue;
8415 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8416 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8417 continue;
8419 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8420 /*InOverloadResolution=*/true,
8421 /*AllowObjCWritebackConversion=*/
8422 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8423 if (Conversions[ConvIdx].isBad())
8424 return true;
8425 }
8426 }
8427
8428 return false;
8429}
8430
8431/// Determine whether this is an allowable conversion from the result
8432/// of an explicit conversion operator to the expected type, per C++
8433/// [over.match.conv]p1 and [over.match.ref]p1.
8434///
8435/// \param ConvType The return type of the conversion function.
8436///
8437/// \param ToType The type we are converting to.
8438///
8439/// \param AllowObjCPointerConversion Allow a conversion from one
8440/// Objective-C pointer to another.
8441///
8442/// \returns true if the conversion is allowable, false otherwise.
8444 QualType ConvType, QualType ToType,
8445 bool AllowObjCPointerConversion) {
8446 QualType ToNonRefType = ToType.getNonReferenceType();
8447
8448 // Easy case: the types are the same.
8449 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8450 return true;
8451
8452 // Allow qualification conversions.
8453 bool ObjCLifetimeConversion;
8454 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8455 ObjCLifetimeConversion))
8456 return true;
8457
8458 // If we're not allowed to consider Objective-C pointer conversions,
8459 // we're done.
8460 if (!AllowObjCPointerConversion)
8461 return false;
8462
8463 // Is this an Objective-C pointer conversion?
8464 bool IncompatibleObjC = false;
8465 QualType ConvertedType;
8466 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8467 IncompatibleObjC);
8468}
8469
8471 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8472 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8473 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8474 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8475 assert(!Conversion->getDescribedFunctionTemplate() &&
8476 "Conversion function templates use AddTemplateConversionCandidate");
8477 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8478 if (!CandidateSet.isNewCandidate(Conversion))
8479 return;
8480
8481 // If the conversion function has an undeduced return type, trigger its
8482 // deduction now.
8483 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8484 if (DeduceReturnType(Conversion, From->getExprLoc()))
8485 return;
8486 ConvType = Conversion->getConversionType().getNonReferenceType();
8487 }
8488
8489 // If we don't allow any conversion of the result type, ignore conversion
8490 // functions that don't convert to exactly (possibly cv-qualified) T.
8491 if (!AllowResultConversion &&
8492 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8493 return;
8494
8495 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8496 // operator is only a candidate if its return type is the target type or
8497 // can be converted to the target type with a qualification conversion.
8498 //
8499 // FIXME: Include such functions in the candidate list and explain why we
8500 // can't select them.
8501 if (Conversion->isExplicit() &&
8502 !isAllowableExplicitConversion(*this, ConvType, ToType,
8503 AllowObjCConversionOnExplicit))
8504 return;
8505
8506 // Overload resolution is always an unevaluated context.
8509
8510 // Add this candidate
8511 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8512 Candidate.FoundDecl = FoundDecl;
8513 Candidate.Function = Conversion;
8515 Candidate.FinalConversion.setFromType(ConvType);
8516 Candidate.FinalConversion.setAllToTypes(ToType);
8517 Candidate.HasFinalConversion = true;
8518 Candidate.Viable = true;
8519 Candidate.ExplicitCallArguments = 1;
8520 Candidate.StrictPackMatch = StrictPackMatch;
8521
8522 // Explicit functions are not actually candidates at all if we're not
8523 // allowing them in this context, but keep them around so we can point
8524 // to them in diagnostics.
8525 if (!AllowExplicit && Conversion->isExplicit()) {
8526 Candidate.Viable = false;
8527 Candidate.FailureKind = ovl_fail_explicit;
8528 return;
8529 }
8530
8531 // C++ [over.match.funcs]p4:
8532 // For conversion functions, the function is considered to be a member of
8533 // the class of the implicit implied object argument for the purpose of
8534 // defining the type of the implicit object parameter.
8535 //
8536 // Determine the implicit conversion sequence for the implicit
8537 // object parameter.
8538 QualType ObjectType = From->getType();
8539 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8540 ObjectType = FromPtrType->getPointeeType();
8541 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8542 // C++23 [over.best.ics.general]
8543 // However, if the target is [...]
8544 // - the object parameter of a user-defined conversion function
8545 // [...] user-defined conversion sequences are not considered.
8547 *this, CandidateSet.getLocation(), From->getType(),
8548 From->Classify(Context), Conversion, ConversionContext,
8549 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8550 /*SuppressUserConversion*/ true);
8551
8552 if (Candidate.Conversions[0].isBad()) {
8553 Candidate.Viable = false;
8555 return;
8556 }
8557
8558 if (Conversion->getTrailingRequiresClause()) {
8559 ConstraintSatisfaction Satisfaction;
8560 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8561 !Satisfaction.IsSatisfied) {
8562 Candidate.Viable = false;
8564 return;
8565 }
8566 }
8567
8568 // We won't go through a user-defined type conversion function to convert a
8569 // derived to base as such conversions are given Conversion Rank. They only
8570 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8571 QualType FromCanon
8572 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8573 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8574 if (FromCanon == ToCanon ||
8575 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8576 Candidate.Viable = false;
8578 return;
8579 }
8580
8581 // To determine what the conversion from the result of calling the
8582 // conversion function to the type we're eventually trying to
8583 // convert to (ToType), we need to synthesize a call to the
8584 // conversion function and attempt copy initialization from it. This
8585 // makes sure that we get the right semantics with respect to
8586 // lvalues/rvalues and the type. Fortunately, we can allocate this
8587 // call on the stack and we don't need its arguments to be
8588 // well-formed.
8589 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8590 VK_LValue, From->getBeginLoc());
8592 Context.getPointerType(Conversion->getType()),
8593 CK_FunctionToPointerDecay, &ConversionRef,
8595
8596 QualType ConversionType = Conversion->getConversionType();
8597 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8598 Candidate.Viable = false;
8600 return;
8601 }
8602
8603 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8604
8605 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8606
8607 // Introduce a temporary expression with the right type and value category
8608 // that we can use for deduction purposes.
8609 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8610
8612 TryCopyInitialization(*this, &FakeCall, ToType,
8613 /*SuppressUserConversions=*/true,
8614 /*InOverloadResolution=*/false,
8615 /*AllowObjCWritebackConversion=*/false);
8616
8617 switch (ICS.getKind()) {
8619 Candidate.FinalConversion = ICS.Standard;
8620 Candidate.HasFinalConversion = true;
8621
8622 // C++ [over.ics.user]p3:
8623 // If the user-defined conversion is specified by a specialization of a
8624 // conversion function template, the second standard conversion sequence
8625 // shall have exact match rank.
8626 if (Conversion->getPrimaryTemplate() &&
8628 Candidate.Viable = false;
8630 return;
8631 }
8632
8633 // C++0x [dcl.init.ref]p5:
8634 // In the second case, if the reference is an rvalue reference and
8635 // the second standard conversion sequence of the user-defined
8636 // conversion sequence includes an lvalue-to-rvalue conversion, the
8637 // program is ill-formed.
8638 if (ToType->isRValueReferenceType() &&
8640 Candidate.Viable = false;
8642 return;
8643 }
8644 break;
8645
8647 Candidate.Viable = false;
8649 return;
8650
8651 default:
8652 llvm_unreachable(
8653 "Can only end up with a standard conversion sequence or failure");
8654 }
8655
8656 if (EnableIfAttr *FailedAttr =
8657 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8658 Candidate.Viable = false;
8659 Candidate.FailureKind = ovl_fail_enable_if;
8660 Candidate.DeductionFailure.Data = FailedAttr;
8661 return;
8662 }
8663
8664 if (isNonViableMultiVersionOverload(Conversion)) {
8665 Candidate.Viable = false;
8667 }
8668}
8669
8671 Sema &S, OverloadCandidateSet &CandidateSet,
8673 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8674 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8675 bool AllowResultConversion) {
8676
8677 // If the function template has a non-dependent explicit specification,
8678 // exclude it now if appropriate; we are not permitted to perform deduction
8679 // and substitution in this case.
8680 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8681 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8682 Candidate.FoundDecl = FoundDecl;
8683 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8684 Candidate.Viable = false;
8685 Candidate.FailureKind = ovl_fail_explicit;
8686 return;
8687 }
8688
8689 QualType ObjectType = From->getType();
8690 Expr::Classification ObjectClassification = From->Classify(S.Context);
8691
8692 TemplateDeductionInfo Info(CandidateSet.getLocation());
8695 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8696 Specialization, Info);
8698 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8699 Candidate.FoundDecl = FoundDecl;
8700 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8701 Candidate.Viable = false;
8703 Candidate.ExplicitCallArguments = 1;
8704 Candidate.DeductionFailure =
8705 MakeDeductionFailureInfo(S.Context, Result, Info);
8706 return;
8707 }
8708
8709 // Add the conversion function template specialization produced by
8710 // template argument deduction as a candidate.
8711 assert(Specialization && "Missing function template specialization?");
8712 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8713 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8714 AllowExplicit, AllowResultConversion,
8715 Info.hasStrictPackMatch());
8716}
8717
8720 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8721 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8722 bool AllowExplicit, bool AllowResultConversion) {
8723 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8724 "Only conversion function templates permitted here");
8725
8726 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8727 return;
8728
8730 CandidateSet.getKind() ==
8734 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8735 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8736 AllowResultConversion);
8737
8739 return;
8740 }
8741
8743 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8744 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8745}
8746
8748 DeclAccessPair FoundDecl,
8749 CXXRecordDecl *ActingContext,
8750 const FunctionProtoType *Proto,
8751 Expr *Object,
8752 ArrayRef<Expr *> Args,
8753 OverloadCandidateSet& CandidateSet) {
8754 if (!CandidateSet.isNewCandidate(Conversion))
8755 return;
8756
8757 // Overload resolution is always an unevaluated context.
8760
8761 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8762 Candidate.FoundDecl = FoundDecl;
8763 Candidate.Function = nullptr;
8764 Candidate.Surrogate = Conversion;
8765 Candidate.IsSurrogate = true;
8766 Candidate.Viable = true;
8767 Candidate.ExplicitCallArguments = Args.size();
8768
8769 // Determine the implicit conversion sequence for the implicit
8770 // object parameter.
8771 ImplicitConversionSequence ObjectInit;
8772 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8773 ObjectInit = TryCopyInitialization(*this, Object,
8774 Conversion->getParamDecl(0)->getType(),
8775 /*SuppressUserConversions=*/false,
8776 /*InOverloadResolution=*/true, false);
8777 } else {
8779 *this, CandidateSet.getLocation(), Object->getType(),
8780 Object->Classify(Context), Conversion, ActingContext);
8781 }
8782
8783 if (ObjectInit.isBad()) {
8784 Candidate.Viable = false;
8786 Candidate.Conversions[0] = ObjectInit;
8787 return;
8788 }
8789
8790 // The first conversion is actually a user-defined conversion whose
8791 // first conversion is ObjectInit's standard conversion (which is
8792 // effectively a reference binding). Record it as such.
8793 Candidate.Conversions[0].setUserDefined();
8794 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8795 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8796 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8797 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8798 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8799 Candidate.Conversions[0].UserDefined.After
8800 = Candidate.Conversions[0].UserDefined.Before;
8801 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8802
8803 // Find the
8804 unsigned NumParams = Proto->getNumParams();
8805
8806 // (C++ 13.3.2p2): A candidate function having fewer than m
8807 // parameters is viable only if it has an ellipsis in its parameter
8808 // list (8.3.5).
8809 if (Args.size() > NumParams && !Proto->isVariadic()) {
8810 Candidate.Viable = false;
8812 return;
8813 }
8814
8815 // Function types don't have any default arguments, so just check if
8816 // we have enough arguments.
8817 if (Args.size() < NumParams) {
8818 // Not enough arguments.
8819 Candidate.Viable = false;
8821 return;
8822 }
8823
8824 // Determine the implicit conversion sequences for each of the
8825 // arguments.
8826 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8827 if (ArgIdx < NumParams) {
8828 // (C++ 13.3.2p3): for F to be a viable function, there shall
8829 // exist for each argument an implicit conversion sequence
8830 // (13.3.3.1) that converts that argument to the corresponding
8831 // parameter of F.
8832 QualType ParamType = Proto->getParamType(ArgIdx);
8833 Candidate.Conversions[ArgIdx + 1]
8834 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8835 /*SuppressUserConversions=*/false,
8836 /*InOverloadResolution=*/false,
8837 /*AllowObjCWritebackConversion=*/
8838 getLangOpts().ObjCAutoRefCount);
8839 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8840 Candidate.Viable = false;
8842 return;
8843 }
8844 } else {
8845 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8846 // argument for which there is no corresponding parameter is
8847 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8848 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8849 }
8850 }
8851
8852 if (Conversion->getTrailingRequiresClause()) {
8853 ConstraintSatisfaction Satisfaction;
8854 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8855 /*ForOverloadResolution*/ true) ||
8856 !Satisfaction.IsSatisfied) {
8857 Candidate.Viable = false;
8859 return;
8860 }
8861 }
8862
8863 if (EnableIfAttr *FailedAttr =
8864 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8865 Candidate.Viable = false;
8866 Candidate.FailureKind = ovl_fail_enable_if;
8867 Candidate.DeductionFailure.Data = FailedAttr;
8868 return;
8869 }
8870}
8871
8873 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8874 OverloadCandidateSet &CandidateSet,
8875 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8876 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8877 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8878 ArrayRef<Expr *> FunctionArgs = Args;
8879
8880 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8881 FunctionDecl *FD =
8882 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8883
8884 // Don't consider rewritten functions if we're not rewriting.
8885 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8886 continue;
8887
8888 assert(!isa<CXXMethodDecl>(FD) &&
8889 "unqualified operator lookup found a member function");
8890
8891 if (FunTmpl) {
8892 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8893 FunctionArgs, CandidateSet);
8894 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8895
8896 // As template candidates are not deduced immediately,
8897 // persist the array in the overload set.
8899 FunctionArgs[1], FunctionArgs[0]);
8900 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8901 Reversed, CandidateSet, false, false, true,
8902 ADLCallKind::NotADL,
8904 }
8905 } else {
8906 if (ExplicitTemplateArgs)
8907 continue;
8908 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8909 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8910 AddOverloadCandidate(FD, F.getPair(),
8911 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8912 false, false, true, false, ADLCallKind::NotADL, {},
8914 }
8915 }
8916}
8917
8919 SourceLocation OpLoc,
8920 ArrayRef<Expr *> Args,
8921 OverloadCandidateSet &CandidateSet,
8923 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8924
8925 // C++ [over.match.oper]p3:
8926 // For a unary operator @ with an operand of a type whose
8927 // cv-unqualified version is T1, and for a binary operator @ with
8928 // a left operand of a type whose cv-unqualified version is T1 and
8929 // a right operand of a type whose cv-unqualified version is T2,
8930 // three sets of candidate functions, designated member
8931 // candidates, non-member candidates and built-in candidates, are
8932 // constructed as follows:
8933 QualType T1 = Args[0]->getType();
8934
8935 // -- If T1 is a complete class type or a class currently being
8936 // defined, the set of member candidates is the result of the
8937 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8938 // the set of member candidates is empty.
8939 if (T1->isRecordType()) {
8940 bool IsComplete = isCompleteType(OpLoc, T1);
8941 auto *T1RD = T1->getAsCXXRecordDecl();
8942 // Complete the type if it can be completed.
8943 // If the type is neither complete nor being defined, bail out now.
8944 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8945 return;
8946
8947 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8948 LookupQualifiedName(Operators, T1RD);
8949 Operators.suppressAccessDiagnostics();
8950
8951 for (LookupResult::iterator Oper = Operators.begin(),
8952 OperEnd = Operators.end();
8953 Oper != OperEnd; ++Oper) {
8954 if (Oper->getAsFunction() &&
8956 !CandidateSet.getRewriteInfo().shouldAddReversed(
8957 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8958 continue;
8959 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8960 Args[0]->Classify(Context), Args.slice(1),
8961 CandidateSet, /*SuppressUserConversion=*/false, PO);
8962 }
8963 }
8964}
8965
8967 OverloadCandidateSet& CandidateSet,
8968 bool IsAssignmentOperator,
8969 unsigned NumContextualBoolArguments) {
8970 // Overload resolution is always an unevaluated context.
8973
8974 // Add this candidate
8975 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8976 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8977 Candidate.Function = nullptr;
8978 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8979
8980 // Determine the implicit conversion sequences for each of the
8981 // arguments.
8982 Candidate.Viable = true;
8983 Candidate.ExplicitCallArguments = Args.size();
8984 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8985 // C++ [over.match.oper]p4:
8986 // For the built-in assignment operators, conversions of the
8987 // left operand are restricted as follows:
8988 // -- no temporaries are introduced to hold the left operand, and
8989 // -- no user-defined conversions are applied to the left
8990 // operand to achieve a type match with the left-most
8991 // parameter of a built-in candidate.
8992 //
8993 // We block these conversions by turning off user-defined
8994 // conversions, since that is the only way that initialization of
8995 // a reference to a non-class type can occur from something that
8996 // is not of the same type.
8997 if (ArgIdx < NumContextualBoolArguments) {
8998 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8999 "Contextual conversion to bool requires bool type");
9000 Candidate.Conversions[ArgIdx]
9001 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9002 } else {
9003 Candidate.Conversions[ArgIdx]
9004 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9005 ArgIdx == 0 && IsAssignmentOperator,
9006 /*InOverloadResolution=*/false,
9007 /*AllowObjCWritebackConversion=*/
9008 getLangOpts().ObjCAutoRefCount);
9009 }
9010 if (Candidate.Conversions[ArgIdx].isBad()) {
9011 Candidate.Viable = false;
9013 break;
9014 }
9015 }
9016}
9017
9018namespace {
9019
9020/// BuiltinCandidateTypeSet - A set of types that will be used for the
9021/// candidate operator functions for built-in operators (C++
9022/// [over.built]). The types are separated into pointer types and
9023/// enumeration types.
9024class BuiltinCandidateTypeSet {
9025 /// TypeSet - A set of types.
9026 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9027
9028 /// PointerTypes - The set of pointer types that will be used in the
9029 /// built-in candidates.
9030 TypeSet PointerTypes;
9031
9032 /// MemberPointerTypes - The set of member pointer types that will be
9033 /// used in the built-in candidates.
9034 TypeSet MemberPointerTypes;
9035
9036 /// EnumerationTypes - The set of enumeration types that will be
9037 /// used in the built-in candidates.
9038 TypeSet EnumerationTypes;
9039
9040 /// The set of vector types that will be used in the built-in
9041 /// candidates.
9042 TypeSet VectorTypes;
9043
9044 /// The set of matrix types that will be used in the built-in
9045 /// candidates.
9046 TypeSet MatrixTypes;
9047
9048 /// The set of _BitInt types that will be used in the built-in candidates.
9049 TypeSet BitIntTypes;
9050
9051 /// A flag indicating non-record types are viable candidates
9052 bool HasNonRecordTypes;
9053
9054 /// A flag indicating whether either arithmetic or enumeration types
9055 /// were present in the candidate set.
9056 bool HasArithmeticOrEnumeralTypes;
9057
9058 /// A flag indicating whether the nullptr type was present in the
9059 /// candidate set.
9060 bool HasNullPtrType;
9061
9062 /// Sema - The semantic analysis instance where we are building the
9063 /// candidate type set.
9064 Sema &SemaRef;
9065
9066 /// Context - The AST context in which we will build the type sets.
9067 ASTContext &Context;
9068
9069 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9070 const Qualifiers &VisibleQuals);
9071 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9072
9073public:
9074 /// iterator - Iterates through the types that are part of the set.
9075 typedef TypeSet::iterator iterator;
9076
9077 BuiltinCandidateTypeSet(Sema &SemaRef)
9078 : HasNonRecordTypes(false),
9079 HasArithmeticOrEnumeralTypes(false),
9080 HasNullPtrType(false),
9081 SemaRef(SemaRef),
9082 Context(SemaRef.Context) { }
9083
9084 void AddTypesConvertedFrom(QualType Ty,
9085 SourceLocation Loc,
9086 bool AllowUserConversions,
9087 bool AllowExplicitConversions,
9088 const Qualifiers &VisibleTypeConversionsQuals);
9089
9090 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9091 llvm::iterator_range<iterator> member_pointer_types() {
9092 return MemberPointerTypes;
9093 }
9094 llvm::iterator_range<iterator> enumeration_types() {
9095 return EnumerationTypes;
9096 }
9097 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9098 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9099 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9100
9101 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9102 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9103 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9104 bool hasNullPtrType() const { return HasNullPtrType; }
9105};
9106
9107} // end anonymous namespace
9108
9109/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9110/// the set of pointer types along with any more-qualified variants of
9111/// that type. For example, if @p Ty is "int const *", this routine
9112/// will add "int const *", "int const volatile *", "int const
9113/// restrict *", and "int const volatile restrict *" to the set of
9114/// pointer types. Returns true if the add of @p Ty itself succeeded,
9115/// false otherwise.
9116///
9117/// FIXME: what to do about extended qualifiers?
9118bool
9119BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9120 const Qualifiers &VisibleQuals) {
9121
9122 // Insert this type.
9123 if (!PointerTypes.insert(Ty))
9124 return false;
9125
9126 QualType PointeeTy;
9127 const PointerType *PointerTy = Ty->getAs<PointerType>();
9128 bool buildObjCPtr = false;
9129 if (!PointerTy) {
9130 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9131 PointeeTy = PTy->getPointeeType();
9132 buildObjCPtr = true;
9133 } else {
9134 PointeeTy = PointerTy->getPointeeType();
9135 }
9136
9137 // Don't add qualified variants of arrays. For one, they're not allowed
9138 // (the qualifier would sink to the element type), and for another, the
9139 // only overload situation where it matters is subscript or pointer +- int,
9140 // and those shouldn't have qualifier variants anyway.
9141 if (PointeeTy->isArrayType())
9142 return true;
9143
9144 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9145 bool hasVolatile = VisibleQuals.hasVolatile();
9146 bool hasRestrict = VisibleQuals.hasRestrict();
9147
9148 // Iterate through all strict supersets of BaseCVR.
9149 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9150 if ((CVR | BaseCVR) != CVR) continue;
9151 // Skip over volatile if no volatile found anywhere in the types.
9152 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9153
9154 // Skip over restrict if no restrict found anywhere in the types, or if
9155 // the type cannot be restrict-qualified.
9156 if ((CVR & Qualifiers::Restrict) &&
9157 (!hasRestrict ||
9158 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9159 continue;
9160
9161 // Build qualified pointee type.
9162 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9163
9164 // Build qualified pointer type.
9165 QualType QPointerTy;
9166 if (!buildObjCPtr)
9167 QPointerTy = Context.getPointerType(QPointeeTy);
9168 else
9169 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9170
9171 // Insert qualified pointer type.
9172 PointerTypes.insert(QPointerTy);
9173 }
9174
9175 return true;
9176}
9177
9178/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9179/// to the set of pointer types along with any more-qualified variants of
9180/// that type. For example, if @p Ty is "int const *", this routine
9181/// will add "int const *", "int const volatile *", "int const
9182/// restrict *", and "int const volatile restrict *" to the set of
9183/// pointer types. Returns true if the add of @p Ty itself succeeded,
9184/// false otherwise.
9185///
9186/// FIXME: what to do about extended qualifiers?
9187bool
9188BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9189 QualType Ty) {
9190 // Insert this type.
9191 if (!MemberPointerTypes.insert(Ty))
9192 return false;
9193
9194 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9195 assert(PointerTy && "type was not a member pointer type!");
9196
9197 QualType PointeeTy = PointerTy->getPointeeType();
9198 // Don't add qualified variants of arrays. For one, they're not allowed
9199 // (the qualifier would sink to the element type), and for another, the
9200 // only overload situation where it matters is subscript or pointer +- int,
9201 // and those shouldn't have qualifier variants anyway.
9202 if (PointeeTy->isArrayType())
9203 return true;
9204 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9205
9206 // Iterate through all strict supersets of the pointee type's CVR
9207 // qualifiers.
9208 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9209 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9210 if ((CVR | BaseCVR) != CVR) continue;
9211
9212 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9213 MemberPointerTypes.insert(Context.getMemberPointerType(
9214 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9215 }
9216
9217 return true;
9218}
9219
9220/// AddTypesConvertedFrom - Add each of the types to which the type @p
9221/// Ty can be implicit converted to the given set of @p Types. We're
9222/// primarily interested in pointer types and enumeration types. We also
9223/// take member pointer types, for the conditional operator.
9224/// AllowUserConversions is true if we should look at the conversion
9225/// functions of a class type, and AllowExplicitConversions if we
9226/// should also include the explicit conversion functions of a class
9227/// type.
9228void
9229BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9230 SourceLocation Loc,
9231 bool AllowUserConversions,
9232 bool AllowExplicitConversions,
9233 const Qualifiers &VisibleQuals) {
9234 // Only deal with canonical types.
9235 Ty = Context.getCanonicalType(Ty);
9236
9237 // Look through reference types; they aren't part of the type of an
9238 // expression for the purposes of conversions.
9239 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9240 Ty = RefTy->getPointeeType();
9241
9242 // If we're dealing with an array type, decay to the pointer.
9243 if (Ty->isArrayType())
9244 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9245
9246 // Otherwise, we don't care about qualifiers on the type.
9247 Ty = Ty.getLocalUnqualifiedType();
9248
9249 // Flag if we ever add a non-record type.
9250 bool TyIsRec = Ty->isRecordType();
9251 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9252
9253 // Flag if we encounter an arithmetic type.
9254 HasArithmeticOrEnumeralTypes =
9255 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9256
9257 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9258 PointerTypes.insert(Ty);
9259 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9260 // Insert our type, and its more-qualified variants, into the set
9261 // of types.
9262 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9263 return;
9264 } else if (Ty->isMemberPointerType()) {
9265 // Member pointers are far easier, since the pointee can't be converted.
9266 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9267 return;
9268 } else if (Ty->isEnumeralType()) {
9269 HasArithmeticOrEnumeralTypes = true;
9270 EnumerationTypes.insert(Ty);
9271 } else if (Ty->isBitIntType()) {
9272 HasArithmeticOrEnumeralTypes = true;
9273 BitIntTypes.insert(Ty);
9274 } else if (Ty->isVectorType()) {
9275 // We treat vector types as arithmetic types in many contexts as an
9276 // extension.
9277 HasArithmeticOrEnumeralTypes = true;
9278 VectorTypes.insert(Ty);
9279 } else if (Ty->isMatrixType()) {
9280 // Similar to vector types, we treat vector types as arithmetic types in
9281 // many contexts as an extension.
9282 HasArithmeticOrEnumeralTypes = true;
9283 MatrixTypes.insert(Ty);
9284 } else if (Ty->isNullPtrType()) {
9285 HasNullPtrType = true;
9286 } else if (AllowUserConversions && TyIsRec) {
9287 // No conversion functions in incomplete types.
9288 if (!SemaRef.isCompleteType(Loc, Ty))
9289 return;
9290
9291 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9292 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9293 if (isa<UsingShadowDecl>(D))
9294 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9295
9296 // Skip conversion function templates; they don't tell us anything
9297 // about which builtin types we can convert to.
9299 continue;
9300
9301 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9302 if (AllowExplicitConversions || !Conv->isExplicit()) {
9303 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9304 VisibleQuals);
9305 }
9306 }
9307 }
9308}
9309/// Helper function for adjusting address spaces for the pointer or reference
9310/// operands of builtin operators depending on the argument.
9315
9316/// Helper function for AddBuiltinOperatorCandidates() that adds
9317/// the volatile- and non-volatile-qualified assignment operators for the
9318/// given type to the candidate set.
9320 QualType T,
9321 ArrayRef<Expr *> Args,
9322 OverloadCandidateSet &CandidateSet) {
9323 QualType ParamTypes[2];
9324
9325 // T& operator=(T&, T)
9326 ParamTypes[0] = S.Context.getLValueReferenceType(
9328 ParamTypes[1] = T;
9329 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9330 /*IsAssignmentOperator=*/true);
9331
9333 // volatile T& operator=(volatile T&, T)
9334 ParamTypes[0] = S.Context.getLValueReferenceType(
9336 Args[0]));
9337 ParamTypes[1] = T;
9338 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9339 /*IsAssignmentOperator=*/true);
9340 }
9341}
9342
9343/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9344/// if any, found in visible type conversion functions found in ArgExpr's type.
9345static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9346 Qualifiers VRQuals;
9347 CXXRecordDecl *ClassDecl;
9348 if (const MemberPointerType *RHSMPType =
9349 ArgExpr->getType()->getAs<MemberPointerType>())
9350 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9351 else
9352 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9353 if (!ClassDecl) {
9354 // Just to be safe, assume the worst case.
9355 VRQuals.addVolatile();
9356 VRQuals.addRestrict();
9357 return VRQuals;
9358 }
9359 if (!ClassDecl->hasDefinition())
9360 return VRQuals;
9361
9362 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9363 if (isa<UsingShadowDecl>(D))
9364 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9365 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9366 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9367 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9368 CanTy = ResTypeRef->getPointeeType();
9369 // Need to go down the pointer/mempointer chain and add qualifiers
9370 // as see them.
9371 bool done = false;
9372 while (!done) {
9373 if (CanTy.isRestrictQualified())
9374 VRQuals.addRestrict();
9375 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9376 CanTy = ResTypePtr->getPointeeType();
9377 else if (const MemberPointerType *ResTypeMPtr =
9378 CanTy->getAs<MemberPointerType>())
9379 CanTy = ResTypeMPtr->getPointeeType();
9380 else
9381 done = true;
9382 if (CanTy.isVolatileQualified())
9383 VRQuals.addVolatile();
9384 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9385 return VRQuals;
9386 }
9387 }
9388 }
9389 return VRQuals;
9390}
9391
9392// Note: We're currently only handling qualifiers that are meaningful for the
9393// LHS of compound assignment overloading.
9395 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9396 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9397 // _Atomic
9398 if (Available.hasAtomic()) {
9399 Available.removeAtomic();
9400 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9401 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9402 return;
9403 }
9404
9405 // volatile
9406 if (Available.hasVolatile()) {
9407 Available.removeVolatile();
9408 assert(!Applied.hasVolatile());
9409 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9410 Callback);
9411 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9412 return;
9413 }
9414
9415 Callback(Applied);
9416}
9417
9419 QualifiersAndAtomic Quals,
9420 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9422 Callback);
9423}
9424
9426 QualifiersAndAtomic Quals,
9427 Sema &S) {
9428 if (Quals.hasAtomic())
9430 if (Quals.hasVolatile())
9433}
9434
9435namespace {
9436
9437/// Helper class to manage the addition of builtin operator overload
9438/// candidates. It provides shared state and utility methods used throughout
9439/// the process, as well as a helper method to add each group of builtin
9440/// operator overloads from the standard to a candidate set.
9441class BuiltinOperatorOverloadBuilder {
9442 // Common instance state available to all overload candidate addition methods.
9443 Sema &S;
9444 ArrayRef<Expr *> Args;
9445 QualifiersAndAtomic VisibleTypeConversionsQuals;
9446 bool HasArithmeticOrEnumeralCandidateType;
9447 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9448 OverloadCandidateSet &CandidateSet;
9449
9450 static constexpr int ArithmeticTypesCap = 26;
9451 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9452
9453 // Define some indices used to iterate over the arithmetic types in
9454 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9455 // types are that preserved by promotion (C++ [over.built]p2).
9456 unsigned FirstIntegralType,
9457 LastIntegralType;
9458 unsigned FirstPromotedIntegralType,
9459 LastPromotedIntegralType;
9460 unsigned FirstPromotedArithmeticType,
9461 LastPromotedArithmeticType;
9462 unsigned NumArithmeticTypes;
9463
9464 void InitArithmeticTypes() {
9465 // Start of promoted types.
9466 FirstPromotedArithmeticType = 0;
9467 ArithmeticTypes.push_back(S.Context.FloatTy);
9468 ArithmeticTypes.push_back(S.Context.DoubleTy);
9469 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9471 ArithmeticTypes.push_back(S.Context.Float128Ty);
9473 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9474
9475 // Start of integral types.
9476 FirstIntegralType = ArithmeticTypes.size();
9477 FirstPromotedIntegralType = ArithmeticTypes.size();
9478 ArithmeticTypes.push_back(S.Context.IntTy);
9479 ArithmeticTypes.push_back(S.Context.LongTy);
9480 ArithmeticTypes.push_back(S.Context.LongLongTy);
9484 ArithmeticTypes.push_back(S.Context.Int128Ty);
9485 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9486 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9487 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9491 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9492
9493 /// We add candidates for the unique, unqualified _BitInt types present in
9494 /// the candidate type set. The candidate set already handled ensuring the
9495 /// type is unqualified and canonical, but because we're adding from N
9496 /// different sets, we need to do some extra work to unique things. Insert
9497 /// the candidates into a unique set, then move from that set into the list
9498 /// of arithmetic types.
9499 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9500 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9501 for (QualType BitTy : Candidate.bitint_types())
9502 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9503 }
9504 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9505 LastPromotedIntegralType = ArithmeticTypes.size();
9506 LastPromotedArithmeticType = ArithmeticTypes.size();
9507 // End of promoted types.
9508
9509 ArithmeticTypes.push_back(S.Context.BoolTy);
9510 ArithmeticTypes.push_back(S.Context.CharTy);
9511 ArithmeticTypes.push_back(S.Context.WCharTy);
9512 if (S.Context.getLangOpts().Char8)
9513 ArithmeticTypes.push_back(S.Context.Char8Ty);
9514 ArithmeticTypes.push_back(S.Context.Char16Ty);
9515 ArithmeticTypes.push_back(S.Context.Char32Ty);
9516 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9517 ArithmeticTypes.push_back(S.Context.ShortTy);
9518 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9519 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9520 LastIntegralType = ArithmeticTypes.size();
9521 NumArithmeticTypes = ArithmeticTypes.size();
9522 // End of integral types.
9523 // FIXME: What about complex? What about half?
9524
9525 // We don't know for sure how many bit-precise candidates were involved, so
9526 // we subtract those from the total when testing whether we're under the
9527 // cap or not.
9528 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9529 ArithmeticTypesCap &&
9530 "Enough inline storage for all arithmetic types.");
9531 }
9532
9533 /// Helper method to factor out the common pattern of adding overloads
9534 /// for '++' and '--' builtin operators.
9535 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9536 bool HasVolatile,
9537 bool HasRestrict) {
9538 QualType ParamTypes[2] = {
9539 S.Context.getLValueReferenceType(CandidateTy),
9540 S.Context.IntTy
9541 };
9542
9543 // Non-volatile version.
9544 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9545
9546 // Use a heuristic to reduce number of builtin candidates in the set:
9547 // add volatile version only if there are conversions to a volatile type.
9548 if (HasVolatile) {
9549 ParamTypes[0] =
9551 S.Context.getVolatileType(CandidateTy));
9552 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9553 }
9554
9555 // Add restrict version only if there are conversions to a restrict type
9556 // and our candidate type is a non-restrict-qualified pointer.
9557 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9558 !CandidateTy.isRestrictQualified()) {
9559 ParamTypes[0]
9562 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9563
9564 if (HasVolatile) {
9565 ParamTypes[0]
9567 S.Context.getCVRQualifiedType(CandidateTy,
9570 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9571 }
9572 }
9573
9574 }
9575
9576 /// Helper to add an overload candidate for a binary builtin with types \p L
9577 /// and \p R.
9578 void AddCandidate(QualType L, QualType R) {
9579 QualType LandR[2] = {L, R};
9580 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9581 }
9582
9583public:
9584 BuiltinOperatorOverloadBuilder(
9585 Sema &S, ArrayRef<Expr *> Args,
9586 QualifiersAndAtomic VisibleTypeConversionsQuals,
9587 bool HasArithmeticOrEnumeralCandidateType,
9588 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9589 OverloadCandidateSet &CandidateSet)
9590 : S(S), Args(Args),
9591 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9592 HasArithmeticOrEnumeralCandidateType(
9593 HasArithmeticOrEnumeralCandidateType),
9594 CandidateTypes(CandidateTypes),
9595 CandidateSet(CandidateSet) {
9596
9597 InitArithmeticTypes();
9598 }
9599
9600 // Increment is deprecated for bool since C++17.
9601 //
9602 // C++ [over.built]p3:
9603 //
9604 // For every pair (T, VQ), where T is an arithmetic type other
9605 // than bool, and VQ is either volatile or empty, there exist
9606 // candidate operator functions of the form
9607 //
9608 // VQ T& operator++(VQ T&);
9609 // T operator++(VQ T&, int);
9610 //
9611 // C++ [over.built]p4:
9612 //
9613 // For every pair (T, VQ), where T is an arithmetic type other
9614 // than bool, and VQ is either volatile or empty, there exist
9615 // candidate operator functions of the form
9616 //
9617 // VQ T& operator--(VQ T&);
9618 // T operator--(VQ T&, int);
9619 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9620 if (!HasArithmeticOrEnumeralCandidateType)
9621 return;
9622
9623 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9624 const auto TypeOfT = ArithmeticTypes[Arith];
9625 if (TypeOfT == S.Context.BoolTy) {
9626 if (Op == OO_MinusMinus)
9627 continue;
9628 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9629 continue;
9630 }
9631 addPlusPlusMinusMinusStyleOverloads(
9632 TypeOfT,
9633 VisibleTypeConversionsQuals.hasVolatile(),
9634 VisibleTypeConversionsQuals.hasRestrict());
9635 }
9636 }
9637
9638 // C++ [over.built]p5:
9639 //
9640 // For every pair (T, VQ), where T is a cv-qualified or
9641 // cv-unqualified object type, and VQ is either volatile or
9642 // empty, there exist candidate operator functions of the form
9643 //
9644 // T*VQ& operator++(T*VQ&);
9645 // T*VQ& operator--(T*VQ&);
9646 // T* operator++(T*VQ&, int);
9647 // T* operator--(T*VQ&, int);
9648 void addPlusPlusMinusMinusPointerOverloads() {
9649 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9650 // Skip pointer types that aren't pointers to object types.
9651 if (!PtrTy->getPointeeType()->isObjectType())
9652 continue;
9653
9654 addPlusPlusMinusMinusStyleOverloads(
9655 PtrTy,
9656 (!PtrTy.isVolatileQualified() &&
9657 VisibleTypeConversionsQuals.hasVolatile()),
9658 (!PtrTy.isRestrictQualified() &&
9659 VisibleTypeConversionsQuals.hasRestrict()));
9660 }
9661 }
9662
9663 // C++ [over.built]p6:
9664 // For every cv-qualified or cv-unqualified object type T, there
9665 // exist candidate operator functions of the form
9666 //
9667 // T& operator*(T*);
9668 //
9669 // C++ [over.built]p7:
9670 // For every function type T that does not have cv-qualifiers or a
9671 // ref-qualifier, there exist candidate operator functions of the form
9672 // T& operator*(T*);
9673 void addUnaryStarPointerOverloads() {
9674 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9675 QualType PointeeTy = ParamTy->getPointeeType();
9676 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9677 continue;
9678
9679 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9680 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9681 continue;
9682
9683 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9684 }
9685 }
9686
9687 // C++ [over.built]p9:
9688 // For every promoted arithmetic type T, there exist candidate
9689 // operator functions of the form
9690 //
9691 // T operator+(T);
9692 // T operator-(T);
9693 void addUnaryPlusOrMinusArithmeticOverloads() {
9694 if (!HasArithmeticOrEnumeralCandidateType)
9695 return;
9696
9697 for (unsigned Arith = FirstPromotedArithmeticType;
9698 Arith < LastPromotedArithmeticType; ++Arith) {
9699 QualType ArithTy = ArithmeticTypes[Arith];
9700 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9701 }
9702
9703 // Extension: We also add these operators for vector types.
9704 for (QualType VecTy : CandidateTypes[0].vector_types())
9705 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9706 }
9707
9708 // C++ [over.built]p8:
9709 // For every type T, there exist candidate operator functions of
9710 // the form
9711 //
9712 // T* operator+(T*);
9713 void addUnaryPlusPointerOverloads() {
9714 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9715 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9716 }
9717
9718 // C++ [over.built]p10:
9719 // For every promoted integral type T, there exist candidate
9720 // operator functions of the form
9721 //
9722 // T operator~(T);
9723 void addUnaryTildePromotedIntegralOverloads() {
9724 if (!HasArithmeticOrEnumeralCandidateType)
9725 return;
9726
9727 for (unsigned Int = FirstPromotedIntegralType;
9728 Int < LastPromotedIntegralType; ++Int) {
9729 QualType IntTy = ArithmeticTypes[Int];
9730 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9731 }
9732
9733 // Extension: We also add this operator for vector types.
9734 for (QualType VecTy : CandidateTypes[0].vector_types())
9735 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9736 }
9737
9738 // C++ [over.match.oper]p16:
9739 // For every pointer to member type T or type std::nullptr_t, there
9740 // exist candidate operator functions of the form
9741 //
9742 // bool operator==(T,T);
9743 // bool operator!=(T,T);
9744 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9745 /// Set of (canonical) types that we've already handled.
9746 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9747
9748 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9749 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9750 // Don't add the same builtin candidate twice.
9751 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9752 continue;
9753
9754 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9755 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9756 }
9757
9758 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9760 if (AddedTypes.insert(NullPtrTy).second) {
9761 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9762 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9763 }
9764 }
9765 }
9766 }
9767
9768 // C++ [over.built]p15:
9769 //
9770 // For every T, where T is an enumeration type or a pointer type,
9771 // there exist candidate operator functions of the form
9772 //
9773 // bool operator<(T, T);
9774 // bool operator>(T, T);
9775 // bool operator<=(T, T);
9776 // bool operator>=(T, T);
9777 // bool operator==(T, T);
9778 // bool operator!=(T, T);
9779 // R operator<=>(T, T)
9780 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9781 // C++ [over.match.oper]p3:
9782 // [...]the built-in candidates include all of the candidate operator
9783 // functions defined in 13.6 that, compared to the given operator, [...]
9784 // do not have the same parameter-type-list as any non-template non-member
9785 // candidate.
9786 //
9787 // Note that in practice, this only affects enumeration types because there
9788 // aren't any built-in candidates of record type, and a user-defined operator
9789 // must have an operand of record or enumeration type. Also, the only other
9790 // overloaded operator with enumeration arguments, operator=,
9791 // cannot be overloaded for enumeration types, so this is the only place
9792 // where we must suppress candidates like this.
9793 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9794 UserDefinedBinaryOperators;
9795
9796 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9797 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9798 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9799 CEnd = CandidateSet.end();
9800 C != CEnd; ++C) {
9801 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9802 continue;
9803
9804 if (C->Function->isFunctionTemplateSpecialization())
9805 continue;
9806
9807 // We interpret "same parameter-type-list" as applying to the
9808 // "synthesized candidate, with the order of the two parameters
9809 // reversed", not to the original function.
9810 bool Reversed = C->isReversed();
9811 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9812 ->getType()
9813 .getUnqualifiedType();
9814 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9815 ->getType()
9816 .getUnqualifiedType();
9817
9818 // Skip if either parameter isn't of enumeral type.
9819 if (!FirstParamType->isEnumeralType() ||
9820 !SecondParamType->isEnumeralType())
9821 continue;
9822
9823 // Add this operator to the set of known user-defined operators.
9824 UserDefinedBinaryOperators.insert(
9825 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9826 S.Context.getCanonicalType(SecondParamType)));
9827 }
9828 }
9829 }
9830
9831 /// Set of (canonical) types that we've already handled.
9832 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9833
9834 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9835 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9836 // Don't add the same builtin candidate twice.
9837 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9838 continue;
9839 if (IsSpaceship && PtrTy->isFunctionPointerType())
9840 continue;
9841
9842 QualType ParamTypes[2] = {PtrTy, PtrTy};
9843 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9844 }
9845 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9846 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9847
9848 // Don't add the same builtin candidate twice, or if a user defined
9849 // candidate exists.
9850 if (!AddedTypes.insert(CanonType).second ||
9851 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9852 CanonType)))
9853 continue;
9854 QualType ParamTypes[2] = {EnumTy, EnumTy};
9855 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9856 }
9857 }
9858 }
9859
9860 // C++ [over.built]p13:
9861 //
9862 // For every cv-qualified or cv-unqualified object type T
9863 // there exist candidate operator functions of the form
9864 //
9865 // T* operator+(T*, ptrdiff_t);
9866 // T& operator[](T*, ptrdiff_t); [BELOW]
9867 // T* operator-(T*, ptrdiff_t);
9868 // T* operator+(ptrdiff_t, T*);
9869 // T& operator[](ptrdiff_t, T*); [BELOW]
9870 //
9871 // C++ [over.built]p14:
9872 //
9873 // For every T, where T is a pointer to object type, there
9874 // exist candidate operator functions of the form
9875 //
9876 // ptrdiff_t operator-(T, T);
9877 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9878 /// Set of (canonical) types that we've already handled.
9879 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9880
9881 for (int Arg = 0; Arg < 2; ++Arg) {
9882 QualType AsymmetricParamTypes[2] = {
9885 };
9886 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9887 QualType PointeeTy = PtrTy->getPointeeType();
9888 if (!PointeeTy->isObjectType())
9889 continue;
9890
9891 AsymmetricParamTypes[Arg] = PtrTy;
9892 if (Arg == 0 || Op == OO_Plus) {
9893 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9894 // T* operator+(ptrdiff_t, T*);
9895 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9896 }
9897 if (Op == OO_Minus) {
9898 // ptrdiff_t operator-(T, T);
9899 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9900 continue;
9901
9902 QualType ParamTypes[2] = {PtrTy, PtrTy};
9903 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9904 }
9905 }
9906 }
9907 }
9908
9909 // C++ [over.built]p12:
9910 //
9911 // For every pair of promoted arithmetic types L and R, there
9912 // exist candidate operator functions of the form
9913 //
9914 // LR operator*(L, R);
9915 // LR operator/(L, R);
9916 // LR operator+(L, R);
9917 // LR operator-(L, R);
9918 // bool operator<(L, R);
9919 // bool operator>(L, R);
9920 // bool operator<=(L, R);
9921 // bool operator>=(L, R);
9922 // bool operator==(L, R);
9923 // bool operator!=(L, R);
9924 //
9925 // where LR is the result of the usual arithmetic conversions
9926 // between types L and R.
9927 //
9928 // C++ [over.built]p24:
9929 //
9930 // For every pair of promoted arithmetic types L and R, there exist
9931 // candidate operator functions of the form
9932 //
9933 // LR operator?(bool, L, R);
9934 //
9935 // where LR is the result of the usual arithmetic conversions
9936 // between types L and R.
9937 // Our candidates ignore the first parameter.
9938 void addGenericBinaryArithmeticOverloads() {
9939 if (!HasArithmeticOrEnumeralCandidateType)
9940 return;
9941
9942 for (unsigned Left = FirstPromotedArithmeticType;
9943 Left < LastPromotedArithmeticType; ++Left) {
9944 for (unsigned Right = FirstPromotedArithmeticType;
9945 Right < LastPromotedArithmeticType; ++Right) {
9946 QualType LandR[2] = { ArithmeticTypes[Left],
9947 ArithmeticTypes[Right] };
9948 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9949 }
9950 }
9951
9952 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9953 // conditional operator for vector types.
9954 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9955 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9956 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9957 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9958 }
9959 }
9960
9961 /// Add binary operator overloads for each candidate matrix type M1, M2:
9962 /// * (M1, M1) -> M1
9963 /// * (M1, M1.getElementType()) -> M1
9964 /// * (M2.getElementType(), M2) -> M2
9965 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9966 void addMatrixBinaryArithmeticOverloads() {
9967 if (!HasArithmeticOrEnumeralCandidateType)
9968 return;
9969
9970 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9971 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9972 AddCandidate(M1, M1);
9973 }
9974
9975 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9976 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9977 if (!CandidateTypes[0].containsMatrixType(M2))
9978 AddCandidate(M2, M2);
9979 }
9980 }
9981
9982 // C++2a [over.built]p14:
9983 //
9984 // For every integral type T there exists a candidate operator function
9985 // of the form
9986 //
9987 // std::strong_ordering operator<=>(T, T)
9988 //
9989 // C++2a [over.built]p15:
9990 //
9991 // For every pair of floating-point types L and R, there exists a candidate
9992 // operator function of the form
9993 //
9994 // std::partial_ordering operator<=>(L, R);
9995 //
9996 // FIXME: The current specification for integral types doesn't play nice with
9997 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9998 // comparisons. Under the current spec this can lead to ambiguity during
9999 // overload resolution. For example:
10000 //
10001 // enum A : int {a};
10002 // auto x = (a <=> (long)42);
10003 //
10004 // error: call is ambiguous for arguments 'A' and 'long'.
10005 // note: candidate operator<=>(int, int)
10006 // note: candidate operator<=>(long, long)
10007 //
10008 // To avoid this error, this function deviates from the specification and adds
10009 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10010 // arithmetic types (the same as the generic relational overloads).
10011 //
10012 // For now this function acts as a placeholder.
10013 void addThreeWayArithmeticOverloads() {
10014 addGenericBinaryArithmeticOverloads();
10015 }
10016
10017 // C++ [over.built]p17:
10018 //
10019 // For every pair of promoted integral types L and R, there
10020 // exist candidate operator functions of the form
10021 //
10022 // LR operator%(L, R);
10023 // LR operator&(L, R);
10024 // LR operator^(L, R);
10025 // LR operator|(L, R);
10026 // L operator<<(L, R);
10027 // L operator>>(L, R);
10028 //
10029 // where LR is the result of the usual arithmetic conversions
10030 // between types L and R.
10031 void addBinaryBitwiseArithmeticOverloads() {
10032 if (!HasArithmeticOrEnumeralCandidateType)
10033 return;
10034
10035 for (unsigned Left = FirstPromotedIntegralType;
10036 Left < LastPromotedIntegralType; ++Left) {
10037 for (unsigned Right = FirstPromotedIntegralType;
10038 Right < LastPromotedIntegralType; ++Right) {
10039 QualType LandR[2] = { ArithmeticTypes[Left],
10040 ArithmeticTypes[Right] };
10041 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10042 }
10043 }
10044 }
10045
10046 // C++ [over.built]p20:
10047 //
10048 // For every pair (T, VQ), where T is an enumeration or
10049 // pointer to member type and VQ is either volatile or
10050 // empty, there exist candidate operator functions of the form
10051 //
10052 // VQ T& operator=(VQ T&, T);
10053 void addAssignmentMemberPointerOrEnumeralOverloads() {
10054 /// Set of (canonical) types that we've already handled.
10055 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10056
10057 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10058 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10059 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10060 continue;
10061
10062 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10063 }
10064
10065 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10066 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10067 continue;
10068
10069 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10070 }
10071 }
10072 }
10073
10074 // C++ [over.built]p19:
10075 //
10076 // For every pair (T, VQ), where T is any type and VQ is either
10077 // volatile or empty, there exist candidate operator functions
10078 // of the form
10079 //
10080 // T*VQ& operator=(T*VQ&, T*);
10081 //
10082 // C++ [over.built]p21:
10083 //
10084 // For every pair (T, VQ), where T is a cv-qualified or
10085 // cv-unqualified object type and VQ is either volatile or
10086 // empty, there exist candidate operator functions of the form
10087 //
10088 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10089 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10090 void addAssignmentPointerOverloads(bool isEqualOp) {
10091 /// Set of (canonical) types that we've already handled.
10092 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10093
10094 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10095 // If this is operator=, keep track of the builtin candidates we added.
10096 if (isEqualOp)
10097 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10098 else if (!PtrTy->getPointeeType()->isObjectType())
10099 continue;
10100
10101 // non-volatile version
10102 QualType ParamTypes[2] = {
10104 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10105 };
10106 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10107 /*IsAssignmentOperator=*/ isEqualOp);
10108
10109 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10110 VisibleTypeConversionsQuals.hasVolatile();
10111 if (NeedVolatile) {
10112 // volatile version
10113 ParamTypes[0] =
10115 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10116 /*IsAssignmentOperator=*/isEqualOp);
10117 }
10118
10119 if (!PtrTy.isRestrictQualified() &&
10120 VisibleTypeConversionsQuals.hasRestrict()) {
10121 // restrict version
10122 ParamTypes[0] =
10124 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10125 /*IsAssignmentOperator=*/isEqualOp);
10126
10127 if (NeedVolatile) {
10128 // volatile restrict version
10129 ParamTypes[0] =
10132 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10133 /*IsAssignmentOperator=*/isEqualOp);
10134 }
10135 }
10136 }
10137
10138 if (isEqualOp) {
10139 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10140 // Make sure we don't add the same candidate twice.
10141 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10142 continue;
10143
10144 QualType ParamTypes[2] = {
10146 PtrTy,
10147 };
10148
10149 // non-volatile version
10150 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10151 /*IsAssignmentOperator=*/true);
10152
10153 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10154 VisibleTypeConversionsQuals.hasVolatile();
10155 if (NeedVolatile) {
10156 // volatile version
10157 ParamTypes[0] = S.Context.getLValueReferenceType(
10158 S.Context.getVolatileType(PtrTy));
10159 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10160 /*IsAssignmentOperator=*/true);
10161 }
10162
10163 if (!PtrTy.isRestrictQualified() &&
10164 VisibleTypeConversionsQuals.hasRestrict()) {
10165 // restrict version
10166 ParamTypes[0] = S.Context.getLValueReferenceType(
10167 S.Context.getRestrictType(PtrTy));
10168 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10169 /*IsAssignmentOperator=*/true);
10170
10171 if (NeedVolatile) {
10172 // volatile restrict version
10173 ParamTypes[0] =
10176 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10177 /*IsAssignmentOperator=*/true);
10178 }
10179 }
10180 }
10181 }
10182 }
10183
10184 // C++ [over.built]p18:
10185 //
10186 // For every triple (L, VQ, R), where L is an arithmetic type,
10187 // VQ is either volatile or empty, and R is a promoted
10188 // arithmetic type, there exist candidate operator functions of
10189 // the form
10190 //
10191 // VQ L& operator=(VQ L&, R);
10192 // VQ L& operator*=(VQ L&, R);
10193 // VQ L& operator/=(VQ L&, R);
10194 // VQ L& operator+=(VQ L&, R);
10195 // VQ L& operator-=(VQ L&, R);
10196 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10197 if (!HasArithmeticOrEnumeralCandidateType)
10198 return;
10199
10200 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10201 for (unsigned Right = FirstPromotedArithmeticType;
10202 Right < LastPromotedArithmeticType; ++Right) {
10203 QualType ParamTypes[2];
10204 ParamTypes[1] = ArithmeticTypes[Right];
10206 S, ArithmeticTypes[Left], Args[0]);
10207
10209 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10210 ParamTypes[0] =
10211 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10212 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10213 /*IsAssignmentOperator=*/isEqualOp);
10214 });
10215 }
10216 }
10217
10218 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10219 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10220 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10221 QualType ParamTypes[2];
10222 ParamTypes[1] = Vec2Ty;
10223 // Add this built-in operator as a candidate (VQ is empty).
10224 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10225 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10226 /*IsAssignmentOperator=*/isEqualOp);
10227
10228 // Add this built-in operator as a candidate (VQ is 'volatile').
10229 if (VisibleTypeConversionsQuals.hasVolatile()) {
10230 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10231 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10232 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10233 /*IsAssignmentOperator=*/isEqualOp);
10234 }
10235 }
10236 }
10237
10238 // C++ [over.built]p22:
10239 //
10240 // For every triple (L, VQ, R), where L is an integral type, VQ
10241 // is either volatile or empty, and R is a promoted integral
10242 // type, there exist candidate operator functions of the form
10243 //
10244 // VQ L& operator%=(VQ L&, R);
10245 // VQ L& operator<<=(VQ L&, R);
10246 // VQ L& operator>>=(VQ L&, R);
10247 // VQ L& operator&=(VQ L&, R);
10248 // VQ L& operator^=(VQ L&, R);
10249 // VQ L& operator|=(VQ L&, R);
10250 void addAssignmentIntegralOverloads() {
10251 if (!HasArithmeticOrEnumeralCandidateType)
10252 return;
10253
10254 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10255 for (unsigned Right = FirstPromotedIntegralType;
10256 Right < LastPromotedIntegralType; ++Right) {
10257 QualType ParamTypes[2];
10258 ParamTypes[1] = ArithmeticTypes[Right];
10260 S, ArithmeticTypes[Left], Args[0]);
10261
10263 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10264 ParamTypes[0] =
10265 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10266 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10267 });
10268 }
10269 }
10270 }
10271
10272 // C++ [over.operator]p23:
10273 //
10274 // There also exist candidate operator functions of the form
10275 //
10276 // bool operator!(bool);
10277 // bool operator&&(bool, bool);
10278 // bool operator||(bool, bool);
10279 void addExclaimOverload() {
10280 QualType ParamTy = S.Context.BoolTy;
10281 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10282 /*IsAssignmentOperator=*/false,
10283 /*NumContextualBoolArguments=*/1);
10284 }
10285 void addAmpAmpOrPipePipeOverload() {
10286 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10287 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10288 /*IsAssignmentOperator=*/false,
10289 /*NumContextualBoolArguments=*/2);
10290 }
10291
10292 // C++ [over.built]p13:
10293 //
10294 // For every cv-qualified or cv-unqualified object type T there
10295 // exist candidate operator functions of the form
10296 //
10297 // T* operator+(T*, ptrdiff_t); [ABOVE]
10298 // T& operator[](T*, ptrdiff_t);
10299 // T* operator-(T*, ptrdiff_t); [ABOVE]
10300 // T* operator+(ptrdiff_t, T*); [ABOVE]
10301 // T& operator[](ptrdiff_t, T*);
10302 void addSubscriptOverloads() {
10303 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10304 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10305 QualType PointeeType = PtrTy->getPointeeType();
10306 if (!PointeeType->isObjectType())
10307 continue;
10308
10309 // T& operator[](T*, ptrdiff_t)
10310 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10311 }
10312
10313 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10314 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10315 QualType PointeeType = PtrTy->getPointeeType();
10316 if (!PointeeType->isObjectType())
10317 continue;
10318
10319 // T& operator[](ptrdiff_t, T*)
10320 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10321 }
10322 }
10323
10324 // C++ [over.built]p11:
10325 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10326 // C1 is the same type as C2 or is a derived class of C2, T is an object
10327 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10328 // there exist candidate operator functions of the form
10329 //
10330 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10331 //
10332 // where CV12 is the union of CV1 and CV2.
10333 void addArrowStarOverloads() {
10334 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10335 QualType C1Ty = PtrTy;
10336 QualType C1;
10337 QualifierCollector Q1;
10338 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10339 if (!isa<RecordType>(C1))
10340 continue;
10341 // heuristic to reduce number of builtin candidates in the set.
10342 // Add volatile/restrict version only if there are conversions to a
10343 // volatile/restrict type.
10344 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10345 continue;
10346 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10347 continue;
10348 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10349 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10350 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10351 *D2 = mptr->getMostRecentCXXRecordDecl();
10352 if (!declaresSameEntity(D1, D2) &&
10353 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10354 break;
10355 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10356 // build CV12 T&
10357 QualType T = mptr->getPointeeType();
10358 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10360 continue;
10361 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10363 continue;
10364 T = Q1.apply(S.Context, T);
10365 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10366 }
10367 }
10368 }
10369
10370 // Note that we don't consider the first argument, since it has been
10371 // contextually converted to bool long ago. The candidates below are
10372 // therefore added as binary.
10373 //
10374 // C++ [over.built]p25:
10375 // For every type T, where T is a pointer, pointer-to-member, or scoped
10376 // enumeration type, there exist candidate operator functions of the form
10377 //
10378 // T operator?(bool, T, T);
10379 //
10380 void addConditionalOperatorOverloads() {
10381 /// Set of (canonical) types that we've already handled.
10382 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10383
10384 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10385 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10386 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10387 continue;
10388
10389 QualType ParamTypes[2] = {PtrTy, PtrTy};
10390 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10391 }
10392
10393 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10394 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10395 continue;
10396
10397 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10398 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10399 }
10400
10401 if (S.getLangOpts().CPlusPlus11) {
10402 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10403 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10404 continue;
10405
10406 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10407 continue;
10408
10409 QualType ParamTypes[2] = {EnumTy, EnumTy};
10410 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10411 }
10412 }
10413 }
10414 }
10415};
10416
10417} // end anonymous namespace
10418
10420 SourceLocation OpLoc,
10421 ArrayRef<Expr *> Args,
10422 OverloadCandidateSet &CandidateSet) {
10423 // Find all of the types that the arguments can convert to, but only
10424 // if the operator we're looking at has built-in operator candidates
10425 // that make use of these types. Also record whether we encounter non-record
10426 // candidate types or either arithmetic or enumeral candidate types.
10427 QualifiersAndAtomic VisibleTypeConversionsQuals;
10428 VisibleTypeConversionsQuals.addConst();
10429 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10430 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10431 if (Args[ArgIdx]->getType()->isAtomicType())
10432 VisibleTypeConversionsQuals.addAtomic();
10433 }
10434
10435 bool HasNonRecordCandidateType = false;
10436 bool HasArithmeticOrEnumeralCandidateType = false;
10438 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10439 CandidateTypes.emplace_back(*this);
10440 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10441 OpLoc,
10442 true,
10443 (Op == OO_Exclaim ||
10444 Op == OO_AmpAmp ||
10445 Op == OO_PipePipe),
10446 VisibleTypeConversionsQuals);
10447 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10448 CandidateTypes[ArgIdx].hasNonRecordTypes();
10449 HasArithmeticOrEnumeralCandidateType =
10450 HasArithmeticOrEnumeralCandidateType ||
10451 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10452 }
10453
10454 // Exit early when no non-record types have been added to the candidate set
10455 // for any of the arguments to the operator.
10456 //
10457 // We can't exit early for !, ||, or &&, since there we have always have
10458 // 'bool' overloads.
10459 if (!HasNonRecordCandidateType &&
10460 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10461 return;
10462
10463 // Setup an object to manage the common state for building overloads.
10464 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10465 VisibleTypeConversionsQuals,
10466 HasArithmeticOrEnumeralCandidateType,
10467 CandidateTypes, CandidateSet);
10468
10469 // Dispatch over the operation to add in only those overloads which apply.
10470 switch (Op) {
10471 case OO_None:
10473 llvm_unreachable("Expected an overloaded operator");
10474
10475 case OO_New:
10476 case OO_Delete:
10477 case OO_Array_New:
10478 case OO_Array_Delete:
10479 case OO_Call:
10480 llvm_unreachable(
10481 "Special operators don't use AddBuiltinOperatorCandidates");
10482
10483 case OO_Comma:
10484 case OO_Arrow:
10485 case OO_Coawait:
10486 // C++ [over.match.oper]p3:
10487 // -- For the operator ',', the unary operator '&', the
10488 // operator '->', or the operator 'co_await', the
10489 // built-in candidates set is empty.
10490 break;
10491
10492 case OO_Plus: // '+' is either unary or binary
10493 if (Args.size() == 1)
10494 OpBuilder.addUnaryPlusPointerOverloads();
10495 [[fallthrough]];
10496
10497 case OO_Minus: // '-' is either unary or binary
10498 if (Args.size() == 1) {
10499 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10500 } else {
10501 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10502 OpBuilder.addGenericBinaryArithmeticOverloads();
10503 OpBuilder.addMatrixBinaryArithmeticOverloads();
10504 }
10505 break;
10506
10507 case OO_Star: // '*' is either unary or binary
10508 if (Args.size() == 1)
10509 OpBuilder.addUnaryStarPointerOverloads();
10510 else {
10511 OpBuilder.addGenericBinaryArithmeticOverloads();
10512 OpBuilder.addMatrixBinaryArithmeticOverloads();
10513 }
10514 break;
10515
10516 case OO_Slash:
10517 OpBuilder.addGenericBinaryArithmeticOverloads();
10518 break;
10519
10520 case OO_PlusPlus:
10521 case OO_MinusMinus:
10522 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10523 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10524 break;
10525
10526 case OO_EqualEqual:
10527 case OO_ExclaimEqual:
10528 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10529 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10530 OpBuilder.addGenericBinaryArithmeticOverloads();
10531 break;
10532
10533 case OO_Less:
10534 case OO_Greater:
10535 case OO_LessEqual:
10536 case OO_GreaterEqual:
10537 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10538 OpBuilder.addGenericBinaryArithmeticOverloads();
10539 break;
10540
10541 case OO_Spaceship:
10542 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10543 OpBuilder.addThreeWayArithmeticOverloads();
10544 break;
10545
10546 case OO_Percent:
10547 case OO_Caret:
10548 case OO_Pipe:
10549 case OO_LessLess:
10550 case OO_GreaterGreater:
10551 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10552 break;
10553
10554 case OO_Amp: // '&' is either unary or binary
10555 if (Args.size() == 1)
10556 // C++ [over.match.oper]p3:
10557 // -- For the operator ',', the unary operator '&', or the
10558 // operator '->', the built-in candidates set is empty.
10559 break;
10560
10561 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10562 break;
10563
10564 case OO_Tilde:
10565 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10566 break;
10567
10568 case OO_Equal:
10569 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10570 [[fallthrough]];
10571
10572 case OO_PlusEqual:
10573 case OO_MinusEqual:
10574 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10575 [[fallthrough]];
10576
10577 case OO_StarEqual:
10578 case OO_SlashEqual:
10579 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10580 break;
10581
10582 case OO_PercentEqual:
10583 case OO_LessLessEqual:
10584 case OO_GreaterGreaterEqual:
10585 case OO_AmpEqual:
10586 case OO_CaretEqual:
10587 case OO_PipeEqual:
10588 OpBuilder.addAssignmentIntegralOverloads();
10589 break;
10590
10591 case OO_Exclaim:
10592 OpBuilder.addExclaimOverload();
10593 break;
10594
10595 case OO_AmpAmp:
10596 case OO_PipePipe:
10597 OpBuilder.addAmpAmpOrPipePipeOverload();
10598 break;
10599
10600 case OO_Subscript:
10601 if (Args.size() == 2)
10602 OpBuilder.addSubscriptOverloads();
10603 break;
10604
10605 case OO_ArrowStar:
10606 OpBuilder.addArrowStarOverloads();
10607 break;
10608
10609 case OO_Conditional:
10610 OpBuilder.addConditionalOperatorOverloads();
10611 OpBuilder.addGenericBinaryArithmeticOverloads();
10612 break;
10613 }
10614}
10615
10616void
10618 SourceLocation Loc,
10619 ArrayRef<Expr *> Args,
10620 TemplateArgumentListInfo *ExplicitTemplateArgs,
10621 OverloadCandidateSet& CandidateSet,
10622 bool PartialOverloading) {
10623 ADLResult Fns;
10624
10625 // FIXME: This approach for uniquing ADL results (and removing
10626 // redundant candidates from the set) relies on pointer-equality,
10627 // which means we need to key off the canonical decl. However,
10628 // always going back to the canonical decl might not get us the
10629 // right set of default arguments. What default arguments are
10630 // we supposed to consider on ADL candidates, anyway?
10631
10632 // FIXME: Pass in the explicit template arguments?
10633 ArgumentDependentLookup(Name, Loc, Args, Fns);
10634
10635 ArrayRef<Expr *> ReversedArgs;
10636
10637 // Erase all of the candidates we already knew about.
10638 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10639 CandEnd = CandidateSet.end();
10640 Cand != CandEnd; ++Cand)
10641 if (Cand->Function) {
10642 FunctionDecl *Fn = Cand->Function;
10643 Fns.erase(Fn);
10644 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10645 Fns.erase(FunTmpl);
10646 }
10647
10648 // For each of the ADL candidates we found, add it to the overload
10649 // set.
10650 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10652
10653 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10654 if (ExplicitTemplateArgs)
10655 continue;
10656
10658 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10659 PartialOverloading, /*AllowExplicit=*/true,
10660 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10661 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10663 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10664 /*SuppressUserConversions=*/false, PartialOverloading,
10665 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10666 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10667 }
10668 } else {
10669 auto *FTD = cast<FunctionTemplateDecl>(*I);
10671 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10672 /*SuppressUserConversions=*/false, PartialOverloading,
10673 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10674 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10675 *this, Args, FTD->getTemplatedDecl())) {
10676
10677 // As template candidates are not deduced immediately,
10678 // persist the array in the overload set.
10679 if (ReversedArgs.empty())
10680 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10681
10683 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10684 /*SuppressUserConversions=*/false, PartialOverloading,
10685 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10687 }
10688 }
10689 }
10690}
10691
10692namespace {
10693enum class Comparison { Equal, Better, Worse };
10694}
10695
10696/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10697/// overload resolution.
10698///
10699/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10700/// Cand1's first N enable_if attributes have precisely the same conditions as
10701/// Cand2's first N enable_if attributes (where N = the number of enable_if
10702/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10703///
10704/// Note that you can have a pair of candidates such that Cand1's enable_if
10705/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10706/// worse than Cand1's.
10707static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10708 const FunctionDecl *Cand2) {
10709 // Common case: One (or both) decls don't have enable_if attrs.
10710 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10711 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10712 if (!Cand1Attr || !Cand2Attr) {
10713 if (Cand1Attr == Cand2Attr)
10714 return Comparison::Equal;
10715 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10716 }
10717
10718 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10719 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10720
10721 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10722 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10723 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10724 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10725
10726 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10727 // has fewer enable_if attributes than Cand2, and vice versa.
10728 if (!Cand1A)
10729 return Comparison::Worse;
10730 if (!Cand2A)
10731 return Comparison::Better;
10732
10733 Cand1ID.clear();
10734 Cand2ID.clear();
10735
10736 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10737 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10738 if (Cand1ID != Cand2ID)
10739 return Comparison::Worse;
10740 }
10741
10742 return Comparison::Equal;
10743}
10744
10745static Comparison
10747 const OverloadCandidate &Cand2) {
10748 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10749 !Cand2.Function->isMultiVersion())
10750 return Comparison::Equal;
10751
10752 // If both are invalid, they are equal. If one of them is invalid, the other
10753 // is better.
10754 if (Cand1.Function->isInvalidDecl()) {
10755 if (Cand2.Function->isInvalidDecl())
10756 return Comparison::Equal;
10757 return Comparison::Worse;
10758 }
10759 if (Cand2.Function->isInvalidDecl())
10760 return Comparison::Better;
10761
10762 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10763 // cpu_dispatch, else arbitrarily based on the identifiers.
10764 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10765 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10766 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10767 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10768
10769 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10770 return Comparison::Equal;
10771
10772 if (Cand1CPUDisp && !Cand2CPUDisp)
10773 return Comparison::Better;
10774 if (Cand2CPUDisp && !Cand1CPUDisp)
10775 return Comparison::Worse;
10776
10777 if (Cand1CPUSpec && Cand2CPUSpec) {
10778 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10779 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10780 ? Comparison::Better
10781 : Comparison::Worse;
10782
10783 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10784 FirstDiff = std::mismatch(
10785 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10786 Cand2CPUSpec->cpus_begin(),
10787 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10788 return LHS->getName() == RHS->getName();
10789 });
10790
10791 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10792 "Two different cpu-specific versions should not have the same "
10793 "identifier list, otherwise they'd be the same decl!");
10794 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10795 ? Comparison::Better
10796 : Comparison::Worse;
10797 }
10798 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10799}
10800
10801/// Compute the type of the implicit object parameter for the given function,
10802/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10803/// null QualType if there is a 'matches anything' implicit object parameter.
10804static std::optional<QualType>
10807 return std::nullopt;
10808
10809 auto *M = cast<CXXMethodDecl>(F);
10810 // Static member functions' object parameters match all types.
10811 if (M->isStatic())
10812 return QualType();
10813 return M->getFunctionObjectParameterReferenceType();
10814}
10815
10816// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10817// represent the same entity.
10818static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10819 const FunctionDecl *F2) {
10820 if (declaresSameEntity(F1, F2))
10821 return true;
10822 auto PT1 = F1->getPrimaryTemplate();
10823 auto PT2 = F2->getPrimaryTemplate();
10824 if (PT1 && PT2) {
10825 if (declaresSameEntity(PT1, PT2) ||
10826 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10827 PT2->getInstantiatedFromMemberTemplate()))
10828 return true;
10829 }
10830 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10831 // different functions with same params). Consider removing this (as no test
10832 // fail w/o it).
10833 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10834 if (First) {
10835 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10836 return *T;
10837 }
10838 assert(I < F->getNumParams());
10839 return F->getParamDecl(I++)->getType();
10840 };
10841
10842 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10843 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10844
10845 if (F1NumParams != F2NumParams)
10846 return false;
10847
10848 unsigned I1 = 0, I2 = 0;
10849 for (unsigned I = 0; I != F1NumParams; ++I) {
10850 QualType T1 = NextParam(F1, I1, I == 0);
10851 QualType T2 = NextParam(F2, I2, I == 0);
10852 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10853 if (!Context.hasSameUnqualifiedType(T1, T2))
10854 return false;
10855 }
10856 return true;
10857}
10858
10859/// We're allowed to use constraints partial ordering only if the candidates
10860/// have the same parameter types:
10861/// [over.match.best.general]p2.6
10862/// F1 and F2 are non-template functions with the same
10863/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10865 FunctionDecl *Fn2,
10866 bool IsFn1Reversed,
10867 bool IsFn2Reversed) {
10868 assert(Fn1 && Fn2);
10869 if (Fn1->isVariadic() != Fn2->isVariadic())
10870 return false;
10871
10872 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10873 IsFn1Reversed ^ IsFn2Reversed))
10874 return false;
10875
10876 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10877 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10878 if (Mem1 && Mem2) {
10879 // if they are member functions, both are direct members of the same class,
10880 // and
10881 if (Mem1->getParent() != Mem2->getParent())
10882 return false;
10883 // if both are non-static member functions, they have the same types for
10884 // their object parameters
10885 if (Mem1->isInstance() && Mem2->isInstance() &&
10887 Mem1->getFunctionObjectParameterReferenceType(),
10888 Mem1->getFunctionObjectParameterReferenceType()))
10889 return false;
10890 }
10891 return true;
10892}
10893
10894static FunctionDecl *
10896 bool IsFn1Reversed, bool IsFn2Reversed) {
10897 if (!Fn1 || !Fn2)
10898 return nullptr;
10899
10900 // C++ [temp.constr.order]:
10901 // A non-template function F1 is more partial-ordering-constrained than a
10902 // non-template function F2 if:
10903 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10904 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10905
10906 if (Cand1IsSpecialization || Cand2IsSpecialization)
10907 return nullptr;
10908
10909 // - they have the same non-object-parameter-type-lists, and [...]
10910 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10911 IsFn2Reversed))
10912 return nullptr;
10913
10914 // - the declaration of F1 is more constrained than the declaration of F2.
10915 return S.getMoreConstrainedFunction(Fn1, Fn2);
10916}
10917
10918/// isBetterOverloadCandidate - Determines whether the first overload
10919/// candidate is a better candidate than the second (C++ 13.3.3p1).
10921 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10923 bool PartialOverloading) {
10924 // Define viable functions to be better candidates than non-viable
10925 // functions.
10926 if (!Cand2.Viable)
10927 return Cand1.Viable;
10928 else if (!Cand1.Viable)
10929 return false;
10930
10931 // [CUDA] A function with 'never' preference is marked not viable, therefore
10932 // is never shown up here. The worst preference shown up here is 'wrong side',
10933 // e.g. an H function called by a HD function in device compilation. This is
10934 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10935 // function which is called only by an H function. A deferred diagnostic will
10936 // be triggered if it is emitted. However a wrong-sided function is still
10937 // a viable candidate here.
10938 //
10939 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10940 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10941 // can be emitted, Cand1 is not better than Cand2. This rule should have
10942 // precedence over other rules.
10943 //
10944 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10945 // other rules should be used to determine which is better. This is because
10946 // host/device based overloading resolution is mostly for determining
10947 // viability of a function. If two functions are both viable, other factors
10948 // should take precedence in preference, e.g. the standard-defined preferences
10949 // like argument conversion ranks or enable_if partial-ordering. The
10950 // preference for pass-object-size parameters is probably most similar to a
10951 // type-based-overloading decision and so should take priority.
10952 //
10953 // If other rules cannot determine which is better, CUDA preference will be
10954 // used again to determine which is better.
10955 //
10956 // TODO: Currently IdentifyPreference does not return correct values
10957 // for functions called in global variable initializers due to missing
10958 // correct context about device/host. Therefore we can only enforce this
10959 // rule when there is a caller. We should enforce this rule for functions
10960 // in global variable initializers once proper context is added.
10961 //
10962 // TODO: We can only enable the hostness based overloading resolution when
10963 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10964 // overloading resolution diagnostics.
10965 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10966 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10967 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10968 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10969 bool IsCand1ImplicitHD =
10971 bool IsCand2ImplicitHD =
10973 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10974 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10975 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10976 // The implicit HD function may be a function in a system header which
10977 // is forced by pragma. In device compilation, if we prefer HD candidates
10978 // over wrong-sided candidates, overloading resolution may change, which
10979 // may result in non-deferrable diagnostics. As a workaround, we let
10980 // implicit HD candidates take equal preference as wrong-sided candidates.
10981 // This will preserve the overloading resolution.
10982 // TODO: We still need special handling of implicit HD functions since
10983 // they may incur other diagnostics to be deferred. We should make all
10984 // host/device related diagnostics deferrable and remove special handling
10985 // of implicit HD functions.
10986 auto EmitThreshold =
10987 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10988 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10991 auto Cand1Emittable = P1 > EmitThreshold;
10992 auto Cand2Emittable = P2 > EmitThreshold;
10993 if (Cand1Emittable && !Cand2Emittable)
10994 return true;
10995 if (!Cand1Emittable && Cand2Emittable)
10996 return false;
10997 }
10998 }
10999
11000 // C++ [over.match.best]p1: (Changed in C++23)
11001 //
11002 // -- if F is a static member function, ICS1(F) is defined such
11003 // that ICS1(F) is neither better nor worse than ICS1(G) for
11004 // any function G, and, symmetrically, ICS1(G) is neither
11005 // better nor worse than ICS1(F).
11006 unsigned StartArg = 0;
11007 if (!Cand1.TookAddressOfOverload &&
11009 StartArg = 1;
11010
11011 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11012 // We don't allow incompatible pointer conversions in C++.
11013 if (!S.getLangOpts().CPlusPlus)
11014 return ICS.isStandard() &&
11015 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11016
11017 // The only ill-formed conversion we allow in C++ is the string literal to
11018 // char* conversion, which is only considered ill-formed after C++11.
11019 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11021 };
11022
11023 // Define functions that don't require ill-formed conversions for a given
11024 // argument to be better candidates than functions that do.
11025 unsigned NumArgs = Cand1.Conversions.size();
11026 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11027 bool HasBetterConversion = false;
11028 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11029 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11030 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11031 if (Cand1Bad != Cand2Bad) {
11032 if (Cand1Bad)
11033 return false;
11034 HasBetterConversion = true;
11035 }
11036 }
11037
11038 if (HasBetterConversion)
11039 return true;
11040
11041 // C++ [over.match.best]p1:
11042 // A viable function F1 is defined to be a better function than another
11043 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11044 // conversion sequence than ICSi(F2), and then...
11045 bool HasWorseConversion = false;
11046 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11048 Cand1.Conversions[ArgIdx],
11049 Cand2.Conversions[ArgIdx])) {
11051 // Cand1 has a better conversion sequence.
11052 HasBetterConversion = true;
11053 break;
11054
11056 if (Cand1.Function && Cand2.Function &&
11057 Cand1.isReversed() != Cand2.isReversed() &&
11058 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11059 // Work around large-scale breakage caused by considering reversed
11060 // forms of operator== in C++20:
11061 //
11062 // When comparing a function against a reversed function, if we have a
11063 // better conversion for one argument and a worse conversion for the
11064 // other, the implicit conversion sequences are treated as being equally
11065 // good.
11066 //
11067 // This prevents a comparison function from being considered ambiguous
11068 // with a reversed form that is written in the same way.
11069 //
11070 // We diagnose this as an extension from CreateOverloadedBinOp.
11071 HasWorseConversion = true;
11072 break;
11073 }
11074
11075 // Cand1 can't be better than Cand2.
11076 return false;
11077
11079 // Do nothing.
11080 break;
11081 }
11082 }
11083
11084 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11085 // ICSj(F2), or, if not that,
11086 if (HasBetterConversion && !HasWorseConversion)
11087 return true;
11088
11089 // -- the context is an initialization by user-defined conversion
11090 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11091 // from the return type of F1 to the destination type (i.e.,
11092 // the type of the entity being initialized) is a better
11093 // conversion sequence than the standard conversion sequence
11094 // from the return type of F2 to the destination type.
11096 Cand1.Function && Cand2.Function &&
11099
11100 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11101 // First check whether we prefer one of the conversion functions over the
11102 // other. This only distinguishes the results in non-standard, extension
11103 // cases such as the conversion from a lambda closure type to a function
11104 // pointer or block.
11109 Cand1.FinalConversion,
11110 Cand2.FinalConversion);
11111
11114
11115 // FIXME: Compare kind of reference binding if conversion functions
11116 // convert to a reference type used in direct reference binding, per
11117 // C++14 [over.match.best]p1 section 2 bullet 3.
11118 }
11119
11120 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11121 // as combined with the resolution to CWG issue 243.
11122 //
11123 // When the context is initialization by constructor ([over.match.ctor] or
11124 // either phase of [over.match.list]), a constructor is preferred over
11125 // a conversion function.
11126 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11127 Cand1.Function && Cand2.Function &&
11130 return isa<CXXConstructorDecl>(Cand1.Function);
11131
11132 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11133 return Cand2.StrictPackMatch;
11134
11135 // -- F1 is a non-template function and F2 is a function template
11136 // specialization, or, if not that,
11137 bool Cand1IsSpecialization = Cand1.Function &&
11139 bool Cand2IsSpecialization = Cand2.Function &&
11141 if (Cand1IsSpecialization != Cand2IsSpecialization)
11142 return Cand2IsSpecialization;
11143
11144 // -- F1 and F2 are function template specializations, and the function
11145 // template for F1 is more specialized than the template for F2
11146 // according to the partial ordering rules described in 14.5.5.2, or,
11147 // if not that,
11148 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11149 const auto *Obj1Context =
11150 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11151 const auto *Obj2Context =
11152 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11153 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11155 Cand2.Function->getPrimaryTemplate(), Loc,
11157 : TPOC_Call,
11159 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11160 : QualType{},
11161 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11162 : QualType{},
11163 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11164 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11165 }
11166 }
11167
11168 // -— F1 and F2 are non-template functions and F1 is more
11169 // partial-ordering-constrained than F2 [...],
11171 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11172 Cand2.isReversed());
11173 F && F == Cand1.Function)
11174 return true;
11175
11176 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11177 // class B of D, and for all arguments the corresponding parameters of
11178 // F1 and F2 have the same type.
11179 // FIXME: Implement the "all parameters have the same type" check.
11180 bool Cand1IsInherited =
11181 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11182 bool Cand2IsInherited =
11183 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11184 if (Cand1IsInherited != Cand2IsInherited)
11185 return Cand2IsInherited;
11186 else if (Cand1IsInherited) {
11187 assert(Cand2IsInherited);
11188 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11189 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11190 if (Cand1Class->isDerivedFrom(Cand2Class))
11191 return true;
11192 if (Cand2Class->isDerivedFrom(Cand1Class))
11193 return false;
11194 // Inherited from sibling base classes: still ambiguous.
11195 }
11196
11197 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11198 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11199 // with reversed order of parameters and F1 is not
11200 //
11201 // We rank reversed + different operator as worse than just reversed, but
11202 // that comparison can never happen, because we only consider reversing for
11203 // the maximally-rewritten operator (== or <=>).
11204 if (Cand1.RewriteKind != Cand2.RewriteKind)
11205 return Cand1.RewriteKind < Cand2.RewriteKind;
11206
11207 // Check C++17 tie-breakers for deduction guides.
11208 {
11209 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11210 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11211 if (Guide1 && Guide2) {
11212 // -- F1 is generated from a deduction-guide and F2 is not
11213 if (Guide1->isImplicit() != Guide2->isImplicit())
11214 return Guide2->isImplicit();
11215
11216 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11217 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11218 return true;
11219 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11220 return false;
11221
11222 // --F1 is generated from a non-template constructor and F2 is generated
11223 // from a constructor template
11224 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11225 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11226 if (Constructor1 && Constructor2) {
11227 bool isC1Templated = Constructor1->getTemplatedKind() !=
11229 bool isC2Templated = Constructor2->getTemplatedKind() !=
11231 if (isC1Templated != isC2Templated)
11232 return isC2Templated;
11233 }
11234 }
11235 }
11236
11237 // Check for enable_if value-based overload resolution.
11238 if (Cand1.Function && Cand2.Function) {
11240 if (Cmp != Comparison::Equal)
11241 return Cmp == Comparison::Better;
11242 }
11243
11244 bool HasPS1 = Cand1.Function != nullptr &&
11246 bool HasPS2 = Cand2.Function != nullptr &&
11248 if (HasPS1 != HasPS2 && HasPS1)
11249 return true;
11250
11251 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11252 if (MV == Comparison::Better)
11253 return true;
11254 if (MV == Comparison::Worse)
11255 return false;
11256
11257 // If other rules cannot determine which is better, CUDA preference is used
11258 // to determine which is better.
11259 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11260 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11261 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11262 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11263 }
11264
11265 // General member function overloading is handled above, so this only handles
11266 // constructors with address spaces.
11267 // This only handles address spaces since C++ has no other
11268 // qualifier that can be used with constructors.
11269 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11270 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11271 if (CD1 && CD2) {
11272 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11273 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11274 if (AS1 != AS2) {
11276 return true;
11278 return false;
11279 }
11280 }
11281
11282 return false;
11283}
11284
11285/// Determine whether two declarations are "equivalent" for the purposes of
11286/// name lookup and overload resolution. This applies when the same internal/no
11287/// linkage entity is defined by two modules (probably by textually including
11288/// the same header). In such a case, we don't consider the declarations to
11289/// declare the same entity, but we also don't want lookups with both
11290/// declarations visible to be ambiguous in some cases (this happens when using
11291/// a modularized libstdc++).
11293 const NamedDecl *B) {
11294 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11295 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11296 if (!VA || !VB)
11297 return false;
11298
11299 // The declarations must be declaring the same name as an internal linkage
11300 // entity in different modules.
11301 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11302 VB->getDeclContext()->getRedeclContext()) ||
11303 getOwningModule(VA) == getOwningModule(VB) ||
11304 VA->isExternallyVisible() || VB->isExternallyVisible())
11305 return false;
11306
11307 // Check that the declarations appear to be equivalent.
11308 //
11309 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11310 // For constants and functions, we should check the initializer or body is
11311 // the same. For non-constant variables, we shouldn't allow it at all.
11312 if (Context.hasSameType(VA->getType(), VB->getType()))
11313 return true;
11314
11315 // Enum constants within unnamed enumerations will have different types, but
11316 // may still be similar enough to be interchangeable for our purposes.
11317 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11318 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11319 // Only handle anonymous enums. If the enumerations were named and
11320 // equivalent, they would have been merged to the same type.
11321 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11322 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11323 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11324 !Context.hasSameType(EnumA->getIntegerType(),
11325 EnumB->getIntegerType()))
11326 return false;
11327 // Allow this only if the value is the same for both enumerators.
11328 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11329 }
11330 }
11331
11332 // Nothing else is sufficiently similar.
11333 return false;
11334}
11335
11338 assert(D && "Unknown declaration");
11339 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11340
11341 Module *M = getOwningModule(D);
11342 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11343 << !M << (M ? M->getFullModuleName() : "");
11344
11345 for (auto *E : Equiv) {
11346 Module *M = getOwningModule(E);
11347 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11348 << !M << (M ? M->getFullModuleName() : "");
11349 }
11350}
11351
11354 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11356 static_cast<CNSInfo *>(DeductionFailure.Data)
11357 ->Satisfaction.ContainsErrors;
11358}
11359
11362 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11363 bool PartialOverloading, bool AllowExplicit,
11365 bool AggregateCandidateDeduction) {
11366
11367 auto *C =
11368 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11369
11372 /*AllowObjCConversionOnExplicit=*/false,
11373 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11374 PartialOverloading, AggregateCandidateDeduction},
11376 FoundDecl,
11377 Args,
11378 IsADLCandidate,
11379 PO};
11380
11381 HasDeferredTemplateConstructors |=
11382 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11383}
11384
11386 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11387 CXXRecordDecl *ActingContext, QualType ObjectType,
11388 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11389 bool SuppressUserConversions, bool PartialOverloading,
11391
11392 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11393
11394 auto *C =
11395 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11396
11399 /*AllowObjCConversionOnExplicit=*/false,
11400 /*AllowResultConversion=*/false,
11401 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11402 /*AggregateCandidateDeduction=*/false},
11403 MethodTmpl,
11404 FoundDecl,
11405 Args,
11406 ActingContext,
11407 ObjectClassification,
11408 ObjectType,
11409 PO};
11410}
11411
11414 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11415 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11416 bool AllowResultConversion) {
11417
11418 auto *C =
11419 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11420
11423 AllowObjCConversionOnExplicit, AllowResultConversion,
11424 /*AllowExplicit=*/false,
11425 /*SuppressUserConversions=*/false,
11426 /*PartialOverloading*/ false,
11427 /*AggregateCandidateDeduction=*/false},
11429 FoundDecl,
11430 ActingContext,
11431 From,
11432 ToType};
11433}
11434
11435static void
11438
11440 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11441 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11442 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11443}
11444
11445static void
11449 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11450 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11451 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11452 C.AggregateCandidateDeduction);
11453}
11454
11455static void
11459 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11460 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11461 C.AllowResultConversion);
11462}
11463
11465 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11466 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11467 while (Cand) {
11468 switch (Cand->Kind) {
11471 S, *this,
11472 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11473 break;
11476 S, *this,
11477 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11478 break;
11481 S, *this,
11482 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11483 break;
11484 }
11485 Cand = Cand->Next;
11486 }
11487 FirstDeferredCandidate = nullptr;
11488 DeferredCandidatesCount = 0;
11489}
11490
11492OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11493 Best->Best = true;
11494 if (Best->Function && Best->Function->isDeleted())
11495 return OR_Deleted;
11496 return OR_Success;
11497}
11498
11499void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11501 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11502 // are accepted by both clang and NVCC. However, during a particular
11503 // compilation mode only one call variant is viable. We need to
11504 // exclude non-viable overload candidates from consideration based
11505 // only on their host/device attributes. Specifically, if one
11506 // candidate call is WrongSide and the other is SameSide, we ignore
11507 // the WrongSide candidate.
11508 // We only need to remove wrong-sided candidates here if
11509 // -fgpu-exclude-wrong-side-overloads is off. When
11510 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11511 // uniformly in isBetterOverloadCandidate.
11512 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11513 return;
11514 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11515
11516 bool ContainsSameSideCandidate =
11517 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11518 // Check viable function only.
11519 return Cand->Viable && Cand->Function &&
11520 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11522 });
11523
11524 if (!ContainsSameSideCandidate)
11525 return;
11526
11527 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11528 // Check viable function only to avoid unnecessary data copying/moving.
11529 return Cand->Viable && Cand->Function &&
11530 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11532 };
11533 llvm::erase_if(Candidates, IsWrongSideCandidate);
11534}
11535
11536/// Computes the best viable function (C++ 13.3.3)
11537/// within an overload candidate set.
11538///
11539/// \param Loc The location of the function name (or operator symbol) for
11540/// which overload resolution occurs.
11541///
11542/// \param Best If overload resolution was successful or found a deleted
11543/// function, \p Best points to the candidate function found.
11544///
11545/// \returns The result of overload resolution.
11547 SourceLocation Loc,
11548 iterator &Best) {
11549
11551 DeferredCandidatesCount == 0) &&
11552 "Unexpected deferred template candidates");
11553
11554 bool TwoPhaseResolution =
11555 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11556
11557 if (TwoPhaseResolution) {
11558 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11559 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11560 if (!(HasDeferredTemplateConstructors &&
11561 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11562 return Res;
11563 }
11564 }
11565
11567 return BestViableFunctionImpl(S, Loc, Best);
11568}
11569
11570OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11572
11574 Candidates.reserve(this->Candidates.size());
11575 std::transform(this->Candidates.begin(), this->Candidates.end(),
11576 std::back_inserter(Candidates),
11577 [](OverloadCandidate &Cand) { return &Cand; });
11578
11579 if (S.getLangOpts().CUDA)
11580 CudaExcludeWrongSideCandidates(S, Candidates);
11581
11582 Best = end();
11583 for (auto *Cand : Candidates) {
11584 Cand->Best = false;
11585 if (Cand->Viable) {
11586 if (Best == end() ||
11587 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11588 Best = Cand;
11589 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11590 // This candidate has constraint that we were unable to evaluate because
11591 // it referenced an expression that contained an error. Rather than fall
11592 // back onto a potentially unintended candidate (made worse by
11593 // subsuming constraints), treat this as 'no viable candidate'.
11594 Best = end();
11595 return OR_No_Viable_Function;
11596 }
11597 }
11598
11599 // If we didn't find any viable functions, abort.
11600 if (Best == end())
11601 return OR_No_Viable_Function;
11602
11603 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11604 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11605 PendingBest.push_back(&*Best);
11606 Best->Best = true;
11607
11608 // Make sure that this function is better than every other viable
11609 // function. If not, we have an ambiguity.
11610 while (!PendingBest.empty()) {
11611 auto *Curr = PendingBest.pop_back_val();
11612 for (auto *Cand : Candidates) {
11613 if (Cand->Viable && !Cand->Best &&
11614 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11615 PendingBest.push_back(Cand);
11616 Cand->Best = true;
11617
11619 Curr->Function))
11620 EquivalentCands.push_back(Cand->Function);
11621 else
11622 Best = end();
11623 }
11624 }
11625 }
11626
11627 if (Best == end())
11628 return OR_Ambiguous;
11629
11630 OverloadingResult R = ResultForBestCandidate(Best);
11631
11632 if (!EquivalentCands.empty())
11634 EquivalentCands);
11635 return R;
11636}
11637
11638namespace {
11639
11640enum OverloadCandidateKind {
11641 oc_function,
11642 oc_method,
11643 oc_reversed_binary_operator,
11644 oc_constructor,
11645 oc_implicit_default_constructor,
11646 oc_implicit_copy_constructor,
11647 oc_implicit_move_constructor,
11648 oc_implicit_copy_assignment,
11649 oc_implicit_move_assignment,
11650 oc_implicit_equality_comparison,
11651 oc_inherited_constructor
11652};
11653
11654enum OverloadCandidateSelect {
11655 ocs_non_template,
11656 ocs_template,
11657 ocs_described_template,
11658};
11659
11660static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11661ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11662 const FunctionDecl *Fn,
11664 std::string &Description) {
11665
11666 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11667 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11668 isTemplate = true;
11669 Description = S.getTemplateArgumentBindingsText(
11670 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11671 }
11672
11673 OverloadCandidateSelect Select = [&]() {
11674 if (!Description.empty())
11675 return ocs_described_template;
11676 return isTemplate ? ocs_template : ocs_non_template;
11677 }();
11678
11679 OverloadCandidateKind Kind = [&]() {
11680 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11681 return oc_implicit_equality_comparison;
11682
11683 if (CRK & CRK_Reversed)
11684 return oc_reversed_binary_operator;
11685
11686 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11687 if (!Ctor->isImplicit()) {
11689 return oc_inherited_constructor;
11690 else
11691 return oc_constructor;
11692 }
11693
11694 if (Ctor->isDefaultConstructor())
11695 return oc_implicit_default_constructor;
11696
11697 if (Ctor->isMoveConstructor())
11698 return oc_implicit_move_constructor;
11699
11700 assert(Ctor->isCopyConstructor() &&
11701 "unexpected sort of implicit constructor");
11702 return oc_implicit_copy_constructor;
11703 }
11704
11705 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11706 // This actually gets spelled 'candidate function' for now, but
11707 // it doesn't hurt to split it out.
11708 if (!Meth->isImplicit())
11709 return oc_method;
11710
11711 if (Meth->isMoveAssignmentOperator())
11712 return oc_implicit_move_assignment;
11713
11714 if (Meth->isCopyAssignmentOperator())
11715 return oc_implicit_copy_assignment;
11716
11717 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11718 return oc_method;
11719 }
11720
11721 return oc_function;
11722 }();
11723
11724 return std::make_pair(Kind, Select);
11725}
11726
11727void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11728 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11729 // set.
11730 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11731 S.Diag(FoundDecl->getLocation(),
11732 diag::note_ovl_candidate_inherited_constructor)
11733 << Shadow->getNominatedBaseClass();
11734}
11735
11736} // end anonymous namespace
11737
11739 const FunctionDecl *FD) {
11740 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11741 bool AlwaysTrue;
11742 if (EnableIf->getCond()->isValueDependent() ||
11743 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11744 return false;
11745 if (!AlwaysTrue)
11746 return false;
11747 }
11748 return true;
11749}
11750
11751/// Returns true if we can take the address of the function.
11752///
11753/// \param Complain - If true, we'll emit a diagnostic
11754/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11755/// we in overload resolution?
11756/// \param Loc - The location of the statement we're complaining about. Ignored
11757/// if we're not complaining, or if we're in overload resolution.
11759 bool Complain,
11760 bool InOverloadResolution,
11761 SourceLocation Loc) {
11762 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11763 if (Complain) {
11764 if (InOverloadResolution)
11765 S.Diag(FD->getBeginLoc(),
11766 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11767 else
11768 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11769 }
11770 return false;
11771 }
11772
11773 if (FD->getTrailingRequiresClause()) {
11774 ConstraintSatisfaction Satisfaction;
11775 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11776 return false;
11777 if (!Satisfaction.IsSatisfied) {
11778 if (Complain) {
11779 if (InOverloadResolution) {
11780 SmallString<128> TemplateArgString;
11781 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11782 TemplateArgString += " ";
11783 TemplateArgString += S.getTemplateArgumentBindingsText(
11784 FunTmpl->getTemplateParameters(),
11786 }
11787
11788 S.Diag(FD->getBeginLoc(),
11789 diag::note_ovl_candidate_unsatisfied_constraints)
11790 << TemplateArgString;
11791 } else
11792 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11793 << FD;
11794 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11795 }
11796 return false;
11797 }
11798 }
11799
11800 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11801 return P->hasAttr<PassObjectSizeAttr>();
11802 });
11803 if (I == FD->param_end())
11804 return true;
11805
11806 if (Complain) {
11807 // Add one to ParamNo because it's user-facing
11808 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11809 if (InOverloadResolution)
11810 S.Diag(FD->getLocation(),
11811 diag::note_ovl_candidate_has_pass_object_size_params)
11812 << ParamNo;
11813 else
11814 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11815 << FD << ParamNo;
11816 }
11817 return false;
11818}
11819
11821 const FunctionDecl *FD) {
11822 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11823 /*InOverloadResolution=*/true,
11824 /*Loc=*/SourceLocation());
11825}
11826
11828 bool Complain,
11829 SourceLocation Loc) {
11830 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11831 /*InOverloadResolution=*/false,
11832 Loc);
11833}
11834
11835// Don't print candidates other than the one that matches the calling
11836// convention of the call operator, since that is guaranteed to exist.
11838 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11839
11840 if (!ConvD)
11841 return false;
11842 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11843 if (!RD->isLambda())
11844 return false;
11845
11846 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11847 CallingConv CallOpCC =
11848 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11849 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11850 CallingConv ConvToCC =
11851 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11852
11853 return ConvToCC != CallOpCC;
11854}
11855
11856// Notes the location of an overload candidate.
11858 OverloadCandidateRewriteKind RewriteKind,
11859 QualType DestType, bool TakingAddress) {
11860 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11861 return;
11862 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11863 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11864 return;
11865 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11866 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11867 return;
11869 return;
11870
11871 std::string FnDesc;
11872 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11873 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11874 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11875 << (unsigned)KSPair.first << (unsigned)KSPair.second
11876 << Fn << FnDesc;
11877
11878 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11879 Diag(Fn->getLocation(), PD);
11880 MaybeEmitInheritedConstructorNote(*this, Found);
11881}
11882
11883static void
11885 // Perhaps the ambiguity was caused by two atomic constraints that are
11886 // 'identical' but not equivalent:
11887 //
11888 // void foo() requires (sizeof(T) > 4) { } // #1
11889 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11890 //
11891 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11892 // #2 to subsume #1, but these constraint are not considered equivalent
11893 // according to the subsumption rules because they are not the same
11894 // source-level construct. This behavior is quite confusing and we should try
11895 // to help the user figure out what happened.
11896
11897 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11898 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11899 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11900 if (!I->Function)
11901 continue;
11903 if (auto *Template = I->Function->getPrimaryTemplate())
11904 Template->getAssociatedConstraints(AC);
11905 else
11906 I->Function->getAssociatedConstraints(AC);
11907 if (AC.empty())
11908 continue;
11909 if (FirstCand == nullptr) {
11910 FirstCand = I->Function;
11911 FirstAC = AC;
11912 } else if (SecondCand == nullptr) {
11913 SecondCand = I->Function;
11914 SecondAC = AC;
11915 } else {
11916 // We have more than one pair of constrained functions - this check is
11917 // expensive and we'd rather not try to diagnose it.
11918 return;
11919 }
11920 }
11921 if (!SecondCand)
11922 return;
11923 // The diagnostic can only happen if there are associated constraints on
11924 // both sides (there needs to be some identical atomic constraint).
11925 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11926 SecondCand, SecondAC))
11927 // Just show the user one diagnostic, they'll probably figure it out
11928 // from here.
11929 return;
11930}
11931
11932// Notes the location of all overload candidates designated through
11933// OverloadedExpr
11934void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11935 bool TakingAddress) {
11936 assert(OverloadedExpr->getType() == Context.OverloadTy);
11937
11938 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11939 OverloadExpr *OvlExpr = Ovl.Expression;
11940
11941 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11942 IEnd = OvlExpr->decls_end();
11943 I != IEnd; ++I) {
11944 if (FunctionTemplateDecl *FunTmpl =
11945 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11946 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11947 TakingAddress);
11948 } else if (FunctionDecl *Fun
11949 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11950 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11951 }
11952 }
11953}
11954
11955/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11956/// "lead" diagnostic; it will be given two arguments, the source and
11957/// target types of the conversion.
11959 Sema &S,
11960 SourceLocation CaretLoc,
11961 const PartialDiagnostic &PDiag) const {
11962 S.Diag(CaretLoc, PDiag)
11963 << Ambiguous.getFromType() << Ambiguous.getToType();
11964 unsigned CandsShown = 0;
11966 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11967 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11968 break;
11969 ++CandsShown;
11970 S.NoteOverloadCandidate(I->first, I->second);
11971 }
11972 S.Diags.overloadCandidatesShown(CandsShown);
11973 if (I != E)
11974 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11975}
11976
11978 unsigned I, bool TakingCandidateAddress) {
11979 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11980 assert(Conv.isBad());
11981 assert(Cand->Function && "for now, candidate must be a function");
11982 FunctionDecl *Fn = Cand->Function;
11983
11984 // There's a conversion slot for the object argument if this is a
11985 // non-constructor method. Note that 'I' corresponds the
11986 // conversion-slot index.
11987 bool isObjectArgument = false;
11988 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11990 if (I == 0)
11991 isObjectArgument = true;
11992 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
11993 I--;
11994 }
11995
11996 std::string FnDesc;
11997 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11998 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11999 FnDesc);
12000
12001 Expr *FromExpr = Conv.Bad.FromExpr;
12002 QualType FromTy = Conv.Bad.getFromType();
12003 QualType ToTy = Conv.Bad.getToType();
12004 SourceRange ToParamRange;
12005
12006 // FIXME: In presence of parameter packs we can't determine parameter range
12007 // reliably, as we don't have access to instantiation.
12008 bool HasParamPack =
12009 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12010 return Parm->isParameterPack();
12011 });
12012 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12013 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12014
12015 if (FromTy == S.Context.OverloadTy) {
12016 assert(FromExpr && "overload set argument came from implicit argument?");
12017 Expr *E = FromExpr->IgnoreParens();
12018 if (isa<UnaryOperator>(E))
12019 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12020 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12021
12022 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12023 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12024 << ToParamRange << ToTy << Name << I + 1;
12025 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12026 return;
12027 }
12028
12029 // Do some hand-waving analysis to see if the non-viability is due
12030 // to a qualifier mismatch.
12031 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12032 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12033 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12034 CToTy = RT->getPointeeType();
12035 else {
12036 // TODO: detect and diagnose the full richness of const mismatches.
12037 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12038 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12039 CFromTy = FromPT->getPointeeType();
12040 CToTy = ToPT->getPointeeType();
12041 }
12042 }
12043
12044 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12045 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12046 Qualifiers FromQs = CFromTy.getQualifiers();
12047 Qualifiers ToQs = CToTy.getQualifiers();
12048
12049 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12050 if (isObjectArgument)
12051 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12052 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12053 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12054 else
12055 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12056 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12057 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12058 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12059 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12060 return;
12061 }
12062
12063 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12064 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12065 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12066 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12067 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12068 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12069 return;
12070 }
12071
12072 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12073 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12074 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12075 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12076 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12077 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12078 return;
12079 }
12080
12081 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12083 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12084 << FromTy << !!FromQs.getPointerAuth()
12085 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12086 << ToQs.getPointerAuth().getAsString() << I + 1
12087 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12088 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12089 return;
12090 }
12091
12092 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12093 assert(CVR && "expected qualifiers mismatch");
12094
12095 if (isObjectArgument) {
12096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12097 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12098 << FromTy << (CVR - 1);
12099 } else {
12100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12101 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12102 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12103 }
12104 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12105 return;
12106 }
12107
12110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12111 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12112 << (unsigned)isObjectArgument << I + 1
12114 << ToParamRange;
12115 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12116 return;
12117 }
12118
12119 // Special diagnostic for failure to convert an initializer list, since
12120 // telling the user that it has type void is not useful.
12121 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12123 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12124 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12127 ? 2
12128 : 0);
12129 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12130 return;
12131 }
12132
12133 // Diagnose references or pointers to incomplete types differently,
12134 // since it's far from impossible that the incompleteness triggered
12135 // the failure.
12136 QualType TempFromTy = FromTy.getNonReferenceType();
12137 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12138 TempFromTy = PTy->getPointeeType();
12139 if (TempFromTy->isIncompleteType()) {
12140 // Emit the generic diagnostic and, optionally, add the hints to it.
12141 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12142 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12143 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12144 << (unsigned)(Cand->Fix.Kind);
12145
12146 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12147 return;
12148 }
12149
12150 // Diagnose base -> derived pointer conversions.
12151 unsigned BaseToDerivedConversion = 0;
12152 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12153 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12154 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12155 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12156 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12157 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12158 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12159 FromPtrTy->getPointeeType()))
12160 BaseToDerivedConversion = 1;
12161 }
12162 } else if (const ObjCObjectPointerType *FromPtrTy
12163 = FromTy->getAs<ObjCObjectPointerType>()) {
12164 if (const ObjCObjectPointerType *ToPtrTy
12165 = ToTy->getAs<ObjCObjectPointerType>())
12166 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12167 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12168 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12169 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12170 FromIface->isSuperClassOf(ToIface))
12171 BaseToDerivedConversion = 2;
12172 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12173 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12174 S.getASTContext()) &&
12175 !FromTy->isIncompleteType() &&
12176 !ToRefTy->getPointeeType()->isIncompleteType() &&
12177 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12178 BaseToDerivedConversion = 3;
12179 }
12180 }
12181
12182 if (BaseToDerivedConversion) {
12183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12184 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12185 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12186 << I + 1;
12187 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12188 return;
12189 }
12190
12191 if (isa<ObjCObjectPointerType>(CFromTy) &&
12192 isa<PointerType>(CToTy)) {
12193 Qualifiers FromQs = CFromTy.getQualifiers();
12194 Qualifiers ToQs = CToTy.getQualifiers();
12195 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12196 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12197 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12198 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12199 << I + 1;
12200 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12201 return;
12202 }
12203 }
12204
12205 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12206 return;
12207
12208 // Emit the generic diagnostic and, optionally, add the hints to it.
12209 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12210 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12211 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12212 << (unsigned)(Cand->Fix.Kind);
12213
12214 // Check that location of Fn is not in system header.
12215 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12216 // If we can fix the conversion, suggest the FixIts.
12217 for (const FixItHint &HI : Cand->Fix.Hints)
12218 FDiag << HI;
12219 }
12220
12221 S.Diag(Fn->getLocation(), FDiag);
12222
12223 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12224}
12225
12226/// Additional arity mismatch diagnosis specific to a function overload
12227/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12228/// over a candidate in any candidate set.
12230 unsigned NumArgs, bool IsAddressOf = false) {
12231 assert(Cand->Function && "Candidate is required to be a function.");
12232 FunctionDecl *Fn = Cand->Function;
12233 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12234 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12235
12236 // With invalid overloaded operators, it's possible that we think we
12237 // have an arity mismatch when in fact it looks like we have the
12238 // right number of arguments, because only overloaded operators have
12239 // the weird behavior of overloading member and non-member functions.
12240 // Just don't report anything.
12241 if (Fn->isInvalidDecl() &&
12242 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12243 return true;
12244
12245 if (NumArgs < MinParams) {
12246 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12248 Cand->DeductionFailure.getResult() ==
12250 } else {
12251 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12253 Cand->DeductionFailure.getResult() ==
12255 }
12256
12257 return false;
12258}
12259
12260/// General arity mismatch diagnosis over a candidate in a candidate set.
12262 unsigned NumFormalArgs,
12263 bool IsAddressOf = false) {
12264 assert(isa<FunctionDecl>(D) &&
12265 "The templated declaration should at least be a function"
12266 " when diagnosing bad template argument deduction due to too many"
12267 " or too few arguments");
12268
12270
12271 // TODO: treat calls to a missing default constructor as a special case
12272 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12273 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12274 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12275
12276 // at least / at most / exactly
12277 bool HasExplicitObjectParam =
12278 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12279
12280 unsigned ParamCount =
12281 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12282 unsigned mode, modeCount;
12283
12284 if (NumFormalArgs < MinParams) {
12285 if (MinParams != ParamCount || FnTy->isVariadic() ||
12286 FnTy->isTemplateVariadic())
12287 mode = 0; // "at least"
12288 else
12289 mode = 2; // "exactly"
12290 modeCount = MinParams;
12291 } else {
12292 if (MinParams != ParamCount)
12293 mode = 1; // "at most"
12294 else
12295 mode = 2; // "exactly"
12296 modeCount = ParamCount;
12297 }
12298
12299 std::string Description;
12300 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12301 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12302
12303 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12304 if (modeCount == 1 && !IsAddressOf &&
12305 FirstNonObjectParamIdx < Fn->getNumParams() &&
12306 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12307 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12308 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12309 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12310 << NumFormalArgs << HasExplicitObjectParam
12311 << Fn->getParametersSourceRange();
12312 else
12313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12314 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12315 << Description << mode << modeCount << NumFormalArgs
12316 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12317
12318 MaybeEmitInheritedConstructorNote(S, Found);
12319}
12320
12321/// Arity mismatch diagnosis specific to a function overload candidate.
12323 unsigned NumFormalArgs) {
12324 assert(Cand->Function && "Candidate must be a function");
12325 FunctionDecl *Fn = Cand->Function;
12326 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12327 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12328 Cand->TookAddressOfOverload);
12329}
12330
12332 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12333 return TD;
12334 llvm_unreachable("Unsupported: Getting the described template declaration"
12335 " for bad deduction diagnosis");
12336}
12337
12338/// Diagnose a failed template-argument deduction.
12339static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12340 DeductionFailureInfo &DeductionFailure,
12341 unsigned NumArgs,
12342 bool TakingCandidateAddress) {
12343 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12344 NamedDecl *ParamD;
12345 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12346 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12347 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12348 switch (DeductionFailure.getResult()) {
12350 llvm_unreachable(
12351 "TemplateDeductionResult::Success while diagnosing bad deduction");
12353 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12354 "while diagnosing bad deduction");
12357 return;
12358
12360 assert(ParamD && "no parameter found for incomplete deduction result");
12361 S.Diag(Templated->getLocation(),
12362 diag::note_ovl_candidate_incomplete_deduction)
12363 << ParamD->getDeclName();
12364 MaybeEmitInheritedConstructorNote(S, Found);
12365 return;
12366 }
12367
12369 assert(ParamD && "no parameter found for incomplete deduction result");
12370 S.Diag(Templated->getLocation(),
12371 diag::note_ovl_candidate_incomplete_deduction_pack)
12372 << ParamD->getDeclName()
12373 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12374 << *DeductionFailure.getFirstArg();
12375 MaybeEmitInheritedConstructorNote(S, Found);
12376 return;
12377 }
12378
12380 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12382
12383 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12384
12385 // Param will have been canonicalized, but it should just be a
12386 // qualified version of ParamD, so move the qualifiers to that.
12388 Qs.strip(Param);
12389 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12390 assert(S.Context.hasSameType(Param, NonCanonParam));
12391
12392 // Arg has also been canonicalized, but there's nothing we can do
12393 // about that. It also doesn't matter as much, because it won't
12394 // have any template parameters in it (because deduction isn't
12395 // done on dependent types).
12396 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12397
12398 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12399 << ParamD->getDeclName() << Arg << NonCanonParam;
12400 MaybeEmitInheritedConstructorNote(S, Found);
12401 return;
12402 }
12403
12405 assert(ParamD && "no parameter found for inconsistent deduction result");
12406 int which = 0;
12407 if (isa<TemplateTypeParmDecl>(ParamD))
12408 which = 0;
12409 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12410 // Deduction might have failed because we deduced arguments of two
12411 // different types for a non-type template parameter.
12412 // FIXME: Use a different TDK value for this.
12413 QualType T1 =
12414 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12415 QualType T2 =
12416 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12417 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12418 S.Diag(Templated->getLocation(),
12419 diag::note_ovl_candidate_inconsistent_deduction_types)
12420 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12421 << *DeductionFailure.getSecondArg() << T2;
12422 MaybeEmitInheritedConstructorNote(S, Found);
12423 return;
12424 }
12425
12426 which = 1;
12427 } else {
12428 which = 2;
12429 }
12430
12431 // Tweak the diagnostic if the problem is that we deduced packs of
12432 // different arities. We'll print the actual packs anyway in case that
12433 // includes additional useful information.
12434 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12435 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12436 DeductionFailure.getFirstArg()->pack_size() !=
12437 DeductionFailure.getSecondArg()->pack_size()) {
12438 which = 3;
12439 }
12440
12441 S.Diag(Templated->getLocation(),
12442 diag::note_ovl_candidate_inconsistent_deduction)
12443 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12444 << *DeductionFailure.getSecondArg();
12445 MaybeEmitInheritedConstructorNote(S, Found);
12446 return;
12447 }
12448
12450 assert(ParamD && "no parameter found for invalid explicit arguments");
12451 if (ParamD->getDeclName())
12452 S.Diag(Templated->getLocation(),
12453 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12454 << ParamD->getDeclName();
12455 else {
12456 int index = 0;
12457 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12458 index = TTP->getIndex();
12459 else if (NonTypeTemplateParmDecl *NTTP
12460 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12461 index = NTTP->getIndex();
12462 else
12463 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12464 S.Diag(Templated->getLocation(),
12465 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12466 << (index + 1);
12467 }
12468 MaybeEmitInheritedConstructorNote(S, Found);
12469 return;
12470
12472 // Format the template argument list into the argument string.
12473 SmallString<128> TemplateArgString;
12474 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12475 TemplateArgString = " ";
12476 TemplateArgString += S.getTemplateArgumentBindingsText(
12477 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12478 if (TemplateArgString.size() == 1)
12479 TemplateArgString.clear();
12480 S.Diag(Templated->getLocation(),
12481 diag::note_ovl_candidate_unsatisfied_constraints)
12482 << TemplateArgString;
12483
12485 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12486 return;
12487 }
12490 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12491 return;
12492
12494 S.Diag(Templated->getLocation(),
12495 diag::note_ovl_candidate_instantiation_depth);
12496 MaybeEmitInheritedConstructorNote(S, Found);
12497 return;
12498
12500 // Format the template argument list into the argument string.
12501 SmallString<128> TemplateArgString;
12502 if (TemplateArgumentList *Args =
12503 DeductionFailure.getTemplateArgumentList()) {
12504 TemplateArgString = " ";
12505 TemplateArgString += S.getTemplateArgumentBindingsText(
12506 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12507 if (TemplateArgString.size() == 1)
12508 TemplateArgString.clear();
12509 }
12510
12511 // If this candidate was disabled by enable_if, say so.
12512 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12513 if (PDiag && PDiag->second.getDiagID() ==
12514 diag::err_typename_nested_not_found_enable_if) {
12515 // FIXME: Use the source range of the condition, and the fully-qualified
12516 // name of the enable_if template. These are both present in PDiag.
12517 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12518 << "'enable_if'" << TemplateArgString;
12519 return;
12520 }
12521
12522 // We found a specific requirement that disabled the enable_if.
12523 if (PDiag && PDiag->second.getDiagID() ==
12524 diag::err_typename_nested_not_found_requirement) {
12525 S.Diag(Templated->getLocation(),
12526 diag::note_ovl_candidate_disabled_by_requirement)
12527 << PDiag->second.getStringArg(0) << TemplateArgString;
12528 return;
12529 }
12530
12531 // Format the SFINAE diagnostic into the argument string.
12532 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12533 // formatted message in another diagnostic.
12534 SmallString<128> SFINAEArgString;
12535 SourceRange R;
12536 if (PDiag) {
12537 SFINAEArgString = ": ";
12538 R = SourceRange(PDiag->first, PDiag->first);
12539 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12540 }
12541
12542 S.Diag(Templated->getLocation(),
12543 diag::note_ovl_candidate_substitution_failure)
12544 << TemplateArgString << SFINAEArgString << R;
12545 MaybeEmitInheritedConstructorNote(S, Found);
12546 return;
12547 }
12548
12551 // Format the template argument list into the argument string.
12552 SmallString<128> TemplateArgString;
12553 if (TemplateArgumentList *Args =
12554 DeductionFailure.getTemplateArgumentList()) {
12555 TemplateArgString = " ";
12556 TemplateArgString += S.getTemplateArgumentBindingsText(
12557 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12558 if (TemplateArgString.size() == 1)
12559 TemplateArgString.clear();
12560 }
12561
12562 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12563 << (*DeductionFailure.getCallArgIndex() + 1)
12564 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12565 << TemplateArgString
12566 << (DeductionFailure.getResult() ==
12568 break;
12569 }
12570
12572 // FIXME: Provide a source location to indicate what we couldn't match.
12573 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12574 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12575 if (FirstTA.getKind() == TemplateArgument::Template &&
12576 SecondTA.getKind() == TemplateArgument::Template) {
12577 TemplateName FirstTN = FirstTA.getAsTemplate();
12578 TemplateName SecondTN = SecondTA.getAsTemplate();
12579 if (FirstTN.getKind() == TemplateName::Template &&
12580 SecondTN.getKind() == TemplateName::Template) {
12581 if (FirstTN.getAsTemplateDecl()->getName() ==
12582 SecondTN.getAsTemplateDecl()->getName()) {
12583 // FIXME: This fixes a bad diagnostic where both templates are named
12584 // the same. This particular case is a bit difficult since:
12585 // 1) It is passed as a string to the diagnostic printer.
12586 // 2) The diagnostic printer only attempts to find a better
12587 // name for types, not decls.
12588 // Ideally, this should folded into the diagnostic printer.
12589 S.Diag(Templated->getLocation(),
12590 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12591 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12592 return;
12593 }
12594 }
12595 }
12596
12597 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12599 return;
12600
12601 // FIXME: For generic lambda parameters, check if the function is a lambda
12602 // call operator, and if so, emit a prettier and more informative
12603 // diagnostic that mentions 'auto' and lambda in addition to
12604 // (or instead of?) the canonical template type parameters.
12605 S.Diag(Templated->getLocation(),
12606 diag::note_ovl_candidate_non_deduced_mismatch)
12607 << FirstTA << SecondTA;
12608 return;
12609 }
12610 // TODO: diagnose these individually, then kill off
12611 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12613 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12614 MaybeEmitInheritedConstructorNote(S, Found);
12615 return;
12617 S.Diag(Templated->getLocation(),
12618 diag::note_cuda_ovl_candidate_target_mismatch);
12619 return;
12620 }
12621}
12622
12623/// Diagnose a failed template-argument deduction, for function calls.
12625 unsigned NumArgs,
12626 bool TakingCandidateAddress) {
12627 assert(Cand->Function && "Candidate must be a function");
12628 FunctionDecl *Fn = Cand->Function;
12632 if (CheckArityMismatch(S, Cand, NumArgs))
12633 return;
12634 }
12635 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12636 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12637}
12638
12639/// CUDA: diagnose an invalid call across targets.
12641 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12642 assert(Cand->Function && "Candidate must be a Function.");
12643 FunctionDecl *Callee = Cand->Function;
12644
12645 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12646 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12647
12648 std::string FnDesc;
12649 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12650 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12651 Cand->getRewriteKind(), FnDesc);
12652
12653 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12654 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12655 << FnDesc /* Ignored */
12656 << CalleeTarget << CallerTarget;
12657
12658 // This could be an implicit constructor for which we could not infer the
12659 // target due to a collsion. Diagnose that case.
12660 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12661 if (Meth != nullptr && Meth->isImplicit()) {
12662 CXXRecordDecl *ParentClass = Meth->getParent();
12664
12665 switch (FnKindPair.first) {
12666 default:
12667 return;
12668 case oc_implicit_default_constructor:
12670 break;
12671 case oc_implicit_copy_constructor:
12673 break;
12674 case oc_implicit_move_constructor:
12676 break;
12677 case oc_implicit_copy_assignment:
12679 break;
12680 case oc_implicit_move_assignment:
12682 break;
12683 };
12684
12685 bool ConstRHS = false;
12686 if (Meth->getNumParams()) {
12687 if (const ReferenceType *RT =
12688 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12689 ConstRHS = RT->getPointeeType().isConstQualified();
12690 }
12691 }
12692
12693 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12694 /* ConstRHS */ ConstRHS,
12695 /* Diagnose */ true);
12696 }
12697}
12698
12700 assert(Cand->Function && "Candidate must be a function");
12701 FunctionDecl *Callee = Cand->Function;
12702 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12703
12704 S.Diag(Callee->getLocation(),
12705 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12706 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12707}
12708
12710 assert(Cand->Function && "Candidate must be a function");
12711 FunctionDecl *Fn = Cand->Function;
12713 assert(ES.isExplicit() && "not an explicit candidate");
12714
12715 unsigned Kind;
12716 switch (Fn->getDeclKind()) {
12717 case Decl::Kind::CXXConstructor:
12718 Kind = 0;
12719 break;
12720 case Decl::Kind::CXXConversion:
12721 Kind = 1;
12722 break;
12723 case Decl::Kind::CXXDeductionGuide:
12724 Kind = Fn->isImplicit() ? 0 : 2;
12725 break;
12726 default:
12727 llvm_unreachable("invalid Decl");
12728 }
12729
12730 // Note the location of the first (in-class) declaration; a redeclaration
12731 // (particularly an out-of-class definition) will typically lack the
12732 // 'explicit' specifier.
12733 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12734 FunctionDecl *First = Fn->getFirstDecl();
12735 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12736 First = Pattern->getFirstDecl();
12737
12738 S.Diag(First->getLocation(),
12739 diag::note_ovl_candidate_explicit)
12740 << Kind << (ES.getExpr() ? 1 : 0)
12741 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12742}
12743
12745 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12746 if (!DG)
12747 return;
12748 TemplateDecl *OriginTemplate =
12750 // We want to always print synthesized deduction guides for type aliases.
12751 // They would retain the explicit bit of the corresponding constructor.
12752 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12753 return;
12754 std::string FunctionProto;
12755 llvm::raw_string_ostream OS(FunctionProto);
12756 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12757 if (!Template) {
12758 // This also could be an instantiation. Find out the primary template.
12759 FunctionDecl *Pattern =
12760 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12761 if (!Pattern) {
12762 // The implicit deduction guide is built on an explicit non-template
12763 // deduction guide. Currently, this might be the case only for type
12764 // aliases.
12765 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12766 // gets merged.
12767 assert(OriginTemplate->isTypeAlias() &&
12768 "Non-template implicit deduction guides are only possible for "
12769 "type aliases");
12770 DG->print(OS);
12771 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12772 << FunctionProto;
12773 return;
12774 }
12776 assert(Template && "Cannot find the associated function template of "
12777 "CXXDeductionGuideDecl?");
12778 }
12779 Template->print(OS);
12780 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12781 << FunctionProto;
12782}
12783
12784/// Generates a 'note' diagnostic for an overload candidate. We've
12785/// already generated a primary error at the call site.
12786///
12787/// It really does need to be a single diagnostic with its caret
12788/// pointed at the candidate declaration. Yes, this creates some
12789/// major challenges of technical writing. Yes, this makes pointing
12790/// out problems with specific arguments quite awkward. It's still
12791/// better than generating twenty screens of text for every failed
12792/// overload.
12793///
12794/// It would be great to be able to express per-candidate problems
12795/// more richly for those diagnostic clients that cared, but we'd
12796/// still have to be just as careful with the default diagnostics.
12797/// \param CtorDestAS Addr space of object being constructed (for ctor
12798/// candidates only).
12800 unsigned NumArgs,
12801 bool TakingCandidateAddress,
12802 LangAS CtorDestAS = LangAS::Default) {
12803 assert(Cand->Function && "Candidate must be a function");
12804 FunctionDecl *Fn = Cand->Function;
12806 return;
12807
12808 // There is no physical candidate declaration to point to for OpenCL builtins.
12809 // Except for failed conversions, the notes are identical for each candidate,
12810 // so do not generate such notes.
12811 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12813 return;
12814
12815 // Skip implicit member functions when trying to resolve
12816 // the address of a an overload set for a function pointer.
12817 if (Cand->TookAddressOfOverload &&
12818 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12819 return;
12820
12821 // Note deleted candidates, but only if they're viable.
12822 if (Cand->Viable) {
12823 if (Fn->isDeleted()) {
12824 std::string FnDesc;
12825 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12826 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12827 Cand->getRewriteKind(), FnDesc);
12828
12829 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12830 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12831 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12832 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12833 return;
12834 }
12835
12836 // We don't really have anything else to say about viable candidates.
12837 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12838 return;
12839 }
12840
12841 // If this is a synthesized deduction guide we're deducing against, add a note
12842 // for it. These deduction guides are not explicitly spelled in the source
12843 // code, so simply printing a deduction failure note mentioning synthesized
12844 // template parameters or pointing to the header of the surrounding RecordDecl
12845 // would be confusing.
12846 //
12847 // We prefer adding such notes at the end of the deduction failure because
12848 // duplicate code snippets appearing in the diagnostic would likely become
12849 // noisy.
12850 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12851
12852 switch (Cand->FailureKind) {
12855 return DiagnoseArityMismatch(S, Cand, NumArgs);
12856
12858 return DiagnoseBadDeduction(S, Cand, NumArgs,
12859 TakingCandidateAddress);
12860
12862 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12863 << (Fn->getPrimaryTemplate() ? 1 : 0);
12864 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12865 return;
12866 }
12867
12869 Qualifiers QualsForPrinting;
12870 QualsForPrinting.setAddressSpace(CtorDestAS);
12871 S.Diag(Fn->getLocation(),
12872 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12873 << QualsForPrinting;
12874 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12875 return;
12876 }
12877
12881 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12882
12884 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12885 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12886 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12887 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12888
12889 // FIXME: this currently happens when we're called from SemaInit
12890 // when user-conversion overload fails. Figure out how to handle
12891 // those conditions and diagnose them well.
12892 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12893 }
12894
12896 return DiagnoseBadTarget(S, Cand);
12897
12898 case ovl_fail_enable_if:
12899 return DiagnoseFailedEnableIfAttr(S, Cand);
12900
12901 case ovl_fail_explicit:
12902 return DiagnoseFailedExplicitSpec(S, Cand);
12903
12905 // It's generally not interesting to note copy/move constructors here.
12906 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12907 return;
12908 S.Diag(Fn->getLocation(),
12909 diag::note_ovl_candidate_inherited_constructor_slice)
12910 << (Fn->getPrimaryTemplate() ? 1 : 0)
12911 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12912 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12913 return;
12914
12916 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12917 (void)Available;
12918 assert(!Available);
12919 break;
12920 }
12922 // Do nothing, these should simply be ignored.
12923 break;
12924
12926 std::string FnDesc;
12927 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12928 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12929 Cand->getRewriteKind(), FnDesc);
12930
12931 S.Diag(Fn->getLocation(),
12932 diag::note_ovl_candidate_constraints_not_satisfied)
12933 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12934 << FnDesc /* Ignored */;
12935 ConstraintSatisfaction Satisfaction;
12936 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12937 /*ForOverloadResolution=*/true))
12938 break;
12939 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12940 }
12941 }
12942}
12943
12946 return;
12947
12948 // Desugar the type of the surrogate down to a function type,
12949 // retaining as many typedefs as possible while still showing
12950 // the function type (and, therefore, its parameter types).
12951 QualType FnType = Cand->Surrogate->getConversionType();
12952 bool isLValueReference = false;
12953 bool isRValueReference = false;
12954 bool isPointer = false;
12955 if (const LValueReferenceType *FnTypeRef =
12956 FnType->getAs<LValueReferenceType>()) {
12957 FnType = FnTypeRef->getPointeeType();
12958 isLValueReference = true;
12959 } else if (const RValueReferenceType *FnTypeRef =
12960 FnType->getAs<RValueReferenceType>()) {
12961 FnType = FnTypeRef->getPointeeType();
12962 isRValueReference = true;
12963 }
12964 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12965 FnType = FnTypePtr->getPointeeType();
12966 isPointer = true;
12967 }
12968 // Desugar down to a function type.
12969 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12970 // Reconstruct the pointer/reference as appropriate.
12971 if (isPointer) FnType = S.Context.getPointerType(FnType);
12972 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12973 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12974
12975 if (!Cand->Viable &&
12977 S.Diag(Cand->Surrogate->getLocation(),
12978 diag::note_ovl_surrogate_constraints_not_satisfied)
12979 << Cand->Surrogate;
12980 ConstraintSatisfaction Satisfaction;
12981 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12982 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12983 } else {
12984 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12985 << FnType;
12986 }
12987}
12988
12989static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12990 SourceLocation OpLoc,
12991 OverloadCandidate *Cand) {
12992 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12993 std::string TypeStr("operator");
12994 TypeStr += Opc;
12995 TypeStr += "(";
12996 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12997 if (Cand->Conversions.size() == 1) {
12998 TypeStr += ")";
12999 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13000 } else {
13001 TypeStr += ", ";
13002 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13003 TypeStr += ")";
13004 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13005 }
13006}
13007
13009 OverloadCandidate *Cand) {
13010 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13011 if (ICS.isBad()) break; // all meaningless after first invalid
13012 if (!ICS.isAmbiguous()) continue;
13013
13015 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13016 }
13017}
13018
13020 if (Cand->Function)
13021 return Cand->Function->getLocation();
13022 if (Cand->IsSurrogate)
13023 return Cand->Surrogate->getLocation();
13024 return SourceLocation();
13025}
13026
13027static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13028 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13032 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13033
13037 return 1;
13038
13041 return 2;
13042
13050 return 3;
13051
13053 return 4;
13054
13056 return 5;
13057
13060 return 6;
13061 }
13062 llvm_unreachable("Unhandled deduction result");
13063}
13064
13065namespace {
13066
13067struct CompareOverloadCandidatesForDisplay {
13068 Sema &S;
13069 SourceLocation Loc;
13070 size_t NumArgs;
13072
13073 CompareOverloadCandidatesForDisplay(
13074 Sema &S, SourceLocation Loc, size_t NArgs,
13076 : S(S), NumArgs(NArgs), CSK(CSK) {}
13077
13078 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13079 // If there are too many or too few arguments, that's the high-order bit we
13080 // want to sort by, even if the immediate failure kind was something else.
13081 if (C->FailureKind == ovl_fail_too_many_arguments ||
13082 C->FailureKind == ovl_fail_too_few_arguments)
13083 return static_cast<OverloadFailureKind>(C->FailureKind);
13084
13085 if (C->Function) {
13086 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13088 if (NumArgs < C->Function->getMinRequiredArguments())
13090 }
13091
13092 return static_cast<OverloadFailureKind>(C->FailureKind);
13093 }
13094
13095 bool operator()(const OverloadCandidate *L,
13096 const OverloadCandidate *R) {
13097 // Fast-path this check.
13098 if (L == R) return false;
13099
13100 // Order first by viability.
13101 if (L->Viable) {
13102 if (!R->Viable) return true;
13103
13104 if (int Ord = CompareConversions(*L, *R))
13105 return Ord < 0;
13106 // Use other tie breakers.
13107 } else if (R->Viable)
13108 return false;
13109
13110 assert(L->Viable == R->Viable);
13111
13112 // Criteria by which we can sort non-viable candidates:
13113 if (!L->Viable) {
13114 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13115 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13116
13117 // 1. Arity mismatches come after other candidates.
13118 if (LFailureKind == ovl_fail_too_many_arguments ||
13119 LFailureKind == ovl_fail_too_few_arguments) {
13120 if (RFailureKind == ovl_fail_too_many_arguments ||
13121 RFailureKind == ovl_fail_too_few_arguments) {
13122 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13123 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13124 if (LDist == RDist) {
13125 if (LFailureKind == RFailureKind)
13126 // Sort non-surrogates before surrogates.
13127 return !L->IsSurrogate && R->IsSurrogate;
13128 // Sort candidates requiring fewer parameters than there were
13129 // arguments given after candidates requiring more parameters
13130 // than there were arguments given.
13131 return LFailureKind == ovl_fail_too_many_arguments;
13132 }
13133 return LDist < RDist;
13134 }
13135 return false;
13136 }
13137 if (RFailureKind == ovl_fail_too_many_arguments ||
13138 RFailureKind == ovl_fail_too_few_arguments)
13139 return true;
13140
13141 // 2. Bad conversions come first and are ordered by the number
13142 // of bad conversions and quality of good conversions.
13143 if (LFailureKind == ovl_fail_bad_conversion) {
13144 if (RFailureKind != ovl_fail_bad_conversion)
13145 return true;
13146
13147 // The conversion that can be fixed with a smaller number of changes,
13148 // comes first.
13149 unsigned numLFixes = L->Fix.NumConversionsFixed;
13150 unsigned numRFixes = R->Fix.NumConversionsFixed;
13151 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13152 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13153 if (numLFixes != numRFixes) {
13154 return numLFixes < numRFixes;
13155 }
13156
13157 // If there's any ordering between the defined conversions...
13158 if (int Ord = CompareConversions(*L, *R))
13159 return Ord < 0;
13160 } else if (RFailureKind == ovl_fail_bad_conversion)
13161 return false;
13162
13163 if (LFailureKind == ovl_fail_bad_deduction) {
13164 if (RFailureKind != ovl_fail_bad_deduction)
13165 return true;
13166
13168 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13169 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13170 if (LRank != RRank)
13171 return LRank < RRank;
13172 }
13173 } else if (RFailureKind == ovl_fail_bad_deduction)
13174 return false;
13175
13176 // TODO: others?
13177 }
13178
13179 // Sort everything else by location.
13180 SourceLocation LLoc = GetLocationForCandidate(L);
13181 SourceLocation RLoc = GetLocationForCandidate(R);
13182
13183 // Put candidates without locations (e.g. builtins) at the end.
13184 if (LLoc.isValid() && RLoc.isValid())
13185 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13186 if (LLoc.isValid() && !RLoc.isValid())
13187 return true;
13188 if (RLoc.isValid() && !LLoc.isValid())
13189 return false;
13190 assert(!LLoc.isValid() && !RLoc.isValid());
13191 // For builtins and other functions without locations, fallback to the order
13192 // in which they were added into the candidate set.
13193 return L < R;
13194 }
13195
13196private:
13197 struct ConversionSignals {
13198 unsigned KindRank = 0;
13200
13201 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13202 ConversionSignals Sig;
13203 Sig.KindRank = Seq.getKindRank();
13204 if (Seq.isStandard())
13205 Sig.Rank = Seq.Standard.getRank();
13206 else if (Seq.isUserDefined())
13207 Sig.Rank = Seq.UserDefined.After.getRank();
13208 // We intend StaticObjectArgumentConversion to compare the same as
13209 // StandardConversion with ICR_ExactMatch rank.
13210 return Sig;
13211 }
13212
13213 static ConversionSignals ForObjectArgument() {
13214 // We intend StaticObjectArgumentConversion to compare the same as
13215 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13216 return {};
13217 }
13218 };
13219
13220 // Returns -1 if conversions in L are considered better.
13221 // 0 if they are considered indistinguishable.
13222 // 1 if conversions in R are better.
13223 int CompareConversions(const OverloadCandidate &L,
13224 const OverloadCandidate &R) {
13225 // We cannot use `isBetterOverloadCandidate` because it is defined
13226 // according to the C++ standard and provides a partial order, but we need
13227 // a total order as this function is used in sort.
13228 assert(L.Conversions.size() == R.Conversions.size());
13229 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13230 auto LS = L.IgnoreObjectArgument && I == 0
13231 ? ConversionSignals::ForObjectArgument()
13232 : ConversionSignals::ForSequence(L.Conversions[I]);
13233 auto RS = R.IgnoreObjectArgument
13234 ? ConversionSignals::ForObjectArgument()
13235 : ConversionSignals::ForSequence(R.Conversions[I]);
13236 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13237 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13238 ? -1
13239 : 1;
13240 }
13241 // FIXME: find a way to compare templates for being more or less
13242 // specialized that provides a strict weak ordering.
13243 return 0;
13244 }
13245};
13246}
13247
13248/// CompleteNonViableCandidate - Normally, overload resolution only
13249/// computes up to the first bad conversion. Produces the FixIt set if
13250/// possible.
13251static void
13253 ArrayRef<Expr *> Args,
13255 assert(!Cand->Viable);
13256
13257 // Don't do anything on failures other than bad conversion.
13259 return;
13260
13261 // We only want the FixIts if all the arguments can be corrected.
13262 bool Unfixable = false;
13263 // Use a implicit copy initialization to check conversion fixes.
13265
13266 // Attempt to fix the bad conversion.
13267 unsigned ConvCount = Cand->Conversions.size();
13268 for (unsigned ConvIdx =
13269 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13270 : 0);
13271 /**/; ++ConvIdx) {
13272 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13273 if (Cand->Conversions[ConvIdx].isInitialized() &&
13274 Cand->Conversions[ConvIdx].isBad()) {
13275 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13276 break;
13277 }
13278 }
13279
13280 // FIXME: this should probably be preserved from the overload
13281 // operation somehow.
13282 bool SuppressUserConversions = false;
13283
13284 unsigned ConvIdx = 0;
13285 unsigned ArgIdx = 0;
13286 ArrayRef<QualType> ParamTypes;
13287 bool Reversed = Cand->isReversed();
13288
13289 if (Cand->IsSurrogate) {
13290 QualType ConvType
13292 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13293 ConvType = ConvPtrType->getPointeeType();
13294 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13295 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13296 ConvIdx = 1;
13297 } else if (Cand->Function) {
13298 ParamTypes =
13299 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13300 if (isa<CXXMethodDecl>(Cand->Function) &&
13303 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13304 ConvIdx = 1;
13306 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13308 OO_Subscript)
13309 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13310 ArgIdx = 1;
13311 }
13312 } else {
13313 // Builtin operator.
13314 assert(ConvCount <= 3);
13315 ParamTypes = Cand->BuiltinParamTypes;
13316 }
13317
13318 // Fill in the rest of the conversions.
13319 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13320 ConvIdx != ConvCount && ArgIdx < Args.size();
13321 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13322 if (Cand->Conversions[ConvIdx].isInitialized()) {
13323 // We've already checked this conversion.
13324 } else if (ParamIdx < ParamTypes.size()) {
13325 if (ParamTypes[ParamIdx]->isDependentType())
13326 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13327 Args[ArgIdx]->getType());
13328 else {
13329 Cand->Conversions[ConvIdx] =
13330 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13331 SuppressUserConversions,
13332 /*InOverloadResolution=*/true,
13333 /*AllowObjCWritebackConversion=*/
13334 S.getLangOpts().ObjCAutoRefCount);
13335 // Store the FixIt in the candidate if it exists.
13336 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13337 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13338 }
13339 } else
13340 Cand->Conversions[ConvIdx].setEllipsis();
13341 }
13342}
13343
13346 SourceLocation OpLoc,
13347 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13348
13350
13351 // Sort the candidates by viability and position. Sorting directly would
13352 // be prohibitive, so we make a set of pointers and sort those.
13354 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13355 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13356 Cand != LastCand; ++Cand) {
13357 if (!Filter(*Cand))
13358 continue;
13359 switch (OCD) {
13360 case OCD_AllCandidates:
13361 if (!Cand->Viable) {
13362 if (!Cand->Function && !Cand->IsSurrogate) {
13363 // This a non-viable builtin candidate. We do not, in general,
13364 // want to list every possible builtin candidate.
13365 continue;
13366 }
13367 CompleteNonViableCandidate(S, Cand, Args, Kind);
13368 }
13369 break;
13370
13372 if (!Cand->Viable)
13373 continue;
13374 break;
13375
13377 if (!Cand->Best)
13378 continue;
13379 break;
13380 }
13381
13382 Cands.push_back(Cand);
13383 }
13384
13385 llvm::stable_sort(
13386 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13387
13388 return Cands;
13389}
13390
13392 SourceLocation OpLoc) {
13393 bool DeferHint = false;
13394 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13395 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13396 // host device candidates.
13397 auto WrongSidedCands =
13398 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13399 return (Cand.Viable == false &&
13401 (Cand.Function &&
13402 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13403 Cand.Function->template hasAttr<CUDADeviceAttr>());
13404 });
13405 DeferHint = !WrongSidedCands.empty();
13406 }
13407 return DeferHint;
13408}
13409
13410/// When overload resolution fails, prints diagnostic messages containing the
13411/// candidates in the candidate set.
13414 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13415 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13416
13417 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13418
13419 {
13420 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13421 S.Diag(PD.first, PD.second);
13422 }
13423
13424 // In WebAssembly we don't want to emit further diagnostics if a table is
13425 // passed as an argument to a function.
13426 bool NoteCands = true;
13427 for (const Expr *Arg : Args) {
13428 if (Arg->getType()->isWebAssemblyTableType())
13429 NoteCands = false;
13430 }
13431
13432 if (NoteCands)
13433 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13434
13435 if (OCD == OCD_AmbiguousCandidates)
13437 {Candidates.begin(), Candidates.end()});
13438}
13439
13442 StringRef Opc, SourceLocation OpLoc) {
13443 bool ReportedAmbiguousConversions = false;
13444
13445 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13446 unsigned CandsShown = 0;
13447 auto I = Cands.begin(), E = Cands.end();
13448 for (; I != E; ++I) {
13449 OverloadCandidate *Cand = *I;
13450
13451 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13452 ShowOverloads == Ovl_Best) {
13453 break;
13454 }
13455 ++CandsShown;
13456
13457 if (Cand->Function)
13458 NoteFunctionCandidate(S, Cand, Args.size(),
13459 Kind == CSK_AddressOfOverloadSet, DestAS);
13460 else if (Cand->IsSurrogate)
13461 NoteSurrogateCandidate(S, Cand);
13462 else {
13463 assert(Cand->Viable &&
13464 "Non-viable built-in candidates are not added to Cands.");
13465 // Generally we only see ambiguities including viable builtin
13466 // operators if overload resolution got screwed up by an
13467 // ambiguous user-defined conversion.
13468 //
13469 // FIXME: It's quite possible for different conversions to see
13470 // different ambiguities, though.
13471 if (!ReportedAmbiguousConversions) {
13472 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13473 ReportedAmbiguousConversions = true;
13474 }
13475
13476 // If this is a viable builtin, print it.
13477 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13478 }
13479 }
13480
13481 // Inform S.Diags that we've shown an overload set with N elements. This may
13482 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13483 S.Diags.overloadCandidatesShown(CandsShown);
13484
13485 if (I != E) {
13486 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13487 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13488 }
13489}
13490
13491static SourceLocation
13493 return Cand->Specialization ? Cand->Specialization->getLocation()
13494 : SourceLocation();
13495}
13496
13497namespace {
13498struct CompareTemplateSpecCandidatesForDisplay {
13499 Sema &S;
13500 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13501
13502 bool operator()(const TemplateSpecCandidate *L,
13503 const TemplateSpecCandidate *R) {
13504 // Fast-path this check.
13505 if (L == R)
13506 return false;
13507
13508 // Assuming that both candidates are not matches...
13509
13510 // Sort by the ranking of deduction failures.
13514
13515 // Sort everything else by location.
13516 SourceLocation LLoc = GetLocationForCandidate(L);
13517 SourceLocation RLoc = GetLocationForCandidate(R);
13518
13519 // Put candidates without locations (e.g. builtins) at the end.
13520 if (LLoc.isInvalid())
13521 return false;
13522 if (RLoc.isInvalid())
13523 return true;
13524
13525 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13526 }
13527};
13528}
13529
13530/// Diagnose a template argument deduction failure.
13531/// We are treating these failures as overload failures due to bad
13532/// deductions.
13534 bool ForTakingAddress) {
13536 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13537}
13538
13539void TemplateSpecCandidateSet::destroyCandidates() {
13540 for (iterator i = begin(), e = end(); i != e; ++i) {
13541 i->DeductionFailure.Destroy();
13542 }
13543}
13544
13546 destroyCandidates();
13547 Candidates.clear();
13548}
13549
13550/// NoteCandidates - When no template specialization match is found, prints
13551/// diagnostic messages containing the non-matching specializations that form
13552/// the candidate set.
13553/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13554/// OCD == OCD_AllCandidates and Cand->Viable == false.
13556 // Sort the candidates by position (assuming no candidate is a match).
13557 // Sorting directly would be prohibitive, so we make a set of pointers
13558 // and sort those.
13560 Cands.reserve(size());
13561 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13562 if (Cand->Specialization)
13563 Cands.push_back(Cand);
13564 // Otherwise, this is a non-matching builtin candidate. We do not,
13565 // in general, want to list every possible builtin candidate.
13566 }
13567
13568 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13569
13570 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13571 // for generalization purposes (?).
13572 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13573
13575 unsigned CandsShown = 0;
13576 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13577 TemplateSpecCandidate *Cand = *I;
13578
13579 // Set an arbitrary limit on the number of candidates we'll spam
13580 // the user with. FIXME: This limit should depend on details of the
13581 // candidate list.
13582 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13583 break;
13584 ++CandsShown;
13585
13586 assert(Cand->Specialization &&
13587 "Non-matching built-in candidates are not added to Cands.");
13588 Cand->NoteDeductionFailure(S, ForTakingAddress);
13589 }
13590
13591 if (I != E)
13592 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13593}
13594
13595// [PossiblyAFunctionType] --> [Return]
13596// NonFunctionType --> NonFunctionType
13597// R (A) --> R(A)
13598// R (*)(A) --> R (A)
13599// R (&)(A) --> R (A)
13600// R (S::*)(A) --> R (A)
13602 QualType Ret = PossiblyAFunctionType;
13603 if (const PointerType *ToTypePtr =
13604 PossiblyAFunctionType->getAs<PointerType>())
13605 Ret = ToTypePtr->getPointeeType();
13606 else if (const ReferenceType *ToTypeRef =
13607 PossiblyAFunctionType->getAs<ReferenceType>())
13608 Ret = ToTypeRef->getPointeeType();
13609 else if (const MemberPointerType *MemTypePtr =
13610 PossiblyAFunctionType->getAs<MemberPointerType>())
13611 Ret = MemTypePtr->getPointeeType();
13612 Ret =
13613 Context.getCanonicalType(Ret).getUnqualifiedType();
13614 return Ret;
13615}
13616
13618 bool Complain = true) {
13619 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13620 S.DeduceReturnType(FD, Loc, Complain))
13621 return true;
13622
13623 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13624 if (S.getLangOpts().CPlusPlus17 &&
13625 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13626 !S.ResolveExceptionSpec(Loc, FPT))
13627 return true;
13628
13629 return false;
13630}
13631
13632namespace {
13633// A helper class to help with address of function resolution
13634// - allows us to avoid passing around all those ugly parameters
13635class AddressOfFunctionResolver {
13636 Sema& S;
13637 Expr* SourceExpr;
13638 const QualType& TargetType;
13639 QualType TargetFunctionType; // Extracted function type from target type
13640
13641 bool Complain;
13642 //DeclAccessPair& ResultFunctionAccessPair;
13643 ASTContext& Context;
13644
13645 bool TargetTypeIsNonStaticMemberFunction;
13646 bool FoundNonTemplateFunction;
13647 bool StaticMemberFunctionFromBoundPointer;
13648 bool HasComplained;
13649
13650 OverloadExpr::FindResult OvlExprInfo;
13651 OverloadExpr *OvlExpr;
13652 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13653 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13654 TemplateSpecCandidateSet FailedCandidates;
13655
13656public:
13657 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13658 const QualType &TargetType, bool Complain)
13659 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13660 Complain(Complain), Context(S.getASTContext()),
13661 TargetTypeIsNonStaticMemberFunction(
13662 !!TargetType->getAs<MemberPointerType>()),
13663 FoundNonTemplateFunction(false),
13664 StaticMemberFunctionFromBoundPointer(false),
13665 HasComplained(false),
13666 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13667 OvlExpr(OvlExprInfo.Expression),
13668 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13669 ExtractUnqualifiedFunctionTypeFromTargetType();
13670
13671 if (TargetFunctionType->isFunctionType()) {
13672 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13673 if (!UME->isImplicitAccess() &&
13675 StaticMemberFunctionFromBoundPointer = true;
13676 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13677 DeclAccessPair dap;
13678 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13679 OvlExpr, false, &dap)) {
13680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13681 if (!Method->isStatic()) {
13682 // If the target type is a non-function type and the function found
13683 // is a non-static member function, pretend as if that was the
13684 // target, it's the only possible type to end up with.
13685 TargetTypeIsNonStaticMemberFunction = true;
13686
13687 // And skip adding the function if its not in the proper form.
13688 // We'll diagnose this due to an empty set of functions.
13689 if (!OvlExprInfo.HasFormOfMemberPointer)
13690 return;
13691 }
13692
13693 Matches.push_back(std::make_pair(dap, Fn));
13694 }
13695 return;
13696 }
13697
13698 if (OvlExpr->hasExplicitTemplateArgs())
13699 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13700
13701 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13702 // C++ [over.over]p4:
13703 // If more than one function is selected, [...]
13704 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13705 if (FoundNonTemplateFunction) {
13706 EliminateAllTemplateMatches();
13707 EliminateLessPartialOrderingConstrainedMatches();
13708 } else
13709 EliminateAllExceptMostSpecializedTemplate();
13710 }
13711 }
13712
13713 if (S.getLangOpts().CUDA && Matches.size() > 1)
13714 EliminateSuboptimalCudaMatches();
13715 }
13716
13717 bool hasComplained() const { return HasComplained; }
13718
13719private:
13720 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13721 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13722 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13723 }
13724
13725 /// \return true if A is considered a better overload candidate for the
13726 /// desired type than B.
13727 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13728 // If A doesn't have exactly the correct type, we don't want to classify it
13729 // as "better" than anything else. This way, the user is required to
13730 // disambiguate for us if there are multiple candidates and no exact match.
13731 return candidateHasExactlyCorrectType(A) &&
13732 (!candidateHasExactlyCorrectType(B) ||
13733 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13734 }
13735
13736 /// \return true if we were able to eliminate all but one overload candidate,
13737 /// false otherwise.
13738 bool eliminiateSuboptimalOverloadCandidates() {
13739 // Same algorithm as overload resolution -- one pass to pick the "best",
13740 // another pass to be sure that nothing is better than the best.
13741 auto Best = Matches.begin();
13742 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13743 if (isBetterCandidate(I->second, Best->second))
13744 Best = I;
13745
13746 const FunctionDecl *BestFn = Best->second;
13747 auto IsBestOrInferiorToBest = [this, BestFn](
13748 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13749 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13750 };
13751
13752 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13753 // option, so we can potentially give the user a better error
13754 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13755 return false;
13756 Matches[0] = *Best;
13757 Matches.resize(1);
13758 return true;
13759 }
13760
13761 bool isTargetTypeAFunction() const {
13762 return TargetFunctionType->isFunctionType();
13763 }
13764
13765 // [ToType] [Return]
13766
13767 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13768 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13769 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13770 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13771 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13772 }
13773
13774 // return true if any matching specializations were found
13775 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13776 const DeclAccessPair& CurAccessFunPair) {
13777 if (CXXMethodDecl *Method
13778 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13779 // Skip non-static function templates when converting to pointer, and
13780 // static when converting to member pointer.
13781 bool CanConvertToFunctionPointer =
13782 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13783 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13784 return false;
13785 }
13786 else if (TargetTypeIsNonStaticMemberFunction)
13787 return false;
13788
13789 // C++ [over.over]p2:
13790 // If the name is a function template, template argument deduction is
13791 // done (14.8.2.2), and if the argument deduction succeeds, the
13792 // resulting template argument list is used to generate a single
13793 // function template specialization, which is added to the set of
13794 // overloaded functions considered.
13795 FunctionDecl *Specialization = nullptr;
13796 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13798 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13799 Specialization, Info, /*IsAddressOfFunction*/ true);
13800 Result != TemplateDeductionResult::Success) {
13801 // Make a note of the failed deduction for diagnostics.
13802 FailedCandidates.addCandidate()
13803 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13804 MakeDeductionFailureInfo(Context, Result, Info));
13805 return false;
13806 }
13807
13808 // Template argument deduction ensures that we have an exact match or
13809 // compatible pointer-to-function arguments that would be adjusted by ICS.
13810 // This function template specicalization works.
13812 Context.getCanonicalType(Specialization->getType()),
13813 Context.getCanonicalType(TargetFunctionType)));
13814
13816 return false;
13817
13818 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13819 return true;
13820 }
13821
13822 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13823 const DeclAccessPair& CurAccessFunPair) {
13824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13825 // Skip non-static functions when converting to pointer, and static
13826 // when converting to member pointer.
13827 bool CanConvertToFunctionPointer =
13828 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13829 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13830 return false;
13831 }
13832 else if (TargetTypeIsNonStaticMemberFunction)
13833 return false;
13834
13835 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13836 if (S.getLangOpts().CUDA) {
13837 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13838 if (!(Caller && Caller->isImplicit()) &&
13839 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13840 return false;
13841 }
13842 if (FunDecl->isMultiVersion()) {
13843 const auto *TA = FunDecl->getAttr<TargetAttr>();
13844 if (TA && !TA->isDefaultVersion())
13845 return false;
13846 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13847 if (TVA && !TVA->isDefaultVersion())
13848 return false;
13849 }
13850
13851 // If any candidate has a placeholder return type, trigger its deduction
13852 // now.
13853 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13854 Complain)) {
13855 HasComplained |= Complain;
13856 return false;
13857 }
13858
13859 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13860 return false;
13861
13862 // If we're in C, we need to support types that aren't exactly identical.
13863 if (!S.getLangOpts().CPlusPlus ||
13864 candidateHasExactlyCorrectType(FunDecl)) {
13865 Matches.push_back(std::make_pair(
13866 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13867 FoundNonTemplateFunction = true;
13868 return true;
13869 }
13870 }
13871
13872 return false;
13873 }
13874
13875 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13876 bool Ret = false;
13877
13878 // If the overload expression doesn't have the form of a pointer to
13879 // member, don't try to convert it to a pointer-to-member type.
13880 if (IsInvalidFormOfPointerToMemberFunction())
13881 return false;
13882
13883 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13884 E = OvlExpr->decls_end();
13885 I != E; ++I) {
13886 // Look through any using declarations to find the underlying function.
13887 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13888
13889 // C++ [over.over]p3:
13890 // Non-member functions and static member functions match
13891 // targets of type "pointer-to-function" or "reference-to-function."
13892 // Nonstatic member functions match targets of
13893 // type "pointer-to-member-function."
13894 // Note that according to DR 247, the containing class does not matter.
13895 if (FunctionTemplateDecl *FunctionTemplate
13896 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13897 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13898 Ret = true;
13899 }
13900 // If we have explicit template arguments supplied, skip non-templates.
13901 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13902 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13903 Ret = true;
13904 }
13905 assert(Ret || Matches.empty());
13906 return Ret;
13907 }
13908
13909 void EliminateAllExceptMostSpecializedTemplate() {
13910 // [...] and any given function template specialization F1 is
13911 // eliminated if the set contains a second function template
13912 // specialization whose function template is more specialized
13913 // than the function template of F1 according to the partial
13914 // ordering rules of 14.5.5.2.
13915
13916 // The algorithm specified above is quadratic. We instead use a
13917 // two-pass algorithm (similar to the one used to identify the
13918 // best viable function in an overload set) that identifies the
13919 // best function template (if it exists).
13920
13921 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13922 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13923 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13924
13925 // TODO: It looks like FailedCandidates does not serve much purpose
13926 // here, since the no_viable diagnostic has index 0.
13927 UnresolvedSetIterator Result = S.getMostSpecialized(
13928 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13929 SourceExpr->getBeginLoc(), S.PDiag(),
13930 S.PDiag(diag::err_addr_ovl_ambiguous)
13931 << Matches[0].second->getDeclName(),
13932 S.PDiag(diag::note_ovl_candidate)
13933 << (unsigned)oc_function << (unsigned)ocs_described_template,
13934 Complain, TargetFunctionType);
13935
13936 if (Result != MatchesCopy.end()) {
13937 // Make it the first and only element
13938 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13939 Matches[0].second = cast<FunctionDecl>(*Result);
13940 Matches.resize(1);
13941 } else
13942 HasComplained |= Complain;
13943 }
13944
13945 void EliminateAllTemplateMatches() {
13946 // [...] any function template specializations in the set are
13947 // eliminated if the set also contains a non-template function, [...]
13948 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13949 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13950 ++I;
13951 else {
13952 Matches[I] = Matches[--N];
13953 Matches.resize(N);
13954 }
13955 }
13956 }
13957
13958 void EliminateLessPartialOrderingConstrainedMatches() {
13959 // C++ [over.over]p5:
13960 // [...] Any given non-template function F0 is eliminated if the set
13961 // contains a second non-template function that is more
13962 // partial-ordering-constrained than F0. [...]
13963 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13964 "Call EliminateAllTemplateMatches() first");
13965 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13966 Results.push_back(Matches[0]);
13967 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13968 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13969 FunctionDecl *F = getMorePartialOrderingConstrained(
13970 S, Matches[I].second, Results[0].second,
13971 /*IsFn1Reversed=*/false,
13972 /*IsFn2Reversed=*/false);
13973 if (!F) {
13974 Results.push_back(Matches[I]);
13975 continue;
13976 }
13977 if (F == Matches[I].second) {
13978 Results.clear();
13979 Results.push_back(Matches[I]);
13980 }
13981 }
13982 std::swap(Matches, Results);
13983 }
13984
13985 void EliminateSuboptimalCudaMatches() {
13986 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13987 Matches);
13988 }
13989
13990public:
13991 void ComplainNoMatchesFound() const {
13992 assert(Matches.empty());
13993 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13994 << OvlExpr->getName() << TargetFunctionType
13995 << OvlExpr->getSourceRange();
13996 if (FailedCandidates.empty())
13997 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13998 /*TakingAddress=*/true);
13999 else {
14000 // We have some deduction failure messages. Use them to diagnose
14001 // the function templates, and diagnose the non-template candidates
14002 // normally.
14003 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14004 IEnd = OvlExpr->decls_end();
14005 I != IEnd; ++I)
14006 if (FunctionDecl *Fun =
14007 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14009 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14010 /*TakingAddress=*/true);
14011 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14012 }
14013 }
14014
14015 bool IsInvalidFormOfPointerToMemberFunction() const {
14016 return TargetTypeIsNonStaticMemberFunction &&
14017 !OvlExprInfo.HasFormOfMemberPointer;
14018 }
14019
14020 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14021 // TODO: Should we condition this on whether any functions might
14022 // have matched, or is it more appropriate to do that in callers?
14023 // TODO: a fixit wouldn't hurt.
14024 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14025 << TargetType << OvlExpr->getSourceRange();
14026 }
14027
14028 bool IsStaticMemberFunctionFromBoundPointer() const {
14029 return StaticMemberFunctionFromBoundPointer;
14030 }
14031
14032 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14033 S.Diag(OvlExpr->getBeginLoc(),
14034 diag::err_invalid_form_pointer_member_function)
14035 << OvlExpr->getSourceRange();
14036 }
14037
14038 void ComplainOfInvalidConversion() const {
14039 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14040 << OvlExpr->getName() << TargetType;
14041 }
14042
14043 void ComplainMultipleMatchesFound() const {
14044 assert(Matches.size() > 1);
14045 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14046 << OvlExpr->getName() << OvlExpr->getSourceRange();
14047 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14048 /*TakingAddress=*/true);
14049 }
14050
14051 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14052
14053 int getNumMatches() const { return Matches.size(); }
14054
14055 FunctionDecl* getMatchingFunctionDecl() const {
14056 if (Matches.size() != 1) return nullptr;
14057 return Matches[0].second;
14058 }
14059
14060 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14061 if (Matches.size() != 1) return nullptr;
14062 return &Matches[0].first;
14063 }
14064};
14065}
14066
14067FunctionDecl *
14069 QualType TargetType,
14070 bool Complain,
14071 DeclAccessPair &FoundResult,
14072 bool *pHadMultipleCandidates) {
14073 assert(AddressOfExpr->getType() == Context.OverloadTy);
14074
14075 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14076 Complain);
14077 int NumMatches = Resolver.getNumMatches();
14078 FunctionDecl *Fn = nullptr;
14079 bool ShouldComplain = Complain && !Resolver.hasComplained();
14080 if (NumMatches == 0 && ShouldComplain) {
14081 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14082 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14083 else
14084 Resolver.ComplainNoMatchesFound();
14085 }
14086 else if (NumMatches > 1 && ShouldComplain)
14087 Resolver.ComplainMultipleMatchesFound();
14088 else if (NumMatches == 1) {
14089 Fn = Resolver.getMatchingFunctionDecl();
14090 assert(Fn);
14091 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14092 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14093 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14094 if (Complain) {
14095 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14096 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14097 else
14098 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14099 }
14100 }
14101
14102 if (pHadMultipleCandidates)
14103 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14104 return Fn;
14105}
14106
14110 OverloadExpr *Ovl = R.Expression;
14111 bool IsResultAmbiguous = false;
14112 FunctionDecl *Result = nullptr;
14113 DeclAccessPair DAP;
14114 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14115
14116 // Return positive for better, negative for worse, 0 for equal preference.
14117 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14118 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14119 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14120 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14121 };
14122
14123 // Don't use the AddressOfResolver because we're specifically looking for
14124 // cases where we have one overload candidate that lacks
14125 // enable_if/pass_object_size/...
14126 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14127 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14128 if (!FD)
14129 return nullptr;
14130
14132 continue;
14133
14134 // If we found a better result, update Result.
14135 auto FoundBetter = [&]() {
14136 IsResultAmbiguous = false;
14137 DAP = I.getPair();
14138 Result = FD;
14139 };
14140
14141 // We have more than one result - see if it is more
14142 // partial-ordering-constrained than the previous one.
14143 if (Result) {
14144 // Check CUDA preference first. If the candidates have differennt CUDA
14145 // preference, choose the one with higher CUDA preference. Otherwise,
14146 // choose the one with more constraints.
14147 if (getLangOpts().CUDA) {
14148 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14149 // FD has different preference than Result.
14150 if (PreferenceByCUDA != 0) {
14151 // FD is more preferable than Result.
14152 if (PreferenceByCUDA > 0)
14153 FoundBetter();
14154 continue;
14155 }
14156 }
14157 // FD has the same CUDA preference than Result. Continue to check
14158 // constraints.
14159
14160 // C++ [over.over]p5:
14161 // [...] Any given non-template function F0 is eliminated if the set
14162 // contains a second non-template function that is more
14163 // partial-ordering-constrained than F0 [...]
14164 FunctionDecl *MoreConstrained =
14166 /*IsFn1Reversed=*/false,
14167 /*IsFn2Reversed=*/false);
14168 if (MoreConstrained != FD) {
14169 if (!MoreConstrained) {
14170 IsResultAmbiguous = true;
14171 AmbiguousDecls.push_back(FD);
14172 }
14173 continue;
14174 }
14175 // FD is more constrained - replace Result with it.
14176 }
14177 FoundBetter();
14178 }
14179
14180 if (IsResultAmbiguous)
14181 return nullptr;
14182
14183 if (Result) {
14184 // We skipped over some ambiguous declarations which might be ambiguous with
14185 // the selected result.
14186 for (FunctionDecl *Skipped : AmbiguousDecls) {
14187 // If skipped candidate has different CUDA preference than the result,
14188 // there is no ambiguity. Otherwise check whether they have different
14189 // constraints.
14190 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14191 continue;
14192 if (!getMoreConstrainedFunction(Skipped, Result))
14193 return nullptr;
14194 }
14195 Pair = DAP;
14196 }
14197 return Result;
14198}
14199
14201 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14202 Expr *E = SrcExpr.get();
14203 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14204
14205 DeclAccessPair DAP;
14207 if (!Found || Found->isCPUDispatchMultiVersion() ||
14208 Found->isCPUSpecificMultiVersion())
14209 return false;
14210
14211 // Emitting multiple diagnostics for a function that is both inaccessible and
14212 // unavailable is consistent with our behavior elsewhere. So, always check
14213 // for both.
14217 if (Res.isInvalid())
14218 return false;
14219 Expr *Fixed = Res.get();
14220 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14221 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14222 else
14223 SrcExpr = Fixed;
14224 return true;
14225}
14226
14228 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14229 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14230 // C++ [over.over]p1:
14231 // [...] [Note: any redundant set of parentheses surrounding the
14232 // overloaded function name is ignored (5.1). ]
14233 // C++ [over.over]p1:
14234 // [...] The overloaded function name can be preceded by the &
14235 // operator.
14236
14237 // If we didn't actually find any template-ids, we're done.
14238 if (!ovl->hasExplicitTemplateArgs())
14239 return nullptr;
14240
14241 TemplateArgumentListInfo ExplicitTemplateArgs;
14242 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14243
14244 // Look through all of the overloaded functions, searching for one
14245 // whose type matches exactly.
14246 FunctionDecl *Matched = nullptr;
14247 for (UnresolvedSetIterator I = ovl->decls_begin(),
14248 E = ovl->decls_end(); I != E; ++I) {
14249 // C++0x [temp.arg.explicit]p3:
14250 // [...] In contexts where deduction is done and fails, or in contexts
14251 // where deduction is not done, if a template argument list is
14252 // specified and it, along with any default template arguments,
14253 // identifies a single function template specialization, then the
14254 // template-id is an lvalue for the function template specialization.
14256 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14257 if (!FunctionTemplate)
14258 continue;
14259
14260 // C++ [over.over]p2:
14261 // If the name is a function template, template argument deduction is
14262 // done (14.8.2.2), and if the argument deduction succeeds, the
14263 // resulting template argument list is used to generate a single
14264 // function template specialization, which is added to the set of
14265 // overloaded functions considered.
14266 FunctionDecl *Specialization = nullptr;
14267 TemplateDeductionInfo Info(ovl->getNameLoc());
14269 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14270 /*IsAddressOfFunction*/ true);
14272 // Make a note of the failed deduction for diagnostics.
14273 if (FailedTSC)
14274 FailedTSC->addCandidate().set(
14275 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14277 continue;
14278 }
14279
14280 assert(Specialization && "no specialization and no error?");
14281
14282 // C++ [temp.deduct.call]p6:
14283 // [...] If all successful deductions yield the same deduced A, that
14284 // deduced A is the result of deduction; otherwise, the parameter is
14285 // treated as a non-deduced context.
14286 if (Matched) {
14287 if (ForTypeDeduction &&
14289 Specialization->getType()))
14290 continue;
14291 // Multiple matches; we can't resolve to a single declaration.
14292 if (Complain) {
14293 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14294 << ovl->getName();
14296 }
14297 return nullptr;
14298 }
14299
14300 Matched = Specialization;
14301 if (FoundResult) *FoundResult = I.getPair();
14302 }
14303
14304 if (Matched &&
14305 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14306 return nullptr;
14307
14308 return Matched;
14309}
14310
14312 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14313 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14314 unsigned DiagIDForComplaining) {
14315 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14316
14318
14319 DeclAccessPair found;
14320 ExprResult SingleFunctionExpression;
14322 ovl.Expression, /*complain*/ false, &found)) {
14323 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14324 SrcExpr = ExprError();
14325 return true;
14326 }
14327
14328 // It is only correct to resolve to an instance method if we're
14329 // resolving a form that's permitted to be a pointer to member.
14330 // Otherwise we'll end up making a bound member expression, which
14331 // is illegal in all the contexts we resolve like this.
14332 if (!ovl.HasFormOfMemberPointer &&
14333 isa<CXXMethodDecl>(fn) &&
14334 cast<CXXMethodDecl>(fn)->isInstance()) {
14335 if (!complain) return false;
14336
14337 Diag(ovl.Expression->getExprLoc(),
14338 diag::err_bound_member_function)
14339 << 0 << ovl.Expression->getSourceRange();
14340
14341 // TODO: I believe we only end up here if there's a mix of
14342 // static and non-static candidates (otherwise the expression
14343 // would have 'bound member' type, not 'overload' type).
14344 // Ideally we would note which candidate was chosen and why
14345 // the static candidates were rejected.
14346 SrcExpr = ExprError();
14347 return true;
14348 }
14349
14350 // Fix the expression to refer to 'fn'.
14351 SingleFunctionExpression =
14352 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14353
14354 // If desired, do function-to-pointer decay.
14355 if (doFunctionPointerConversion) {
14356 SingleFunctionExpression =
14357 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14358 if (SingleFunctionExpression.isInvalid()) {
14359 SrcExpr = ExprError();
14360 return true;
14361 }
14362 }
14363 }
14364
14365 if (!SingleFunctionExpression.isUsable()) {
14366 if (complain) {
14367 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14368 << ovl.Expression->getName()
14369 << DestTypeForComplaining
14370 << OpRangeForComplaining
14372 NoteAllOverloadCandidates(SrcExpr.get());
14373
14374 SrcExpr = ExprError();
14375 return true;
14376 }
14377
14378 return false;
14379 }
14380
14381 SrcExpr = SingleFunctionExpression;
14382 return true;
14383}
14384
14385/// Add a single candidate to the overload set.
14387 DeclAccessPair FoundDecl,
14388 TemplateArgumentListInfo *ExplicitTemplateArgs,
14389 ArrayRef<Expr *> Args,
14390 OverloadCandidateSet &CandidateSet,
14391 bool PartialOverloading,
14392 bool KnownValid) {
14393 NamedDecl *Callee = FoundDecl.getDecl();
14394 if (isa<UsingShadowDecl>(Callee))
14395 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14396
14397 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14398 if (ExplicitTemplateArgs) {
14399 assert(!KnownValid && "Explicit template arguments?");
14400 return;
14401 }
14402 // Prevent ill-formed function decls to be added as overload candidates.
14403 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14404 return;
14405
14406 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14407 /*SuppressUserConversions=*/false,
14408 PartialOverloading);
14409 return;
14410 }
14411
14412 if (FunctionTemplateDecl *FuncTemplate
14413 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14414 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14415 ExplicitTemplateArgs, Args, CandidateSet,
14416 /*SuppressUserConversions=*/false,
14417 PartialOverloading);
14418 return;
14419 }
14420
14421 assert(!KnownValid && "unhandled case in overloaded call candidate");
14422}
14423
14425 ArrayRef<Expr *> Args,
14426 OverloadCandidateSet &CandidateSet,
14427 bool PartialOverloading) {
14428
14429#ifndef NDEBUG
14430 // Verify that ArgumentDependentLookup is consistent with the rules
14431 // in C++0x [basic.lookup.argdep]p3:
14432 //
14433 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14434 // and let Y be the lookup set produced by argument dependent
14435 // lookup (defined as follows). If X contains
14436 //
14437 // -- a declaration of a class member, or
14438 //
14439 // -- a block-scope function declaration that is not a
14440 // using-declaration, or
14441 //
14442 // -- a declaration that is neither a function or a function
14443 // template
14444 //
14445 // then Y is empty.
14446
14447 if (ULE->requiresADL()) {
14449 E = ULE->decls_end(); I != E; ++I) {
14450 assert(!(*I)->getDeclContext()->isRecord());
14451 assert(isa<UsingShadowDecl>(*I) ||
14452 !(*I)->getDeclContext()->isFunctionOrMethod());
14453 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14454 }
14455 }
14456#endif
14457
14458 // It would be nice to avoid this copy.
14459 TemplateArgumentListInfo TABuffer;
14460 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14461 if (ULE->hasExplicitTemplateArgs()) {
14462 ULE->copyTemplateArgumentsInto(TABuffer);
14463 ExplicitTemplateArgs = &TABuffer;
14464 }
14465
14467 E = ULE->decls_end(); I != E; ++I)
14468 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14469 CandidateSet, PartialOverloading,
14470 /*KnownValid*/ true);
14471
14472 if (ULE->requiresADL())
14474 Args, ExplicitTemplateArgs,
14475 CandidateSet, PartialOverloading);
14476}
14477
14479 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14480 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14481 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14482 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14483 CandidateSet, false, /*KnownValid*/ false);
14484}
14485
14486/// Determine whether a declaration with the specified name could be moved into
14487/// a different namespace.
14489 switch (Name.getCXXOverloadedOperator()) {
14490 case OO_New: case OO_Array_New:
14491 case OO_Delete: case OO_Array_Delete:
14492 return false;
14493
14494 default:
14495 return true;
14496 }
14497}
14498
14499/// Attempt to recover from an ill-formed use of a non-dependent name in a
14500/// template, where the non-dependent name was declared after the template
14501/// was defined. This is common in code written for a compilers which do not
14502/// correctly implement two-stage name lookup.
14503///
14504/// Returns true if a viable candidate was found and a diagnostic was issued.
14506 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14508 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14509 CXXRecordDecl **FoundInClass = nullptr) {
14510 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14511 return false;
14512
14513 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14514 if (DC->isTransparentContext())
14515 continue;
14516
14517 SemaRef.LookupQualifiedName(R, DC);
14518
14519 if (!R.empty()) {
14521
14522 OverloadCandidateSet Candidates(FnLoc, CSK);
14523 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14524 Candidates);
14525
14528 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14529
14530 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14531 // We either found non-function declarations or a best viable function
14532 // at class scope. A class-scope lookup result disables ADL. Don't
14533 // look past this, but let the caller know that we found something that
14534 // either is, or might be, usable in this class.
14535 if (FoundInClass) {
14536 *FoundInClass = RD;
14537 if (OR == OR_Success) {
14538 R.clear();
14539 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14540 R.resolveKind();
14541 }
14542 }
14543 return false;
14544 }
14545
14546 if (OR != OR_Success) {
14547 // There wasn't a unique best function or function template.
14548 return false;
14549 }
14550
14551 // Find the namespaces where ADL would have looked, and suggest
14552 // declaring the function there instead.
14553 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14554 Sema::AssociatedClassSet AssociatedClasses;
14555 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14556 AssociatedNamespaces,
14557 AssociatedClasses);
14558 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14560 DeclContext *Std = SemaRef.getStdNamespace();
14561 for (Sema::AssociatedNamespaceSet::iterator
14562 it = AssociatedNamespaces.begin(),
14563 end = AssociatedNamespaces.end(); it != end; ++it) {
14564 // Never suggest declaring a function within namespace 'std'.
14565 if (Std && Std->Encloses(*it))
14566 continue;
14567
14568 // Never suggest declaring a function within a namespace with a
14569 // reserved name, like __gnu_cxx.
14570 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14571 if (NS &&
14572 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14573 continue;
14574
14575 SuggestedNamespaces.insert(*it);
14576 }
14577 }
14578
14579 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14580 << R.getLookupName();
14581 if (SuggestedNamespaces.empty()) {
14582 SemaRef.Diag(Best->Function->getLocation(),
14583 diag::note_not_found_by_two_phase_lookup)
14584 << R.getLookupName() << 0;
14585 } else if (SuggestedNamespaces.size() == 1) {
14586 SemaRef.Diag(Best->Function->getLocation(),
14587 diag::note_not_found_by_two_phase_lookup)
14588 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14589 } else {
14590 // FIXME: It would be useful to list the associated namespaces here,
14591 // but the diagnostics infrastructure doesn't provide a way to produce
14592 // a localized representation of a list of items.
14593 SemaRef.Diag(Best->Function->getLocation(),
14594 diag::note_not_found_by_two_phase_lookup)
14595 << R.getLookupName() << 2;
14596 }
14597
14598 // Try to recover by calling this function.
14599 return true;
14600 }
14601
14602 R.clear();
14603 }
14604
14605 return false;
14606}
14607
14608/// Attempt to recover from ill-formed use of a non-dependent operator in a
14609/// template, where the non-dependent operator was declared after the template
14610/// was defined.
14611///
14612/// Returns true if a viable candidate was found and a diagnostic was issued.
14613static bool
14615 SourceLocation OpLoc,
14616 ArrayRef<Expr *> Args) {
14617 DeclarationName OpName =
14619 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14620 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14622 /*ExplicitTemplateArgs=*/nullptr, Args);
14623}
14624
14625namespace {
14626class BuildRecoveryCallExprRAII {
14627 Sema &SemaRef;
14628 Sema::SatisfactionStackResetRAII SatStack;
14629
14630public:
14631 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14632 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14633 SemaRef.IsBuildingRecoveryCallExpr = true;
14634 }
14635
14636 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14637};
14638}
14639
14640/// Attempts to recover from a call where no functions were found.
14641///
14642/// This function will do one of three things:
14643/// * Diagnose, recover, and return a recovery expression.
14644/// * Diagnose, fail to recover, and return ExprError().
14645/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14646/// expected to diagnose as appropriate.
14647static ExprResult
14650 SourceLocation LParenLoc,
14652 SourceLocation RParenLoc,
14653 bool EmptyLookup, bool AllowTypoCorrection) {
14654 // Do not try to recover if it is already building a recovery call.
14655 // This stops infinite loops for template instantiations like
14656 //
14657 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14658 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14659 if (SemaRef.IsBuildingRecoveryCallExpr)
14660 return ExprResult();
14661 BuildRecoveryCallExprRAII RCE(SemaRef);
14662
14663 CXXScopeSpec SS;
14664 SS.Adopt(ULE->getQualifierLoc());
14665 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14666
14667 TemplateArgumentListInfo TABuffer;
14668 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14669 if (ULE->hasExplicitTemplateArgs()) {
14670 ULE->copyTemplateArgumentsInto(TABuffer);
14671 ExplicitTemplateArgs = &TABuffer;
14672 }
14673
14674 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14676 CXXRecordDecl *FoundInClass = nullptr;
14677 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14679 ExplicitTemplateArgs, Args, &FoundInClass)) {
14680 // OK, diagnosed a two-phase lookup issue.
14681 } else if (EmptyLookup) {
14682 // Try to recover from an empty lookup with typo correction.
14683 R.clear();
14684 NoTypoCorrectionCCC NoTypoValidator{};
14685 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14686 ExplicitTemplateArgs != nullptr,
14687 dyn_cast<MemberExpr>(Fn));
14688 CorrectionCandidateCallback &Validator =
14689 AllowTypoCorrection
14690 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14691 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14692 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14693 Args))
14694 return ExprError();
14695 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14696 // We found a usable declaration of the name in a dependent base of some
14697 // enclosing class.
14698 // FIXME: We should also explain why the candidates found by name lookup
14699 // were not viable.
14700 if (SemaRef.DiagnoseDependentMemberLookup(R))
14701 return ExprError();
14702 } else {
14703 // We had viable candidates and couldn't recover; let the caller diagnose
14704 // this.
14705 return ExprResult();
14706 }
14707
14708 // If we get here, we should have issued a diagnostic and formed a recovery
14709 // lookup result.
14710 assert(!R.empty() && "lookup results empty despite recovery");
14711
14712 // If recovery created an ambiguity, just bail out.
14713 if (R.isAmbiguous()) {
14715 return ExprError();
14716 }
14717
14718 // Build an implicit member call if appropriate. Just drop the
14719 // casts and such from the call, we don't really care.
14720 ExprResult NewFn = ExprError();
14721 if ((*R.begin())->isCXXClassMember())
14722 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14723 ExplicitTemplateArgs, S);
14724 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14725 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14726 ExplicitTemplateArgs);
14727 else
14728 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14729
14730 if (NewFn.isInvalid())
14731 return ExprError();
14732
14733 // This shouldn't cause an infinite loop because we're giving it
14734 // an expression with viable lookup results, which should never
14735 // end up here.
14736 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14737 MultiExprArg(Args.data(), Args.size()),
14738 RParenLoc);
14739}
14740
14743 MultiExprArg Args,
14744 SourceLocation RParenLoc,
14745 OverloadCandidateSet *CandidateSet,
14746 ExprResult *Result) {
14747#ifndef NDEBUG
14748 if (ULE->requiresADL()) {
14749 // To do ADL, we must have found an unqualified name.
14750 assert(!ULE->getQualifier() && "qualified name with ADL");
14751
14752 // We don't perform ADL for implicit declarations of builtins.
14753 // Verify that this was correctly set up.
14754 FunctionDecl *F;
14755 if (ULE->decls_begin() != ULE->decls_end() &&
14756 ULE->decls_begin() + 1 == ULE->decls_end() &&
14757 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14758 F->getBuiltinID() && F->isImplicit())
14759 llvm_unreachable("performing ADL for builtin");
14760
14761 // We don't perform ADL in C.
14762 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14763 }
14764#endif
14765
14766 UnbridgedCastsSet UnbridgedCasts;
14767 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14768 *Result = ExprError();
14769 return true;
14770 }
14771
14772 // Add the functions denoted by the callee to the set of candidate
14773 // functions, including those from argument-dependent lookup.
14774 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14775
14776 if (getLangOpts().MSVCCompat &&
14777 CurContext->isDependentContext() && !isSFINAEContext() &&
14779
14781 if (CandidateSet->empty() ||
14782 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14784 // In Microsoft mode, if we are inside a template class member function
14785 // then create a type dependent CallExpr. The goal is to postpone name
14786 // lookup to instantiation time to be able to search into type dependent
14787 // base classes.
14788 CallExpr *CE =
14789 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14790 RParenLoc, CurFPFeatureOverrides());
14792 *Result = CE;
14793 return true;
14794 }
14795 }
14796
14797 if (CandidateSet->empty())
14798 return false;
14799
14800 UnbridgedCasts.restore();
14801 return false;
14802}
14803
14804// Guess at what the return type for an unresolvable overload should be.
14807 std::optional<QualType> Result;
14808 // Adjust Type after seeing a candidate.
14809 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14810 if (!Candidate.Function)
14811 return;
14812 if (Candidate.Function->isInvalidDecl())
14813 return;
14814 QualType T = Candidate.Function->getReturnType();
14815 if (T.isNull())
14816 return;
14817 if (!Result)
14818 Result = T;
14819 else if (Result != T)
14820 Result = QualType();
14821 };
14822
14823 // Look for an unambiguous type from a progressively larger subset.
14824 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14825 //
14826 // First, consider only the best candidate.
14827 if (Best && *Best != CS.end())
14828 ConsiderCandidate(**Best);
14829 // Next, consider only viable candidates.
14830 if (!Result)
14831 for (const auto &C : CS)
14832 if (C.Viable)
14833 ConsiderCandidate(C);
14834 // Finally, consider all candidates.
14835 if (!Result)
14836 for (const auto &C : CS)
14837 ConsiderCandidate(C);
14838
14839 if (!Result)
14840 return QualType();
14841 auto Value = *Result;
14842 if (Value.isNull() || Value->isUndeducedType())
14843 return QualType();
14844 return Value;
14845}
14846
14847/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14848/// the completed call expression. If overload resolution fails, emits
14849/// diagnostics and returns ExprError()
14852 SourceLocation LParenLoc,
14853 MultiExprArg Args,
14854 SourceLocation RParenLoc,
14855 Expr *ExecConfig,
14856 OverloadCandidateSet *CandidateSet,
14858 OverloadingResult OverloadResult,
14859 bool AllowTypoCorrection) {
14860 switch (OverloadResult) {
14861 case OR_Success: {
14862 FunctionDecl *FDecl = (*Best)->Function;
14863 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14864 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14865 return ExprError();
14866 ExprResult Res =
14867 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14868 if (Res.isInvalid())
14869 return ExprError();
14870 return SemaRef.BuildResolvedCallExpr(
14871 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14872 /*IsExecConfig=*/false,
14873 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14874 }
14875
14876 case OR_No_Viable_Function: {
14877 if (*Best != CandidateSet->end() &&
14878 CandidateSet->getKind() ==
14880 if (CXXMethodDecl *M =
14881 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14883 CandidateSet->NoteCandidates(
14885 Fn->getBeginLoc(),
14886 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14887 SemaRef, OCD_AmbiguousCandidates, Args);
14888 return ExprError();
14889 }
14890 }
14891
14892 // Try to recover by looking for viable functions which the user might
14893 // have meant to call.
14894 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14895 Args, RParenLoc,
14896 CandidateSet->empty(),
14897 AllowTypoCorrection);
14898 if (Recovery.isInvalid() || Recovery.isUsable())
14899 return Recovery;
14900
14901 // If the user passes in a function that we can't take the address of, we
14902 // generally end up emitting really bad error messages. Here, we attempt to
14903 // emit better ones.
14904 for (const Expr *Arg : Args) {
14905 if (!Arg->getType()->isFunctionType())
14906 continue;
14907 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14908 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14909 if (FD &&
14910 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14911 Arg->getExprLoc()))
14912 return ExprError();
14913 }
14914 }
14915
14916 CandidateSet->NoteCandidates(
14918 Fn->getBeginLoc(),
14919 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14920 << ULE->getName() << Fn->getSourceRange()),
14921 SemaRef, OCD_AllCandidates, Args);
14922 break;
14923 }
14924
14925 case OR_Ambiguous:
14926 CandidateSet->NoteCandidates(
14927 PartialDiagnosticAt(Fn->getBeginLoc(),
14928 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14929 << ULE->getName() << Fn->getSourceRange()),
14930 SemaRef, OCD_AmbiguousCandidates, Args);
14931 break;
14932
14933 case OR_Deleted: {
14934 FunctionDecl *FDecl = (*Best)->Function;
14935 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14936 Fn->getSourceRange(), ULE->getName(),
14937 *CandidateSet, FDecl, Args);
14938
14939 // We emitted an error for the unavailable/deleted function call but keep
14940 // the call in the AST.
14941 ExprResult Res =
14942 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14943 if (Res.isInvalid())
14944 return ExprError();
14945 return SemaRef.BuildResolvedCallExpr(
14946 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14947 /*IsExecConfig=*/false,
14948 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14949 }
14950 }
14951
14952 // Overload resolution failed, try to recover.
14953 SmallVector<Expr *, 8> SubExprs = {Fn};
14954 SubExprs.append(Args.begin(), Args.end());
14955 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14956 chooseRecoveryType(*CandidateSet, Best));
14957}
14958
14961 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14962 if (I->Viable &&
14963 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14964 I->Viable = false;
14965 I->FailureKind = ovl_fail_addr_not_available;
14966 }
14967 }
14968}
14969
14972 SourceLocation LParenLoc,
14973 MultiExprArg Args,
14974 SourceLocation RParenLoc,
14975 Expr *ExecConfig,
14976 bool AllowTypoCorrection,
14977 bool CalleesAddressIsTaken) {
14978
14982
14983 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14984 ExprResult result;
14985
14986 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14987 &result))
14988 return result;
14989
14990 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14991 // functions that aren't addressible are considered unviable.
14992 if (CalleesAddressIsTaken)
14993 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14994
14996 OverloadingResult OverloadResult =
14997 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14998
14999 // [C++23][over.call.func]
15000 // if overload resolution selects a non-static member function,
15001 // the call is ill-formed;
15003 Best != CandidateSet.end()) {
15004 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15005 M && M->isImplicitObjectMemberFunction()) {
15006 OverloadResult = OR_No_Viable_Function;
15007 }
15008 }
15009
15010 // Model the case with a call to a templated function whose definition
15011 // encloses the call and whose return type contains a placeholder type as if
15012 // the UnresolvedLookupExpr was type-dependent.
15013 if (OverloadResult == OR_Success) {
15014 const FunctionDecl *FDecl = Best->Function;
15015 if (LangOpts.CUDA)
15016 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15017 if (FDecl && FDecl->isTemplateInstantiation() &&
15018 FDecl->getReturnType()->isUndeducedType()) {
15019
15020 // Creating dependent CallExpr is not okay if the enclosing context itself
15021 // is not dependent. This situation notably arises if a non-dependent
15022 // member function calls the later-defined overloaded static function.
15023 //
15024 // For example, in
15025 // class A {
15026 // void c() { callee(1); }
15027 // static auto callee(auto x) { }
15028 // };
15029 //
15030 // Here callee(1) is unresolved at the call site, but is not inside a
15031 // dependent context. There will be no further attempt to resolve this
15032 // call if it is made dependent.
15033
15034 if (const auto *TP =
15035 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15036 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15037 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15038 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15039 }
15040 }
15041 }
15042
15043 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15044 ExecConfig, &CandidateSet, &Best,
15045 OverloadResult, AllowTypoCorrection);
15046}
15047
15051 const UnresolvedSetImpl &Fns,
15052 bool PerformADL) {
15054 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15055 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15056}
15057
15060 bool HadMultipleCandidates) {
15061 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15062 // the FoundDecl as it impedes TransformMemberExpr.
15063 // We go a bit further here: if there's no difference in UnderlyingDecl,
15064 // then using FoundDecl vs Method shouldn't make a difference either.
15065 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15066 FoundDecl = Method;
15067 // Convert the expression to match the conversion function's implicit object
15068 // parameter.
15069 ExprResult Exp;
15070 if (Method->isExplicitObjectMemberFunction())
15072 else
15074 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15075 if (Exp.isInvalid())
15076 return true;
15077
15078 if (Method->getParent()->isLambda() &&
15079 Method->getConversionType()->isBlockPointerType()) {
15080 // This is a lambda conversion to block pointer; check if the argument
15081 // was a LambdaExpr.
15082 Expr *SubE = E;
15083 auto *CE = dyn_cast<CastExpr>(SubE);
15084 if (CE && CE->getCastKind() == CK_NoOp)
15085 SubE = CE->getSubExpr();
15086 SubE = SubE->IgnoreParens();
15087 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15088 SubE = BE->getSubExpr();
15089 if (isa<LambdaExpr>(SubE)) {
15090 // For the conversion to block pointer on a lambda expression, we
15091 // construct a special BlockLiteral instead; this doesn't really make
15092 // a difference in ARC, but outside of ARC the resulting block literal
15093 // follows the normal lifetime rules for block literals instead of being
15094 // autoreleased.
15098 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15100
15101 // FIXME: This note should be produced by a CodeSynthesisContext.
15102 if (BlockExp.isInvalid())
15103 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15104 return BlockExp;
15105 }
15106 }
15107 CallExpr *CE;
15108 QualType ResultType = Method->getReturnType();
15110 ResultType = ResultType.getNonLValueExprType(Context);
15111 if (Method->isExplicitObjectMemberFunction()) {
15112 ExprResult FnExpr =
15113 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15114 HadMultipleCandidates, E->getBeginLoc());
15115 if (FnExpr.isInvalid())
15116 return ExprError();
15117 Expr *ObjectParam = Exp.get();
15118 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15119 ResultType, VK, Exp.get()->getEndLoc(),
15121 CE->setUsesMemberSyntax(true);
15122 } else {
15123 MemberExpr *ME =
15124 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15126 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15127 HadMultipleCandidates, DeclarationNameInfo(),
15128 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15129
15130 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15131 Exp.get()->getEndLoc(),
15133 }
15134
15135 if (CheckFunctionCall(Method, CE,
15136 Method->getType()->castAs<FunctionProtoType>()))
15137 return ExprError();
15138
15140}
15141
15144 const UnresolvedSetImpl &Fns,
15145 Expr *Input, bool PerformADL) {
15147 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15148 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15149 // TODO: provide better source location info.
15150 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15151
15152 if (checkPlaceholderForOverload(*this, Input))
15153 return ExprError();
15154
15155 Expr *Args[2] = { Input, nullptr };
15156 unsigned NumArgs = 1;
15157
15158 // For post-increment and post-decrement, add the implicit '0' as
15159 // the second argument, so that we know this is a post-increment or
15160 // post-decrement.
15161 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15162 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15163 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15164 SourceLocation());
15165 NumArgs = 2;
15166 }
15167
15168 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15169
15170 if (Input->isTypeDependent()) {
15172 // [C++26][expr.unary.op][expr.pre.incr]
15173 // The * operator yields an lvalue of type
15174 // The pre/post increment operators yied an lvalue.
15175 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15176 VK = VK_LValue;
15177
15178 if (Fns.empty())
15179 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15180 OK_Ordinary, OpLoc, false,
15182
15183 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15185 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15186 if (Fn.isInvalid())
15187 return ExprError();
15188 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15189 Context.DependentTy, VK_PRValue, OpLoc,
15191 }
15192
15193 // Build an empty overload set.
15195
15196 // Add the candidates from the given function set.
15197 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15198
15199 // Add operator candidates that are member functions.
15200 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15201
15202 // Add candidates from ADL.
15203 if (PerformADL) {
15204 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15205 /*ExplicitTemplateArgs*/nullptr,
15206 CandidateSet);
15207 }
15208
15209 // Add builtin operator candidates.
15210 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15211
15212 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15213
15214 // Perform overload resolution.
15216 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15217 case OR_Success: {
15218 // We found a built-in operator or an overloaded operator.
15219 FunctionDecl *FnDecl = Best->Function;
15220
15221 if (FnDecl) {
15222 Expr *Base = nullptr;
15223 // We matched an overloaded operator. Build a call to that
15224 // operator.
15225
15226 // Convert the arguments.
15227 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15228 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15229
15230 ExprResult InputInit;
15231 if (Method->isExplicitObjectMemberFunction())
15232 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15233 else
15235 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15236 if (InputInit.isInvalid())
15237 return ExprError();
15238 Base = Input = InputInit.get();
15239 } else {
15240 // Convert the arguments.
15241 ExprResult InputInit
15243 Context,
15244 FnDecl->getParamDecl(0)),
15246 Input);
15247 if (InputInit.isInvalid())
15248 return ExprError();
15249 Input = InputInit.get();
15250 }
15251
15252 // Build the actual expression node.
15253 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15254 Base, HadMultipleCandidates,
15255 OpLoc);
15256 if (FnExpr.isInvalid())
15257 return ExprError();
15258
15259 // Determine the result type.
15260 QualType ResultTy = FnDecl->getReturnType();
15262 ResultTy = ResultTy.getNonLValueExprType(Context);
15263
15264 Args[0] = Input;
15266 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15268 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15269
15270 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15271 return ExprError();
15272
15273 if (CheckFunctionCall(FnDecl, TheCall,
15274 FnDecl->getType()->castAs<FunctionProtoType>()))
15275 return ExprError();
15276 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15277 } else {
15278 // We matched a built-in operator. Convert the arguments, then
15279 // break out so that we will build the appropriate built-in
15280 // operator node.
15282 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15285 if (InputRes.isInvalid())
15286 return ExprError();
15287 Input = InputRes.get();
15288 break;
15289 }
15290 }
15291
15293 // This is an erroneous use of an operator which can be overloaded by
15294 // a non-member function. Check for non-member operators which were
15295 // defined too late to be candidates.
15296 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15297 // FIXME: Recover by calling the found function.
15298 return ExprError();
15299
15300 // No viable function; fall through to handling this as a
15301 // built-in operator, which will produce an error message for us.
15302 break;
15303
15304 case OR_Ambiguous:
15305 CandidateSet.NoteCandidates(
15306 PartialDiagnosticAt(OpLoc,
15307 PDiag(diag::err_ovl_ambiguous_oper_unary)
15309 << Input->getType() << Input->getSourceRange()),
15310 *this, OCD_AmbiguousCandidates, ArgsArray,
15311 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15312 return ExprError();
15313
15314 case OR_Deleted: {
15315 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15316 // object whose method was called. Later in NoteCandidates size of ArgsArray
15317 // is passed further and it eventually ends up compared to number of
15318 // function candidate parameters which never includes the object parameter,
15319 // so slice ArgsArray to make sure apples are compared to apples.
15320 StringLiteral *Msg = Best->Function->getDeletedMessage();
15321 CandidateSet.NoteCandidates(
15322 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15324 << (Msg != nullptr)
15325 << (Msg ? Msg->getString() : StringRef())
15326 << Input->getSourceRange()),
15327 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15328 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15329 return ExprError();
15330 }
15331 }
15332
15333 // Either we found no viable overloaded operator or we matched a
15334 // built-in operator. In either case, fall through to trying to
15335 // build a built-in operation.
15336 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15337}
15338
15341 const UnresolvedSetImpl &Fns,
15342 ArrayRef<Expr *> Args, bool PerformADL) {
15343 SourceLocation OpLoc = CandidateSet.getLocation();
15344
15345 OverloadedOperatorKind ExtraOp =
15348 : OO_None;
15349
15350 // Add the candidates from the given function set. This also adds the
15351 // rewritten candidates using these functions if necessary.
15352 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15353
15354 // As template candidates are not deduced immediately,
15355 // persist the array in the overload set.
15356 ArrayRef<Expr *> ReversedArgs;
15357 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15358 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15359 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15360
15361 // Add operator candidates that are member functions.
15362 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15363 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15364 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15366
15367 // In C++20, also add any rewritten member candidates.
15368 if (ExtraOp) {
15369 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15370 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15371 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15373 }
15374
15375 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15376 // performed for an assignment operator (nor for operator[] nor operator->,
15377 // which don't get here).
15378 if (Op != OO_Equal && PerformADL) {
15379 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15380 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15381 /*ExplicitTemplateArgs*/ nullptr,
15382 CandidateSet);
15383 if (ExtraOp) {
15384 DeclarationName ExtraOpName =
15385 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15386 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15387 /*ExplicitTemplateArgs*/ nullptr,
15388 CandidateSet);
15389 }
15390 }
15391
15392 // Add builtin operator candidates.
15393 //
15394 // FIXME: We don't add any rewritten candidates here. This is strictly
15395 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15396 // resulting in our selecting a rewritten builtin candidate. For example:
15397 //
15398 // enum class E { e };
15399 // bool operator!=(E, E) requires false;
15400 // bool k = E::e != E::e;
15401 //
15402 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15403 // it seems unreasonable to consider rewritten builtin candidates. A core
15404 // issue has been filed proposing to removed this requirement.
15405 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15406}
15407
15410 const UnresolvedSetImpl &Fns, Expr *LHS,
15411 Expr *RHS, bool PerformADL,
15412 bool AllowRewrittenCandidates,
15413 FunctionDecl *DefaultedFn) {
15414 Expr *Args[2] = { LHS, RHS };
15415 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15416
15417 if (!getLangOpts().CPlusPlus20)
15418 AllowRewrittenCandidates = false;
15419
15421
15422 // If either side is type-dependent, create an appropriate dependent
15423 // expression.
15424 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15425 if (Fns.empty()) {
15426 // If there are no functions to store, just build a dependent
15427 // BinaryOperator or CompoundAssignment.
15430 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15431 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15432 Context.DependentTy);
15434 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15436 }
15437
15438 // FIXME: save results of ADL from here?
15439 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15440 // TODO: provide better source location info in DNLoc component.
15441 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15442 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15444 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15445 if (Fn.isInvalid())
15446 return ExprError();
15447 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15448 Context.DependentTy, VK_PRValue, OpLoc,
15450 }
15451
15452 // If this is the .* operator, which is not overloadable, just
15453 // create a built-in binary operator.
15454 if (Opc == BO_PtrMemD) {
15455 auto CheckPlaceholder = [&](Expr *&Arg) {
15457 if (Res.isUsable())
15458 Arg = Res.get();
15459 return !Res.isUsable();
15460 };
15461
15462 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15463 // expression that contains placeholders (in either the LHS or RHS).
15464 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15465 return ExprError();
15466 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15467 }
15468
15469 // Always do placeholder-like conversions on the RHS.
15470 if (checkPlaceholderForOverload(*this, Args[1]))
15471 return ExprError();
15472
15473 // Do placeholder-like conversion on the LHS; note that we should
15474 // not get here with a PseudoObject LHS.
15475 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15476 if (checkPlaceholderForOverload(*this, Args[0]))
15477 return ExprError();
15478
15479 // If this is the assignment operator, we only perform overload resolution
15480 // if the left-hand side is a class or enumeration type. This is actually
15481 // a hack. The standard requires that we do overload resolution between the
15482 // various built-in candidates, but as DR507 points out, this can lead to
15483 // problems. So we do it this way, which pretty much follows what GCC does.
15484 // Note that we go the traditional code path for compound assignment forms.
15485 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15486 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15487
15488 // Build the overload set.
15491 Op, OpLoc, AllowRewrittenCandidates));
15492 if (DefaultedFn)
15493 CandidateSet.exclude(DefaultedFn);
15494 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15495
15496 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15497
15498 // Perform overload resolution.
15500 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15501 case OR_Success: {
15502 // We found a built-in operator or an overloaded operator.
15503 FunctionDecl *FnDecl = Best->Function;
15504
15505 bool IsReversed = Best->isReversed();
15506 if (IsReversed)
15507 std::swap(Args[0], Args[1]);
15508
15509 if (FnDecl) {
15510
15511 if (FnDecl->isInvalidDecl())
15512 return ExprError();
15513
15514 Expr *Base = nullptr;
15515 // We matched an overloaded operator. Build a call to that
15516 // operator.
15517
15518 OverloadedOperatorKind ChosenOp =
15520
15521 // C++2a [over.match.oper]p9:
15522 // If a rewritten operator== candidate is selected by overload
15523 // resolution for an operator@, its return type shall be cv bool
15524 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15525 !FnDecl->getReturnType()->isBooleanType()) {
15526 bool IsExtension =
15528 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15529 : diag::err_ovl_rewrite_equalequal_not_bool)
15530 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15531 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15532 Diag(FnDecl->getLocation(), diag::note_declared_at);
15533 if (!IsExtension)
15534 return ExprError();
15535 }
15536
15537 if (AllowRewrittenCandidates && !IsReversed &&
15538 CandidateSet.getRewriteInfo().isReversible()) {
15539 // We could have reversed this operator, but didn't. Check if some
15540 // reversed form was a viable candidate, and if so, if it had a
15541 // better conversion for either parameter. If so, this call is
15542 // formally ambiguous, and allowing it is an extension.
15544 for (OverloadCandidate &Cand : CandidateSet) {
15545 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15546 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15547 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15549 *this, OpLoc, Cand.Conversions[ArgIdx],
15550 Best->Conversions[ArgIdx]) ==
15552 AmbiguousWith.push_back(Cand.Function);
15553 break;
15554 }
15555 }
15556 }
15557 }
15558
15559 if (!AmbiguousWith.empty()) {
15560 bool AmbiguousWithSelf =
15561 AmbiguousWith.size() == 1 &&
15562 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15563 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15565 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15566 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15567 if (AmbiguousWithSelf) {
15568 Diag(FnDecl->getLocation(),
15569 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15570 // Mark member== const or provide matching != to disallow reversed
15571 // args. Eg.
15572 // struct S { bool operator==(const S&); };
15573 // S()==S();
15574 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15575 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15576 !MD->isConst() &&
15577 !MD->hasCXXExplicitFunctionObjectParameter() &&
15578 Context.hasSameUnqualifiedType(
15579 MD->getFunctionObjectParameterType(),
15580 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15581 Context.hasSameUnqualifiedType(
15582 MD->getFunctionObjectParameterType(),
15583 Args[0]->getType()) &&
15584 Context.hasSameUnqualifiedType(
15585 MD->getFunctionObjectParameterType(),
15586 Args[1]->getType()))
15587 Diag(FnDecl->getLocation(),
15588 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15589 } else {
15590 Diag(FnDecl->getLocation(),
15591 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15592 for (auto *F : AmbiguousWith)
15593 Diag(F->getLocation(),
15594 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15595 }
15596 }
15597 }
15598
15599 // Check for nonnull = nullable.
15600 // This won't be caught in the arg's initialization: the parameter to
15601 // the assignment operator is not marked nonnull.
15602 if (Op == OO_Equal)
15604 Args[1]->getType(), OpLoc);
15605
15606 // Convert the arguments.
15607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15608 // Best->Access is only meaningful for class members.
15609 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15610
15611 ExprResult Arg0, Arg1;
15612 unsigned ParamIdx = 0;
15613 if (Method->isExplicitObjectMemberFunction()) {
15614 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15615 ParamIdx = 1;
15616 } else {
15618 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15619 }
15622 Context, FnDecl->getParamDecl(ParamIdx)),
15623 SourceLocation(), Args[1]);
15624 if (Arg0.isInvalid() || Arg1.isInvalid())
15625 return ExprError();
15626
15627 Base = Args[0] = Arg0.getAs<Expr>();
15628 Args[1] = RHS = Arg1.getAs<Expr>();
15629 } else {
15630 // Convert the arguments.
15633 FnDecl->getParamDecl(0)),
15634 SourceLocation(), Args[0]);
15635 if (Arg0.isInvalid())
15636 return ExprError();
15637
15638 ExprResult Arg1 =
15641 FnDecl->getParamDecl(1)),
15642 SourceLocation(), Args[1]);
15643 if (Arg1.isInvalid())
15644 return ExprError();
15645 Args[0] = LHS = Arg0.getAs<Expr>();
15646 Args[1] = RHS = Arg1.getAs<Expr>();
15647 }
15648
15649 // Build the actual expression node.
15650 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15651 Best->FoundDecl, Base,
15652 HadMultipleCandidates, OpLoc);
15653 if (FnExpr.isInvalid())
15654 return ExprError();
15655
15656 // Determine the result type.
15657 QualType ResultTy = FnDecl->getReturnType();
15659 ResultTy = ResultTy.getNonLValueExprType(Context);
15660
15661 CallExpr *TheCall;
15662 ArrayRef<const Expr *> ArgsArray(Args, 2);
15663 const Expr *ImplicitThis = nullptr;
15664
15665 // We always create a CXXOperatorCallExpr, even for explicit object
15666 // members; CodeGen should take care not to emit the this pointer.
15668 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15670 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15671
15672 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15673 Method && Method->isImplicitObjectMemberFunction()) {
15674 // Cut off the implicit 'this'.
15675 ImplicitThis = ArgsArray[0];
15676 ArgsArray = ArgsArray.slice(1);
15677 }
15678
15679 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15680 FnDecl))
15681 return ExprError();
15682
15683 if (Op == OO_Equal) {
15684 // Check for a self move.
15685 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15686 // lifetime check.
15688 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15689 Args[1]);
15690 }
15691 if (ImplicitThis) {
15692 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15693 QualType ThisTypeFromDecl = Context.getPointerType(
15694 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15695
15696 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15697 ThisTypeFromDecl);
15698 }
15699
15700 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15701 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15703
15704 ExprResult R = MaybeBindToTemporary(TheCall);
15705 if (R.isInvalid())
15706 return ExprError();
15707
15708 R = CheckForImmediateInvocation(R, FnDecl);
15709 if (R.isInvalid())
15710 return ExprError();
15711
15712 // For a rewritten candidate, we've already reversed the arguments
15713 // if needed. Perform the rest of the rewrite now.
15714 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15715 (Op == OO_Spaceship && IsReversed)) {
15716 if (Op == OO_ExclaimEqual) {
15717 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15718 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15719 } else {
15720 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15721 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15722 Expr *ZeroLiteral =
15724
15727 Ctx.Entity = FnDecl;
15729
15731 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15732 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15733 /*AllowRewrittenCandidates=*/false);
15734
15736 }
15737 if (R.isInvalid())
15738 return ExprError();
15739 } else {
15740 assert(ChosenOp == Op && "unexpected operator name");
15741 }
15742
15743 // Make a note in the AST if we did any rewriting.
15744 if (Best->RewriteKind != CRK_None)
15745 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15746
15747 return R;
15748 } else {
15749 // We matched a built-in operator. Convert the arguments, then
15750 // break out so that we will build the appropriate built-in
15751 // operator node.
15753 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15756 if (ArgsRes0.isInvalid())
15757 return ExprError();
15758 Args[0] = ArgsRes0.get();
15759
15761 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15764 if (ArgsRes1.isInvalid())
15765 return ExprError();
15766 Args[1] = ArgsRes1.get();
15767 break;
15768 }
15769 }
15770
15771 case OR_No_Viable_Function: {
15772 // C++ [over.match.oper]p9:
15773 // If the operator is the operator , [...] and there are no
15774 // viable functions, then the operator is assumed to be the
15775 // built-in operator and interpreted according to clause 5.
15776 if (Opc == BO_Comma)
15777 break;
15778
15779 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15780 // compare result using '==' and '<'.
15781 if (DefaultedFn && Opc == BO_Cmp) {
15782 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15783 Args[1], DefaultedFn);
15784 if (E.isInvalid() || E.isUsable())
15785 return E;
15786 }
15787
15788 // For class as left operand for assignment or compound assignment
15789 // operator do not fall through to handling in built-in, but report that
15790 // no overloaded assignment operator found
15792 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15793 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15794 Args, OpLoc);
15795 DeferDiagsRAII DDR(*this,
15796 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15797 if (Args[0]->getType()->isRecordType() &&
15798 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15799 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15801 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15802 if (Args[0]->getType()->isIncompleteType()) {
15803 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15804 << Args[0]->getType()
15805 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15806 }
15807 } else {
15808 // This is an erroneous use of an operator which can be overloaded by
15809 // a non-member function. Check for non-member operators which were
15810 // defined too late to be candidates.
15811 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15812 // FIXME: Recover by calling the found function.
15813 return ExprError();
15814
15815 // No viable function; try to create a built-in operation, which will
15816 // produce an error. Then, show the non-viable candidates.
15817 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15818 }
15819 assert(Result.isInvalid() &&
15820 "C++ binary operator overloading is missing candidates!");
15821 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15822 return Result;
15823 }
15824
15825 case OR_Ambiguous:
15826 CandidateSet.NoteCandidates(
15827 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15829 << Args[0]->getType()
15830 << Args[1]->getType()
15831 << Args[0]->getSourceRange()
15832 << Args[1]->getSourceRange()),
15834 OpLoc);
15835 return ExprError();
15836
15837 case OR_Deleted: {
15838 if (isImplicitlyDeleted(Best->Function)) {
15839 FunctionDecl *DeletedFD = Best->Function;
15841 if (DFK.isSpecialMember()) {
15842 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15843 << Args[0]->getType() << DFK.asSpecialMember();
15844 } else {
15845 assert(DFK.isComparison());
15846 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15847 << Args[0]->getType() << DeletedFD;
15848 }
15849
15850 // The user probably meant to call this special member. Just
15851 // explain why it's deleted.
15852 NoteDeletedFunction(DeletedFD);
15853 return ExprError();
15854 }
15855
15856 StringLiteral *Msg = Best->Function->getDeletedMessage();
15857 CandidateSet.NoteCandidates(
15859 OpLoc,
15860 PDiag(diag::err_ovl_deleted_oper)
15861 << getOperatorSpelling(Best->Function->getDeclName()
15862 .getCXXOverloadedOperator())
15863 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15864 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15866 OpLoc);
15867 return ExprError();
15868 }
15869 }
15870
15871 // We matched a built-in operator; build it.
15872 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15873}
15874
15876 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15877 FunctionDecl *DefaultedFn) {
15878 const ComparisonCategoryInfo *Info =
15879 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15880 // If we're not producing a known comparison category type, we can't
15881 // synthesize a three-way comparison. Let the caller diagnose this.
15882 if (!Info)
15883 return ExprResult((Expr*)nullptr);
15884
15885 // If we ever want to perform this synthesis more generally, we will need to
15886 // apply the temporary materialization conversion to the operands.
15887 assert(LHS->isGLValue() && RHS->isGLValue() &&
15888 "cannot use prvalue expressions more than once");
15889 Expr *OrigLHS = LHS;
15890 Expr *OrigRHS = RHS;
15891
15892 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15893 // each of them multiple times below.
15894 LHS = new (Context)
15895 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15896 LHS->getObjectKind(), LHS);
15897 RHS = new (Context)
15898 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15899 RHS->getObjectKind(), RHS);
15900
15901 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15902 DefaultedFn);
15903 if (Eq.isInvalid())
15904 return ExprError();
15905
15906 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15907 true, DefaultedFn);
15908 if (Less.isInvalid())
15909 return ExprError();
15910
15912 if (Info->isPartial()) {
15913 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15914 DefaultedFn);
15915 if (Greater.isInvalid())
15916 return ExprError();
15917 }
15918
15919 // Form the list of comparisons we're going to perform.
15920 struct Comparison {
15923 } Comparisons[4] =
15929 };
15930
15931 int I = Info->isPartial() ? 3 : 2;
15932
15933 // Combine the comparisons with suitable conditional expressions.
15935 for (; I >= 0; --I) {
15936 // Build a reference to the comparison category constant.
15937 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15938 // FIXME: Missing a constant for a comparison category. Diagnose this?
15939 if (!VI)
15940 return ExprResult((Expr*)nullptr);
15941 ExprResult ThisResult =
15943 if (ThisResult.isInvalid())
15944 return ExprError();
15945
15946 // Build a conditional unless this is the final case.
15947 if (Result.get()) {
15948 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15949 ThisResult.get(), Result.get());
15950 if (Result.isInvalid())
15951 return ExprError();
15952 } else {
15953 Result = ThisResult;
15954 }
15955 }
15956
15957 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15958 // bind the OpaqueValueExprs before they're (repeatedly) used.
15959 Expr *SyntacticForm = BinaryOperator::Create(
15960 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15961 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15963 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15964 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15965}
15966
15968 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15969 MultiExprArg Args, SourceLocation LParenLoc) {
15970
15971 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15972 unsigned NumParams = Proto->getNumParams();
15973 unsigned NumArgsSlots =
15974 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15975 // Build the full argument list for the method call (the implicit object
15976 // parameter is placed at the beginning of the list).
15977 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15978 bool IsError = false;
15979 // Initialize the implicit object parameter.
15980 // Check the argument types.
15981 for (unsigned i = 0; i != NumParams; i++) {
15982 Expr *Arg;
15983 if (i < Args.size()) {
15984 Arg = Args[i];
15985 ExprResult InputInit =
15987 S.Context, Method->getParamDecl(i)),
15988 SourceLocation(), Arg);
15989 IsError |= InputInit.isInvalid();
15990 Arg = InputInit.getAs<Expr>();
15991 } else {
15992 ExprResult DefArg =
15993 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15994 if (DefArg.isInvalid()) {
15995 IsError = true;
15996 break;
15997 }
15998 Arg = DefArg.getAs<Expr>();
15999 }
16000
16001 MethodArgs.push_back(Arg);
16002 }
16003 return IsError;
16004}
16005
16007 SourceLocation RLoc,
16008 Expr *Base,
16009 MultiExprArg ArgExpr) {
16011 Args.push_back(Base);
16012 for (auto *e : ArgExpr) {
16013 Args.push_back(e);
16014 }
16015 DeclarationName OpName =
16016 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16017
16018 SourceRange Range = ArgExpr.empty()
16019 ? SourceRange{}
16020 : SourceRange(ArgExpr.front()->getBeginLoc(),
16021 ArgExpr.back()->getEndLoc());
16022
16023 // If either side is type-dependent, create an appropriate dependent
16024 // expression.
16026
16027 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16028 // CHECKME: no 'operator' keyword?
16029 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16030 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16032 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16033 if (Fn.isInvalid())
16034 return ExprError();
16035 // Can't add any actual overloads yet
16036
16037 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16038 Context.DependentTy, VK_PRValue, RLoc,
16040 }
16041
16042 // Handle placeholders
16043 UnbridgedCastsSet UnbridgedCasts;
16044 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16045 return ExprError();
16046 }
16047 // Build an empty overload set.
16049
16050 // Subscript can only be overloaded as a member function.
16051
16052 // Add operator candidates that are member functions.
16053 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16054
16055 // Add builtin operator candidates.
16056 if (Args.size() == 2)
16057 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16058
16059 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16060
16061 // Perform overload resolution.
16063 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16064 case OR_Success: {
16065 // We found a built-in operator or an overloaded operator.
16066 FunctionDecl *FnDecl = Best->Function;
16067
16068 if (FnDecl) {
16069 // We matched an overloaded operator. Build a call to that
16070 // operator.
16071
16072 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16073
16074 // Convert the arguments.
16076 SmallVector<Expr *, 2> MethodArgs;
16077
16078 // Initialize the object parameter.
16079 if (Method->isExplicitObjectMemberFunction()) {
16080 ExprResult Res =
16082 if (Res.isInvalid())
16083 return ExprError();
16084 Args[0] = Res.get();
16085 ArgExpr = Args;
16086 } else {
16088 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16089 if (Arg0.isInvalid())
16090 return ExprError();
16091
16092 MethodArgs.push_back(Arg0.get());
16093 }
16094
16096 *this, MethodArgs, Method, ArgExpr, LLoc);
16097 if (IsError)
16098 return ExprError();
16099
16100 // Build the actual expression node.
16101 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16102 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16104 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16105 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16106 if (FnExpr.isInvalid())
16107 return ExprError();
16108
16109 // Determine the result type
16110 QualType ResultTy = FnDecl->getReturnType();
16112 ResultTy = ResultTy.getNonLValueExprType(Context);
16113
16115 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16117
16118 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16119 return ExprError();
16120
16121 if (CheckFunctionCall(Method, TheCall,
16122 Method->getType()->castAs<FunctionProtoType>()))
16123 return ExprError();
16124
16126 FnDecl);
16127 } else {
16128 // We matched a built-in operator. Convert the arguments, then
16129 // break out so that we will build the appropriate built-in
16130 // operator node.
16132 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16135 if (ArgsRes0.isInvalid())
16136 return ExprError();
16137 Args[0] = ArgsRes0.get();
16138
16140 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16143 if (ArgsRes1.isInvalid())
16144 return ExprError();
16145 Args[1] = ArgsRes1.get();
16146
16147 break;
16148 }
16149 }
16150
16151 case OR_No_Viable_Function: {
16153 CandidateSet.empty()
16154 ? (PDiag(diag::err_ovl_no_oper)
16155 << Args[0]->getType() << /*subscript*/ 0
16156 << Args[0]->getSourceRange() << Range)
16157 : (PDiag(diag::err_ovl_no_viable_subscript)
16158 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16159 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16160 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16161 return ExprError();
16162 }
16163
16164 case OR_Ambiguous:
16165 if (Args.size() == 2) {
16166 CandidateSet.NoteCandidates(
16168 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16169 << "[]" << Args[0]->getType() << Args[1]->getType()
16170 << Args[0]->getSourceRange() << Range),
16171 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16172 } else {
16173 CandidateSet.NoteCandidates(
16175 PDiag(diag::err_ovl_ambiguous_subscript_call)
16176 << Args[0]->getType()
16177 << Args[0]->getSourceRange() << Range),
16178 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16179 }
16180 return ExprError();
16181
16182 case OR_Deleted: {
16183 StringLiteral *Msg = Best->Function->getDeletedMessage();
16184 CandidateSet.NoteCandidates(
16186 PDiag(diag::err_ovl_deleted_oper)
16187 << "[]" << (Msg != nullptr)
16188 << (Msg ? Msg->getString() : StringRef())
16189 << Args[0]->getSourceRange() << Range),
16190 *this, OCD_AllCandidates, Args, "[]", LLoc);
16191 return ExprError();
16192 }
16193 }
16194
16195 // We matched a built-in operator; build it.
16196 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16197}
16198
16200 SourceLocation LParenLoc,
16201 MultiExprArg Args,
16202 SourceLocation RParenLoc,
16203 Expr *ExecConfig, bool IsExecConfig,
16204 bool AllowRecovery) {
16205 assert(MemExprE->getType() == Context.BoundMemberTy ||
16206 MemExprE->getType() == Context.OverloadTy);
16207
16208 // Dig out the member expression. This holds both the object
16209 // argument and the member function we're referring to.
16210 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16211
16212 // Determine whether this is a call to a pointer-to-member function.
16213 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16214 assert(op->getType() == Context.BoundMemberTy);
16215 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16216
16217 QualType fnType =
16218 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16219
16220 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16221 QualType resultType = proto->getCallResultType(Context);
16223
16224 // Check that the object type isn't more qualified than the
16225 // member function we're calling.
16226 Qualifiers funcQuals = proto->getMethodQuals();
16227
16228 QualType objectType = op->getLHS()->getType();
16229 if (op->getOpcode() == BO_PtrMemI)
16230 objectType = objectType->castAs<PointerType>()->getPointeeType();
16231 Qualifiers objectQuals = objectType.getQualifiers();
16232
16233 Qualifiers difference = objectQuals - funcQuals;
16234 difference.removeObjCGCAttr();
16235 difference.removeAddressSpace();
16236 if (difference) {
16237 std::string qualsString = difference.getAsString();
16238 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16239 << fnType.getUnqualifiedType()
16240 << qualsString
16241 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16242 }
16243
16245 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16247
16248 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16249 call, nullptr))
16250 return ExprError();
16251
16252 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16253 return ExprError();
16254
16255 if (CheckOtherCall(call, proto))
16256 return ExprError();
16257
16258 return MaybeBindToTemporary(call);
16259 }
16260
16261 // We only try to build a recovery expr at this level if we can preserve
16262 // the return type, otherwise we return ExprError() and let the caller
16263 // recover.
16264 auto BuildRecoveryExpr = [&](QualType Type) {
16265 if (!AllowRecovery)
16266 return ExprError();
16267 std::vector<Expr *> SubExprs = {MemExprE};
16268 llvm::append_range(SubExprs, Args);
16269 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16270 Type);
16271 };
16272 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16273 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16274 RParenLoc, CurFPFeatureOverrides());
16275
16276 UnbridgedCastsSet UnbridgedCasts;
16277 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16278 return ExprError();
16279
16280 MemberExpr *MemExpr;
16281 CXXMethodDecl *Method = nullptr;
16282 bool HadMultipleCandidates = false;
16283 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16284 NestedNameSpecifier Qualifier = std::nullopt;
16285 if (isa<MemberExpr>(NakedMemExpr)) {
16286 MemExpr = cast<MemberExpr>(NakedMemExpr);
16288 FoundDecl = MemExpr->getFoundDecl();
16289 Qualifier = MemExpr->getQualifier();
16290 UnbridgedCasts.restore();
16291 } else {
16292 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16293 Qualifier = UnresExpr->getQualifier();
16294
16295 QualType ObjectType = UnresExpr->getBaseType();
16296 Expr::Classification ObjectClassification
16298 : UnresExpr->getBase()->Classify(Context);
16299
16300 // Add overload candidates
16301 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16303
16304 // FIXME: avoid copy.
16305 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16306 if (UnresExpr->hasExplicitTemplateArgs()) {
16307 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16308 TemplateArgs = &TemplateArgsBuffer;
16309 }
16310
16312 E = UnresExpr->decls_end(); I != E; ++I) {
16313
16314 QualType ExplicitObjectType = ObjectType;
16315
16316 NamedDecl *Func = *I;
16317 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16319 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16320
16321 bool HasExplicitParameter = false;
16322 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16323 M && M->hasCXXExplicitFunctionObjectParameter())
16324 HasExplicitParameter = true;
16325 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16326 M &&
16327 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16328 HasExplicitParameter = true;
16329
16330 if (HasExplicitParameter)
16331 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16332
16333 // Microsoft supports direct constructor calls.
16334 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16336 CandidateSet,
16337 /*SuppressUserConversions*/ false);
16338 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16339 // If explicit template arguments were provided, we can't call a
16340 // non-template member function.
16341 if (TemplateArgs)
16342 continue;
16343
16344 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16345 ObjectClassification, Args, CandidateSet,
16346 /*SuppressUserConversions=*/false);
16347 } else {
16349 I.getPair(), ActingDC, TemplateArgs,
16350 ExplicitObjectType, ObjectClassification,
16351 Args, CandidateSet,
16352 /*SuppressUserConversions=*/false);
16353 }
16354 }
16355
16356 HadMultipleCandidates = (CandidateSet.size() > 1);
16357
16358 DeclarationName DeclName = UnresExpr->getMemberName();
16359
16360 UnbridgedCasts.restore();
16361
16363 bool Succeeded = false;
16364 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16365 Best)) {
16366 case OR_Success:
16367 Method = cast<CXXMethodDecl>(Best->Function);
16368 FoundDecl = Best->FoundDecl;
16369 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16370 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16371 break;
16372 // If FoundDecl is different from Method (such as if one is a template
16373 // and the other a specialization), make sure DiagnoseUseOfDecl is
16374 // called on both.
16375 // FIXME: This would be more comprehensively addressed by modifying
16376 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16377 // being used.
16378 if (Method != FoundDecl.getDecl() &&
16380 break;
16381 Succeeded = true;
16382 break;
16383
16385 CandidateSet.NoteCandidates(
16387 UnresExpr->getMemberLoc(),
16388 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16389 << DeclName << MemExprE->getSourceRange()),
16390 *this, OCD_AllCandidates, Args);
16391 break;
16392 case OR_Ambiguous:
16393 CandidateSet.NoteCandidates(
16394 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16395 PDiag(diag::err_ovl_ambiguous_member_call)
16396 << DeclName << MemExprE->getSourceRange()),
16397 *this, OCD_AmbiguousCandidates, Args);
16398 break;
16399 case OR_Deleted:
16401 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16402 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16403 break;
16404 }
16405 // Overload resolution fails, try to recover.
16406 if (!Succeeded)
16407 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16408
16409 ExprResult Res =
16410 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16411 if (Res.isInvalid())
16412 return ExprError();
16413 MemExprE = Res.get();
16414
16415 // If overload resolution picked a static member
16416 // build a non-member call based on that function.
16417 if (Method->isStatic()) {
16418 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16419 ExecConfig, IsExecConfig);
16420 }
16421
16422 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16423 }
16424
16425 QualType ResultType = Method->getReturnType();
16427 ResultType = ResultType.getNonLValueExprType(Context);
16428
16429 assert(Method && "Member call to something that isn't a method?");
16430 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16431
16432 CallExpr *TheCall = nullptr;
16434 if (Method->isExplicitObjectMemberFunction()) {
16435 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16436 NewArgs))
16437 return ExprError();
16438
16439 // Build the actual expression node.
16440 ExprResult FnExpr =
16441 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16442 HadMultipleCandidates, MemExpr->getExprLoc());
16443 if (FnExpr.isInvalid())
16444 return ExprError();
16445
16446 TheCall =
16447 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16448 CurFPFeatureOverrides(), Proto->getNumParams());
16449 TheCall->setUsesMemberSyntax(true);
16450 } else {
16451 // Convert the object argument (for a non-static member function call).
16453 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16454 if (ObjectArg.isInvalid())
16455 return ExprError();
16456 MemExpr->setBase(ObjectArg.get());
16457 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16458 RParenLoc, CurFPFeatureOverrides(),
16459 Proto->getNumParams());
16460 }
16461
16462 // Check for a valid return type.
16463 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16464 TheCall, Method))
16465 return BuildRecoveryExpr(ResultType);
16466
16467 // Convert the rest of the arguments
16468 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16469 RParenLoc))
16470 return BuildRecoveryExpr(ResultType);
16471
16472 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16473
16474 if (CheckFunctionCall(Method, TheCall, Proto))
16475 return ExprError();
16476
16477 // In the case the method to call was not selected by the overloading
16478 // resolution process, we still need to handle the enable_if attribute. Do
16479 // that here, so it will not hide previous -- and more relevant -- errors.
16480 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16481 if (const EnableIfAttr *Attr =
16482 CheckEnableIf(Method, LParenLoc, Args, true)) {
16483 Diag(MemE->getMemberLoc(),
16484 diag::err_ovl_no_viable_member_function_in_call)
16485 << Method << Method->getSourceRange();
16486 Diag(Method->getLocation(),
16487 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16488 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16489 return ExprError();
16490 }
16491 }
16492
16494 TheCall->getDirectCallee()->isPureVirtual()) {
16495 const FunctionDecl *MD = TheCall->getDirectCallee();
16496
16497 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16499 Diag(MemExpr->getBeginLoc(),
16500 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16502 << MD->getParent();
16503
16504 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16505 if (getLangOpts().AppleKext)
16506 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16507 << MD->getParent() << MD->getDeclName();
16508 }
16509 }
16510
16511 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16512 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16513 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16514 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16515 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16516 MemExpr->getMemberLoc());
16517 }
16518
16520 TheCall->getDirectCallee());
16521}
16522
16525 SourceLocation LParenLoc,
16526 MultiExprArg Args,
16527 SourceLocation RParenLoc) {
16528 if (checkPlaceholderForOverload(*this, Obj))
16529 return ExprError();
16530 ExprResult Object = Obj;
16531
16532 UnbridgedCastsSet UnbridgedCasts;
16533 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16534 return ExprError();
16535
16536 assert(Object.get()->getType()->isRecordType() &&
16537 "Requires object type argument");
16538
16539 // C++ [over.call.object]p1:
16540 // If the primary-expression E in the function call syntax
16541 // evaluates to a class object of type "cv T", then the set of
16542 // candidate functions includes at least the function call
16543 // operators of T. The function call operators of T are obtained by
16544 // ordinary lookup of the name operator() in the context of
16545 // (E).operator().
16546 OverloadCandidateSet CandidateSet(LParenLoc,
16548 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16549
16550 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16551 diag::err_incomplete_object_call, Object.get()))
16552 return true;
16553
16554 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16555 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16558
16559 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16560 Oper != OperEnd; ++Oper) {
16561 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16562 Object.get()->Classify(Context), Args, CandidateSet,
16563 /*SuppressUserConversion=*/false);
16564 }
16565
16566 // When calling a lambda, both the call operator, and
16567 // the conversion operator to function pointer
16568 // are considered. But when constraint checking
16569 // on the call operator fails, it will also fail on the
16570 // conversion operator as the constraints are always the same.
16571 // As the user probably does not intend to perform a surrogate call,
16572 // we filter them out to produce better error diagnostics, ie to avoid
16573 // showing 2 failed overloads instead of one.
16574 bool IgnoreSurrogateFunctions = false;
16575 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16576 const OverloadCandidate &Candidate = *CandidateSet.begin();
16577 if (!Candidate.Viable &&
16579 IgnoreSurrogateFunctions = true;
16580 }
16581
16582 // C++ [over.call.object]p2:
16583 // In addition, for each (non-explicit in C++0x) conversion function
16584 // declared in T of the form
16585 //
16586 // operator conversion-type-id () cv-qualifier;
16587 //
16588 // where cv-qualifier is the same cv-qualification as, or a
16589 // greater cv-qualification than, cv, and where conversion-type-id
16590 // denotes the type "pointer to function of (P1,...,Pn) returning
16591 // R", or the type "reference to pointer to function of
16592 // (P1,...,Pn) returning R", or the type "reference to function
16593 // of (P1,...,Pn) returning R", a surrogate call function [...]
16594 // is also considered as a candidate function. Similarly,
16595 // surrogate call functions are added to the set of candidate
16596 // functions for each conversion function declared in an
16597 // accessible base class provided the function is not hidden
16598 // within T by another intervening declaration.
16599 const auto &Conversions = Record->getVisibleConversionFunctions();
16600 for (auto I = Conversions.begin(), E = Conversions.end();
16601 !IgnoreSurrogateFunctions && I != E; ++I) {
16602 NamedDecl *D = *I;
16603 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16604 if (isa<UsingShadowDecl>(D))
16605 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16606
16607 // Skip over templated conversion functions; they aren't
16608 // surrogates.
16610 continue;
16611
16613 if (!Conv->isExplicit()) {
16614 // Strip the reference type (if any) and then the pointer type (if
16615 // any) to get down to what might be a function type.
16616 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16617 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16618 ConvType = ConvPtrType->getPointeeType();
16619
16620 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16621 {
16622 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16623 Object.get(), Args, CandidateSet);
16624 }
16625 }
16626 }
16627
16628 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16629
16630 // Perform overload resolution.
16632 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16633 Best)) {
16634 case OR_Success:
16635 // Overload resolution succeeded; we'll build the appropriate call
16636 // below.
16637 break;
16638
16639 case OR_No_Viable_Function: {
16641 CandidateSet.empty()
16642 ? (PDiag(diag::err_ovl_no_oper)
16643 << Object.get()->getType() << /*call*/ 1
16644 << Object.get()->getSourceRange())
16645 : (PDiag(diag::err_ovl_no_viable_object_call)
16646 << Object.get()->getType() << Object.get()->getSourceRange());
16647 CandidateSet.NoteCandidates(
16648 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16649 OCD_AllCandidates, Args);
16650 break;
16651 }
16652 case OR_Ambiguous:
16653 if (!R.isAmbiguous())
16654 CandidateSet.NoteCandidates(
16655 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16656 PDiag(diag::err_ovl_ambiguous_object_call)
16657 << Object.get()->getType()
16658 << Object.get()->getSourceRange()),
16659 *this, OCD_AmbiguousCandidates, Args);
16660 break;
16661
16662 case OR_Deleted: {
16663 // FIXME: Is this diagnostic here really necessary? It seems that
16664 // 1. we don't have any tests for this diagnostic, and
16665 // 2. we already issue err_deleted_function_use for this later on anyway.
16666 StringLiteral *Msg = Best->Function->getDeletedMessage();
16667 CandidateSet.NoteCandidates(
16668 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16669 PDiag(diag::err_ovl_deleted_object_call)
16670 << Object.get()->getType() << (Msg != nullptr)
16671 << (Msg ? Msg->getString() : StringRef())
16672 << Object.get()->getSourceRange()),
16673 *this, OCD_AllCandidates, Args);
16674 break;
16675 }
16676 }
16677
16678 if (Best == CandidateSet.end())
16679 return true;
16680
16681 UnbridgedCasts.restore();
16682
16683 if (Best->Function == nullptr) {
16684 // Since there is no function declaration, this is one of the
16685 // surrogate candidates. Dig out the conversion function.
16686 CXXConversionDecl *Conv
16688 Best->Conversions[0].UserDefined.ConversionFunction);
16689
16690 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16691 Best->FoundDecl);
16692 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16693 return ExprError();
16694 assert(Conv == Best->FoundDecl.getDecl() &&
16695 "Found Decl & conversion-to-functionptr should be same, right?!");
16696 // We selected one of the surrogate functions that converts the
16697 // object parameter to a function pointer. Perform the conversion
16698 // on the object argument, then let BuildCallExpr finish the job.
16699
16700 // Create an implicit member expr to refer to the conversion operator.
16701 // and then call it.
16702 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16703 Conv, HadMultipleCandidates);
16704 if (Call.isInvalid())
16705 return ExprError();
16706 // Record usage of conversion in an implicit cast.
16708 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16709 nullptr, VK_PRValue, CurFPFeatureOverrides());
16710
16711 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16712 }
16713
16714 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16715
16716 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16717 // that calls this method, using Object for the implicit object
16718 // parameter and passing along the remaining arguments.
16719 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16720
16721 // An error diagnostic has already been printed when parsing the declaration.
16722 if (Method->isInvalidDecl())
16723 return ExprError();
16724
16725 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16726 unsigned NumParams = Proto->getNumParams();
16727
16728 DeclarationNameInfo OpLocInfo(
16729 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16730 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16731 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16732 Obj, HadMultipleCandidates,
16733 OpLocInfo.getLoc(),
16734 OpLocInfo.getInfo());
16735 if (NewFn.isInvalid())
16736 return true;
16737
16738 SmallVector<Expr *, 8> MethodArgs;
16739 MethodArgs.reserve(NumParams + 1);
16740
16741 bool IsError = false;
16742
16743 // Initialize the object parameter.
16745 if (Method->isExplicitObjectMemberFunction()) {
16746 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16747 } else {
16749 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16750 if (ObjRes.isInvalid())
16751 IsError = true;
16752 else
16753 Object = ObjRes;
16754 MethodArgs.push_back(Object.get());
16755 }
16756
16758 *this, MethodArgs, Method, Args, LParenLoc);
16759
16760 // If this is a variadic call, handle args passed through "...".
16761 if (Proto->isVariadic()) {
16762 // Promote the arguments (C99 6.5.2.2p7).
16763 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16765 Args[i], VariadicCallType::Method, nullptr);
16766 IsError |= Arg.isInvalid();
16767 MethodArgs.push_back(Arg.get());
16768 }
16769 }
16770
16771 if (IsError)
16772 return true;
16773
16774 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16775
16776 // Once we've built TheCall, all of the expressions are properly owned.
16777 QualType ResultTy = Method->getReturnType();
16779 ResultTy = ResultTy.getNonLValueExprType(Context);
16780
16782 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16784
16785 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16786 return true;
16787
16788 if (CheckFunctionCall(Method, TheCall, Proto))
16789 return true;
16790
16792}
16793
16795 SourceLocation OpLoc,
16796 bool *NoArrowOperatorFound) {
16797 assert(Base->getType()->isRecordType() &&
16798 "left-hand side must have class type");
16799
16801 return ExprError();
16802
16803 SourceLocation Loc = Base->getExprLoc();
16804
16805 // C++ [over.ref]p1:
16806 //
16807 // [...] An expression x->m is interpreted as (x.operator->())->m
16808 // for a class object x of type T if T::operator->() exists and if
16809 // the operator is selected as the best match function by the
16810 // overload resolution mechanism (13.3).
16811 DeclarationName OpName =
16812 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16814
16815 if (RequireCompleteType(Loc, Base->getType(),
16816 diag::err_typecheck_incomplete_tag, Base))
16817 return ExprError();
16818
16819 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16820 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16822
16823 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16824 Oper != OperEnd; ++Oper) {
16825 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16826 {}, CandidateSet,
16827 /*SuppressUserConversion=*/false);
16828 }
16829
16830 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16831
16832 // Perform overload resolution.
16834 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16835 case OR_Success:
16836 // Overload resolution succeeded; we'll build the call below.
16837 break;
16838
16839 case OR_No_Viable_Function: {
16840 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16841 if (CandidateSet.empty()) {
16842 QualType BaseType = Base->getType();
16843 if (NoArrowOperatorFound) {
16844 // Report this specific error to the caller instead of emitting a
16845 // diagnostic, as requested.
16846 *NoArrowOperatorFound = true;
16847 return ExprError();
16848 }
16849 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16850 << BaseType << Base->getSourceRange();
16851 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16852 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16853 << FixItHint::CreateReplacement(OpLoc, ".");
16854 }
16855 } else
16856 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16857 << "operator->" << Base->getSourceRange();
16858 CandidateSet.NoteCandidates(*this, Base, Cands);
16859 return ExprError();
16860 }
16861 case OR_Ambiguous:
16862 if (!R.isAmbiguous())
16863 CandidateSet.NoteCandidates(
16864 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16865 << "->" << Base->getType()
16866 << Base->getSourceRange()),
16868 return ExprError();
16869
16870 case OR_Deleted: {
16871 StringLiteral *Msg = Best->Function->getDeletedMessage();
16872 CandidateSet.NoteCandidates(
16873 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16874 << "->" << (Msg != nullptr)
16875 << (Msg ? Msg->getString() : StringRef())
16876 << Base->getSourceRange()),
16877 *this, OCD_AllCandidates, Base);
16878 return ExprError();
16879 }
16880 }
16881
16882 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16883
16884 // Convert the object parameter.
16885 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16886
16887 if (Method->isExplicitObjectMemberFunction()) {
16889 if (R.isInvalid())
16890 return ExprError();
16891 Base = R.get();
16892 } else {
16894 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16895 if (BaseResult.isInvalid())
16896 return ExprError();
16897 Base = BaseResult.get();
16898 }
16899
16900 // Build the operator call.
16901 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16902 Base, HadMultipleCandidates, OpLoc);
16903 if (FnExpr.isInvalid())
16904 return ExprError();
16905
16906 QualType ResultTy = Method->getReturnType();
16908 ResultTy = ResultTy.getNonLValueExprType(Context);
16909
16910 CallExpr *TheCall =
16911 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16912 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16913
16914 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16915 return ExprError();
16916
16917 if (CheckFunctionCall(Method, TheCall,
16918 Method->getType()->castAs<FunctionProtoType>()))
16919 return ExprError();
16920
16922}
16923
16925 DeclarationNameInfo &SuffixInfo,
16926 ArrayRef<Expr*> Args,
16927 SourceLocation LitEndLoc,
16928 TemplateArgumentListInfo *TemplateArgs) {
16929 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16930
16931 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16933 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16934 TemplateArgs);
16935
16936 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16937
16938 // Perform overload resolution. This will usually be trivial, but might need
16939 // to perform substitutions for a literal operator template.
16941 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16942 case OR_Success:
16943 case OR_Deleted:
16944 break;
16945
16947 CandidateSet.NoteCandidates(
16948 PartialDiagnosticAt(UDSuffixLoc,
16949 PDiag(diag::err_ovl_no_viable_function_in_call)
16950 << R.getLookupName()),
16951 *this, OCD_AllCandidates, Args);
16952 return ExprError();
16953
16954 case OR_Ambiguous:
16955 CandidateSet.NoteCandidates(
16956 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16957 << R.getLookupName()),
16958 *this, OCD_AmbiguousCandidates, Args);
16959 return ExprError();
16960 }
16961
16962 FunctionDecl *FD = Best->Function;
16963 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16964 nullptr, HadMultipleCandidates,
16965 SuffixInfo.getLoc(),
16966 SuffixInfo.getInfo());
16967 if (Fn.isInvalid())
16968 return true;
16969
16970 // Check the argument types. This should almost always be a no-op, except
16971 // that array-to-pointer decay is applied to string literals.
16972 Expr *ConvArgs[2];
16973 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16976 SourceLocation(), Args[ArgIdx]);
16977 if (InputInit.isInvalid())
16978 return true;
16979 ConvArgs[ArgIdx] = InputInit.get();
16980 }
16981
16982 QualType ResultTy = FD->getReturnType();
16984 ResultTy = ResultTy.getNonLValueExprType(Context);
16985
16987 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16988 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16989
16990 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16991 return ExprError();
16992
16993 if (CheckFunctionCall(FD, UDL, nullptr))
16994 return ExprError();
16995
16997}
16998
17001 SourceLocation RangeLoc,
17002 const DeclarationNameInfo &NameInfo,
17003 LookupResult &MemberLookup,
17004 OverloadCandidateSet *CandidateSet,
17005 Expr *Range, ExprResult *CallExpr) {
17006 Scope *S = nullptr;
17007
17009 if (!MemberLookup.empty()) {
17010 ExprResult MemberRef =
17011 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17012 /*IsPtr=*/false, CXXScopeSpec(),
17013 /*TemplateKWLoc=*/SourceLocation(),
17014 /*FirstQualifierInScope=*/nullptr,
17015 MemberLookup,
17016 /*TemplateArgs=*/nullptr, S);
17017 if (MemberRef.isInvalid()) {
17018 *CallExpr = ExprError();
17019 return FRS_DiagnosticIssued;
17020 }
17021 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17022 if (CallExpr->isInvalid()) {
17023 *CallExpr = ExprError();
17024 return FRS_DiagnosticIssued;
17025 }
17026 } else {
17027 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17029 NameInfo, UnresolvedSet<0>());
17030 if (FnR.isInvalid())
17031 return FRS_DiagnosticIssued;
17033
17034 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17035 CandidateSet, CallExpr);
17036 if (CandidateSet->empty() || CandidateSetError) {
17037 *CallExpr = ExprError();
17038 return FRS_NoViableFunction;
17039 }
17041 OverloadingResult OverloadResult =
17042 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17043
17044 if (OverloadResult == OR_No_Viable_Function) {
17045 *CallExpr = ExprError();
17046 return FRS_NoViableFunction;
17047 }
17048 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17049 Loc, nullptr, CandidateSet, &Best,
17050 OverloadResult,
17051 /*AllowTypoCorrection=*/false);
17052 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17053 *CallExpr = ExprError();
17054 return FRS_DiagnosticIssued;
17055 }
17056 }
17057 return FRS_Success;
17058}
17059
17061 FunctionDecl *Fn) {
17062 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17063 ExprResult SubExpr =
17064 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17065 if (SubExpr.isInvalid())
17066 return ExprError();
17067 if (SubExpr.get() == PE->getSubExpr())
17068 return PE;
17069
17070 return new (Context)
17071 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17072 }
17073
17074 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17075 ExprResult SubExpr =
17076 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17077 if (SubExpr.isInvalid())
17078 return ExprError();
17079 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17080 SubExpr.get()->getType()) &&
17081 "Implicit cast type cannot be determined from overload");
17082 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17083 if (SubExpr.get() == ICE->getSubExpr())
17084 return ICE;
17085
17086 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17087 SubExpr.get(), nullptr, ICE->getValueKind(),
17089 }
17090
17091 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17092 if (!GSE->isResultDependent()) {
17093 ExprResult SubExpr =
17094 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17095 if (SubExpr.isInvalid())
17096 return ExprError();
17097 if (SubExpr.get() == GSE->getResultExpr())
17098 return GSE;
17099
17100 // Replace the resulting type information before rebuilding the generic
17101 // selection expression.
17102 ArrayRef<Expr *> A = GSE->getAssocExprs();
17103 SmallVector<Expr *, 4> AssocExprs(A);
17104 unsigned ResultIdx = GSE->getResultIndex();
17105 AssocExprs[ResultIdx] = SubExpr.get();
17106
17107 if (GSE->isExprPredicate())
17109 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17110 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17111 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17112 ResultIdx);
17114 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17115 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17116 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17117 ResultIdx);
17118 }
17119 // Rather than fall through to the unreachable, return the original generic
17120 // selection expression.
17121 return GSE;
17122 }
17123
17124 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17125 assert(UnOp->getOpcode() == UO_AddrOf &&
17126 "Can only take the address of an overloaded function");
17127 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17128 if (!Method->isImplicitObjectMemberFunction()) {
17129 // Do nothing: the address of static and
17130 // explicit object member functions is a (non-member) function pointer.
17131 } else {
17132 // Fix the subexpression, which really has to be an
17133 // UnresolvedLookupExpr holding an overloaded member function
17134 // or template.
17135 ExprResult SubExpr =
17136 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17137 if (SubExpr.isInvalid())
17138 return ExprError();
17139 if (SubExpr.get() == UnOp->getSubExpr())
17140 return UnOp;
17141
17142 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17143 SubExpr.get(), Method))
17144 return ExprError();
17145
17146 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17147 "fixed to something other than a decl ref");
17148 NestedNameSpecifier Qualifier =
17149 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17150 assert(Qualifier &&
17151 "fixed to a member ref with no nested name qualifier");
17152
17153 // We have taken the address of a pointer to member
17154 // function. Perform the computation here so that we get the
17155 // appropriate pointer to member type.
17156 QualType MemPtrType = Context.getMemberPointerType(
17157 Fn->getType(), Qualifier,
17158 cast<CXXRecordDecl>(Method->getDeclContext()));
17159 // Under the MS ABI, lock down the inheritance model now.
17160 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17161 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17162
17163 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17164 MemPtrType, VK_PRValue, OK_Ordinary,
17165 UnOp->getOperatorLoc(), false,
17167 }
17168 }
17169 ExprResult SubExpr =
17170 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17171 if (SubExpr.isInvalid())
17172 return ExprError();
17173 if (SubExpr.get() == UnOp->getSubExpr())
17174 return UnOp;
17175
17176 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17177 SubExpr.get());
17178 }
17179
17180 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17181 if (Found.getAccess() == AS_none) {
17183 }
17184 // FIXME: avoid copy.
17185 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17186 if (ULE->hasExplicitTemplateArgs()) {
17187 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17188 TemplateArgs = &TemplateArgsBuffer;
17189 }
17190
17191 QualType Type = Fn->getType();
17192 ExprValueKind ValueKind =
17193 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17194 ? VK_LValue
17195 : VK_PRValue;
17196
17197 // FIXME: Duplicated from BuildDeclarationNameExpr.
17198 if (unsigned BID = Fn->getBuiltinID()) {
17199 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17200 Type = Context.BuiltinFnTy;
17201 ValueKind = VK_PRValue;
17202 }
17203 }
17204
17206 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17207 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17208 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17209 return DRE;
17210 }
17211
17212 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17213 // FIXME: avoid copy.
17214 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17215 if (MemExpr->hasExplicitTemplateArgs()) {
17216 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17217 TemplateArgs = &TemplateArgsBuffer;
17218 }
17219
17220 Expr *Base;
17221
17222 // If we're filling in a static method where we used to have an
17223 // implicit member access, rewrite to a simple decl ref.
17224 if (MemExpr->isImplicitAccess()) {
17225 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17227 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17228 MemExpr->getQualifierLoc(), Found.getDecl(),
17229 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17230 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17231 return DRE;
17232 } else {
17233 SourceLocation Loc = MemExpr->getMemberLoc();
17234 if (MemExpr->getQualifier())
17235 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17236 Base =
17237 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17238 }
17239 } else
17240 Base = MemExpr->getBase();
17241
17242 ExprValueKind valueKind;
17243 QualType type;
17244 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17245 valueKind = VK_LValue;
17246 type = Fn->getType();
17247 } else {
17248 valueKind = VK_PRValue;
17249 type = Context.BoundMemberTy;
17250 }
17251
17252 return BuildMemberExpr(
17253 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17254 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17255 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17256 type, valueKind, OK_Ordinary, TemplateArgs);
17257 }
17258
17259 llvm_unreachable("Invalid reference to overloaded function");
17260}
17261
17267
17268bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17270 if (!PartialOverloading || !Function)
17271 return true;
17272 if (Function->isVariadic())
17273 return false;
17274 if (const auto *Proto =
17275 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17276 if (Proto->isTemplateVariadic())
17277 return false;
17278 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17279 if (const auto *Proto =
17280 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17281 if (Proto->isTemplateVariadic())
17282 return false;
17283 return true;
17284}
17285
17287 DeclarationName Name,
17288 OverloadCandidateSet &CandidateSet,
17289 FunctionDecl *Fn, MultiExprArg Args,
17290 bool IsMember) {
17291 StringLiteral *Msg = Fn->getDeletedMessage();
17292 CandidateSet.NoteCandidates(
17293 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17294 << IsMember << Name << (Msg != nullptr)
17295 << (Msg ? Msg->getString() : StringRef())
17296 << Range),
17297 *this, OCD_AllCandidates, Args);
17298}
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:187
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 bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
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 bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
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 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 ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
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 IsMatrixConversion(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 matrix conversion.
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:481
bool isFloat() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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:801
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:951
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:917
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
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
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:916
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:3900
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:280
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3730
QualType getElementType() const
Definition TypeBase.h:3742
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8187
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2180
StringRef getOpcodeStr() const
Definition Expr.h:4107
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2133
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:5076
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
Pointer to a block type.
Definition TypeBase.h:3550
This class is used for builtin types like 'int'.
Definition TypeBase.h:3172
Kind getKind() const
Definition TypeBase.h:3220
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) const
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:2611
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3037
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:3074
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2982
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2986
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:180
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:2136
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:2721
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:2728
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2838
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
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:1987
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:1742
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:287
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
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:2946
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:1517
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3110
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3328
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:3283
QualType getElementType() const
Definition TypeBase.h:3293
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:5098
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3768
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4395
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4414
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4411
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:1273
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:1466
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:785
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:770
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:761
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:597
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4013
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4231
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4129
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1955
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1939
const Expr * getExpr() const
Definition DeclCXX.h:1940
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2372
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:398
bool isRValue() const
Definition Expr.h:394
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:3095
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:447
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:3086
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:3339
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4211
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
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:814
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:4050
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
ExtVectorType - Extended vector type.
Definition TypeBase.h:4275
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:4194
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
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:3667
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
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:4265
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3748
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3134
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4330
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4258
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3870
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:4131
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:3711
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:3716
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
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:5315
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5819
unsigned getNumParams() const
Definition TypeBase.h:5593
Qualifiers getMethodQuals() const
Definition TypeBase.h:5741
QualType getParamType(unsigned i) const
Definition TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5755
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:4622
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4693
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4550
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
ExtInfo getExtInfo() const
Definition TypeBase.h:4867
CallingConv getCallConv() const
Definition TypeBase.h:4866
QualType getReturnType() const
Definition TypeBase.h:4851
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4879
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:4698
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:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
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:673
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:770
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
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:827
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:681
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:812
bool hasInitializerListContainerType() const
Definition Overload.h:809
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:734
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:816
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:685
QualType getInitializerListContainerType() const
Definition Overload.h:819
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5417
unsigned getNumInits() const
Definition Expr.h:5332
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2496
const Expr * getInit(unsigned Init) const
Definition Expr.h:5356
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2514
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:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3625
bool isCompatibleWithMSVC() 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
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4359
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3478
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3464
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3585
Expr * getBase() const
Definition Expr.h:3444
void setBase(Expr *E)
Definition Expr.h:3443
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1794
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3562
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3454
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3661
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3693
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5530
QualType getPointeeType() const
Definition TypeBase.h:3679
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:7950
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8006
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8095
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8064
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8018
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8058
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1853
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8070
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
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:1360
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:1458
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1392
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:1408
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1350
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1549
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1185
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
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:1368
SourceLocation getLocation() const
Definition Overload.h:1348
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1349
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1383
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:3129
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3281
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3190
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3245
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3242
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3220
decls_iterator decls_begin() const
Definition ExprCXX.h:3222
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3233
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3255
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3251
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3343
decls_iterator decls_end() const
Definition ExprCXX.h:3225
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3239
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
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:3059
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5170
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8472
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8466
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8477
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3624
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1231
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:8388
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8514
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8428
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:8573
QualType getCanonicalType() const
Definition TypeBase.h:8440
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
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:8542
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8461
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8509
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8434
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
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:8553
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8420
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8328
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8335
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4734
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:3643
Represents a struct/union/class.
Definition Decl.h:4327
field_range fields() const
Definition Decl.h:4530
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3581
QualType getPointeeType() const
Definition TypeBase.h:3599
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:1602
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1646
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:212
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:459
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:400
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:406
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:312
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:10370
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:6405
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6434
RAII class to control scope of DeferDiags.
Definition Sema.h:10093
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1378
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1413
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:12517
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12551
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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:10111
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:9382
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9409
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9394
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9390
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:415
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:170
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:1465
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:10453
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10456
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10462
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10460
@ AR_dependent
Definition Sema.h:1680
@ AR_accessible
Definition Sema.h:1678
@ AR_inaccessible
Definition Sema.h:1679
@ AR_delayed
Definition Sema.h:1681
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:2069
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:1674
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:1300
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
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:225
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
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:1510
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:758
ASTContext & getASTContext() const
Definition Sema.h:939
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:10841
@ FRS_DiagnosticIssued
Definition Sema.h:10843
@ FRS_NoViableFunction
Definition Sema.h:10842
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9375
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:10162
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:1204
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:3629
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:12215
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:932
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:1298
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:1475
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9374
MemberPointerConversionDirection
Definition Sema.h:10294
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:10481
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.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
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:643
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:15575
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:7024
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:1438
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
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:8228
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:14026
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:7522
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:13759
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:15530
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:124
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:6790
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6759
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:10286
SourceManager & SourceMgr
Definition Sema.h:1303
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1302
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:519
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:6467
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:1445
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:8710
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:298
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:392
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:362
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:339
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:324
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:391
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:334
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:367
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:318
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:329
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
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:384
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:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
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:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
StringRef getString() const
Definition Expr.h:1870
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:678
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:732
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:717
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:1839
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2491
bool isBlockPointerType() const
Definition TypeBase.h:8645
bool isVoidType() const
Definition TypeBase.h:8991
bool isBooleanType() const
Definition TypeBase.h:9128
bool isObjCBuiltinType() const
Definition TypeBase.h:8855
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2253
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:1964
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:788
bool isIncompleteArrayType() const
Definition TypeBase.h:8732
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2230
bool isFloat16Type() const
Definition TypeBase.h:9000
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:725
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2137
bool isRValueReferenceType() const
Definition TypeBase.h:8657
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:8728
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9158
bool isArrayType() const
Definition TypeBase.h:8724
bool isCharType() const
Definition Type.cpp:2157
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9063
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2374
bool isPointerType() const
Definition TypeBase.h:8625
bool isArrayParameterType() const
Definition TypeBase.h:8740
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9035
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2617
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
bool isEnumeralType() const
Definition TypeBase.h:8756
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2120
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8825
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9113
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2193
bool isExtVectorBoolType() const
Definition TypeBase.h:8772
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8812
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2798
bool isLValueReferenceType() const
Definition TypeBase.h:8653
bool isBitIntType() const
Definition TypeBase.h:8900
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2455
bool isAnyComplexType() const
Definition TypeBase.h:8760
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9051
bool isHalfType() const
Definition TypeBase.h:8995
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8973
bool isQueueT() const
Definition TypeBase.h:8881
bool isMemberPointerType() const
Definition TypeBase.h:8706
bool isObjCIdType() const
Definition TypeBase.h:8837
bool isMatrixType() const
Definition TypeBase.h:8788
bool isOverflowBehaviorType() const
Definition TypeBase.h:8796
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9134
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2516
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8873
bool isBFloat16Type() const
Definition TypeBase.h:9012
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2479
bool isFunctionType() const
Definition TypeBase.h:8621
bool isObjCObjectPointerType() const
Definition TypeBase.h:8804
bool isVectorType() const
Definition TypeBase.h:8764
bool isObjCClassType() const
Definition TypeBase.h:8843
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2357
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2638
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2929
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8948
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:2284
bool isAnyPointerType() const
Definition TypeBase.h:8633
TypeClass getTypeClass() const
Definition TypeBase.h:2391
bool isSamplerT() const
Definition TypeBase.h:8869
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:654
bool isNullPtrType() const
Definition TypeBase.h:9028
bool isRecordType() const
Definition TypeBase.h:8752
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1430
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:5133
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1406
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3391
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3460
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:4127
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4235
QualType getBaseType() const
Definition ExprCXX.h:4209
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4219
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4200
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4245
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4239
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:641
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:4198
QualType getElementType() const
Definition TypeBase.h:4197
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:236
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:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
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:61
@ 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:859
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:887
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:896
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:879
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:883
@ 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:924
@ ovl_fail_too_few_arguments
Definition Overload.h:861
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:903
@ ovl_fail_too_many_arguments
Definition Overload.h:860
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:911
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:892
@ ovl_fail_bad_deduction
Definition Overload.h:863
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:907
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:916
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:900
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:868
@ Comparison
A comparison.
Definition Sema.h:667
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1788
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1791
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1794
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:221
@ ICR_Conversion
Conversion.
Definition Overload.h:235
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:247
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:257
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:263
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:250
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:238
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:244
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:260
@ ICR_Promotion
Promotion.
Definition Overload.h:229
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:223
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:254
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:232
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:1045
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:929
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
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:208
@ 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:205
@ 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:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ 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_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ 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:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
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:587
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:216
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
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:150
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:274
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:311
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:307
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:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
@ 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:1519
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
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:5928
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:448
__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:522
ConversionSet::const_iterator const_iterator
Definition Overload.h:558
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:523
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:549
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:607
QualType getFromType() const
Definition Overload.h:606
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:1102
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
Extra information about a function prototype.
Definition TypeBase.h:5400
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5405
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1195
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:1217
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1244
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1206
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1208
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1234
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:998
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:989
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1063
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1037
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1002
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:979
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:947
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:943
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:938
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1010
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:959
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:973
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1028
unsigned getNumParams() const
Definition Overload.h:1076
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1006
unsigned TookAddressOfOverload
Definition Overload.h:992
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1019
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
DeductionFailureInfo DeductionFailure
Definition Overload.h:1022
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:951
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1033
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10573
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10580
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13165
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13253
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13299
Abstract class used to diagnose incomplete types.
Definition Sema.h:8309
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:477
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:489
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:511
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:502
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:497
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:516
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.